"""Extract every FEN from a Stockfish .plain file. This replaces filter_plain.py for consumers that want positions rather than Stockfish NNUE training samples. filter_plain.py drops any position holding castling rights that did not arise from a standard opening, because Stockfish cannot train on Chess960 castling. Nothing here is dropped by default: the positions are the product, and which ones to keep is the caller's decision. Chess960 positions are recognised and counted, and can be excluded with --standard-only. They are reported either way, so the composition of the output is never silent. """ from __future__ import annotations import argparse import gzip import sys from pathlib import Path # Shredder-FEN castling fields name the rook files, so anything outside KQkq is # a Chess960 game. lc0's test80 run mixes a small share of them into self-play. STANDARD_CASTLING = set("KQkq-") def is_chess960(fen: str) -> bool: field = fen.split(" ")[2] return not set(field) <= STANDARD_CASTLING def opened(path: Path, mode: str): if path.suffix == ".gz": return gzip.open(path, mode + "t", encoding="utf-8") return open(path, mode, encoding="utf-8") def convert(source: Path, destination: Path, standard_only: bool) -> dict[str, int]: counts = {"positions": 0, "chess960": 0, "written": 0} with opened(source, "r") as infile, opened(destination, "w") as outfile: for row in infile: if not row.startswith("fen "): continue fen = row[4:].strip() counts["positions"] += 1 frc = is_chess960(fen) counts["chess960"] += frc if standard_only and frc: continue counts["written"] += 1 outfile.write(fen + "\n") return counts def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=Path, help="a .plain or .plain.gz file") parser.add_argument("-o", "--output", type=Path) parser.add_argument( "--standard-only", action="store_true", help="drop Chess960 positions instead of keeping them", ) args = parser.parse_args() destination = args.output if destination is None: stem = args.input.name.replace(".plain.gz", "").replace(".plain", "") destination = args.input.with_name(stem + ".fen") counts = convert(args.input, destination, args.standard_only) print( f"{args.input} -> {destination}\n" f" positions read: {counts['positions']:,}\n" f" chess960: {counts['chess960']:,}\n" f" written: {counts['written']:,}", file=sys.stderr, ) if __name__ == "__main__": main()