File size: 2,756 Bytes
0040de1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""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()