Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / chess / generate_puzzles.py

generate_puzzles.py278 lines · 9.3 KiBRaw
1#!/usr/bin/env python3
2"""Generate the compact `puzzles.dat` asset for the Chess app's Puzzles mode.
3
4Source: the Lichess puzzle database CSV (`lichess_db_puzzle.csv.zst`, ~6M rows),
5whose columns are:
6
7 PuzzleId,FEN,Moves,Rating,RatingDeviation,Popularity,NbPlays,Themes,GameUrl,OpeningTags
8
9Shipping all ~6M puzzles is infeasible, so we keep only the highest-`Popularity`
10puzzles spread evenly across rating bands, and store just the three fields the
11app needs (FEN, Moves, Rating) in a tight custom binary blob.
12
13Selection: 200-point rating bands over 400..2799 (12 bands). Within each band we
14keep the top `ceil(TARGET / 12)` rows by Popularity, so difficulty is balanced.
15All bands 400..2799 are densely populated in the source (each has 130k-880k
16rows), so no redistribution is needed; any short band simply contributes fewer.
17
18Binary format (`puzzles.dat`, little-endian) — kept in sync with the Kotlin
19loader in `PuzzleRepository` / `Board.fromPuzzle`:
20
21 Header:
22 4 bytes magic "CPZ1"
23 4 bytes uint32 count (N puzzles)
24 Per-puzzle record (variable length), written sorted by rating ascending:
25 32 bytes board: one nibble per square, square index s = row*8 + col
26 (row 0 = rank 8, col 0 = file a). Byte b holds square 2b in its
27 low nibble and 2b+1 in its high nibble. Nibble 0 = empty; else
28 bits0-2 = type (1=K,2=Q,3=R,4=B,5=N,6=P), bit3 = color (0=w,1=b).
29 1 byte flags: bit0 = side-to-move (0=white,1=black);
30 bits1-4 = castling rights KQkq (bit1=K,bit2=Q,bit3=k,bit4=q)
31 1 byte enPassantSquare (0..63, or 0xFF = none)
32 2 bytes uint16 rating
33 1 byte moveCount (M, full solution incl. the opponent's setup move)
34 2*M bytes each move uint16: bits0-5 fromSq, bits6-11 toSq,
35 bits12-14 promo (0=none,1=Q,2=R,3=B,4=N)
36
37Usage:
38 python3 generate_puzzles.py [input.csv.zst] [output.bin]
39
40Defaults: input ~/Documents/lichess_db_puzzle.csv.zst, output
41Modern-Apps/games/chess/src/main/assets/puzzles.dat (both overridable via argv).
42"""
43from __future__ import annotations
44
45import csv
46import heapq
47import math
48import os
49import struct
50import subprocess
51import sys
52
53# Repo layout: scripts/chess/generate_puzzles.py -> repo root is two levels up.
54REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
55DEFAULT_INPUT = os.path.expanduser("~/Documents/lichess_db_puzzle.csv.zst")
56DEFAULT_OUTPUT = os.path.join(
57 REPO_ROOT, "games", "chess", "src", "main", "assets", "puzzles.dat"
58)
59
60MAGIC = b"CPZ1"
61TARGET_TOTAL = 50000
62BAND_MIN = 400
63BAND_MAX = 2800 # exclusive upper edge; bands cover 400..2799
64BAND_SIZE = 200
65NUM_BANDS = (BAND_MAX - BAND_MIN) // BAND_SIZE # 12
66PER_BAND = math.ceil(TARGET_TOTAL / NUM_BANDS) # 4167
67
68# FEN piece letter -> (type, color). type: 1=K,2=Q,3=R,4=B,5=N,6=P; color 0=w,1=b.
69_TYPE_OF = {"k": 1, "q": 2, "r": 3, "b": 4, "n": 5, "p": 6}
70_PROMO_OF = {"q": 1, "r": 2, "b": 3, "n": 4}
71
72
73def band_index(rating: int) -> int:
74 """Band for a rating, or -1 if outside the kept range."""
75 if rating < BAND_MIN or rating >= BAND_MAX:
76 return -1
77 return (rating - BAND_MIN) // BAND_SIZE
78
79
80def parse_fen(fen: str):
81 """FEN -> (board[64] nibbles, side_to_move, castling_bits, ep_square)."""
82 placement, side, castling, ep = fen.split()[:4]
83
84 board = [0] * 64
85 row = 0
86 col = 0
87 for ch in placement:
88 if ch == "/":
89 row += 1
90 col = 0
91 elif ch.isdigit():
92 col += int(ch)
93 else:
94 typ = _TYPE_OF[ch.lower()]
95 color = 0 if ch.isupper() else 1
96 board[row * 8 + col] = typ | (color << 3)
97 col += 1
98
99 stm = 0 if side == "w" else 1
100
101 cbits = 0
102 if "K" in castling:
103 cbits |= 1
104 if "Q" in castling:
105 cbits |= 2
106 if "k" in castling:
107 cbits |= 4
108 if "q" in castling:
109 cbits |= 8
110
111 if ep == "-":
112 ep_sq = 0xFF
113 else:
114 f = ord(ep[0]) - ord("a")
115 r = int(ep[1])
116 ep_sq = (8 - r) * 8 + f
117
118 return board, stm, cbits, ep_sq
119
120
121def parse_move(uci: str) -> int:
122 """UCI move (e.g. 'e2e4' or 'e7e8q') -> packed uint16."""
123 ffile = ord(uci[0]) - ord("a")
124 frank = int(uci[1])
125 tfile = ord(uci[2]) - ord("a")
126 trank = int(uci[3])
127 from_sq = (8 - frank) * 8 + ffile
128 to_sq = (8 - trank) * 8 + tfile
129 promo = _PROMO_OF[uci[4]] if len(uci) >= 5 else 0
130 return from_sq | (to_sq << 6) | (promo << 12)
131
132
133def encode_record(fen: str, moves: str, rating: int) -> bytes:
134 board, stm, cbits, ep_sq = parse_fen(fen)
135 move_list = moves.split()
136
137 out = bytearray(32)
138 for b in range(32):
139 out[b] = board[2 * b] | (board[2 * b + 1] << 4)
140
141 flags = stm | (cbits << 1)
142 out.append(flags)
143 out.append(ep_sq)
144 out += struct.pack("<H", rating)
145 out.append(len(move_list))
146 for uci in move_list:
147 out += struct.pack("<H", parse_move(uci))
148 return bytes(out)
149
150
151def select_puzzles(input_path: str):
152 """Stream the CSV, keeping the top-PER_BAND rows by popularity in each band.
153
154 Returns a list of (rating, encoded_record_bytes) for all kept puzzles.
155 Uses one bounded min-heap per band so memory stays O(NUM_BANDS * PER_BAND).
156 """
157 # heap entries are (popularity, seq, fen, moves, rating); seq is a unique
158 # tiebreaker so heapq never has to compare the string payloads.
159 heaps = [[] for _ in range(NUM_BANDS)]
160 seq = 0
161 total_rows = 0
162
163 proc = subprocess.Popen(
164 ["zstd", "-dc", input_path],
165 stdout=subprocess.PIPE,
166 text=True,
167 )
168 try:
169 reader = csv.reader(proc.stdout)
170 header = next(reader) # discard header row
171 # Column indices (guard against future column reordering).
172 i_fen = header.index("FEN")
173 i_moves = header.index("Moves")
174 i_rating = header.index("Rating")
175 i_pop = header.index("Popularity")
176
177 for fields in reader:
178 total_rows += 1
179 try:
180 rating = int(fields[i_rating])
181 except (ValueError, IndexError):
182 continue
183 bi = band_index(rating)
184 if bi < 0:
185 continue
186 try:
187 pop = int(fields[i_pop])
188 except ValueError:
189 continue
190
191 h = heaps[bi]
192 entry = (pop, seq, fields[i_fen], fields[i_moves], rating)
193 seq += 1
194 if len(h) < PER_BAND:
195 heapq.heappush(h, entry)
196 elif pop > h[0][0]:
197 heapq.heapreplace(h, entry)
198 finally:
199 if proc.stdout:
200 proc.stdout.close()
201 proc.wait()
202
203 if proc.returncode not in (0, None):
204 raise RuntimeError(f"zstd exited with code {proc.returncode}")
205
206 kept = []
207 band_counts = []
208 for bi, h in enumerate(heaps):
209 band_counts.append(len(h))
210 for pop, _seq, fen, moves, rating in h:
211 kept.append((rating, encode_record(fen, moves, rating)))
212
213 return kept, band_counts, total_rows
214
215
216def write_blob(output_path: str, kept):
217 kept.sort(key=lambda x: x[0]) # ascending rating -> bands contiguous
218 os.makedirs(os.path.dirname(output_path), exist_ok=True)
219 with open(output_path, "wb") as f:
220 f.write(MAGIC)
221 f.write(struct.pack("<I", len(kept)))
222 for _rating, rec in kept:
223 f.write(rec)
224
225
226def self_check(output_path: str, expected_count: int):
227 """Re-read the header and decode the first and last records as a sanity test."""
228 with open(output_path, "rb") as f:
229 data = f.read()
230 assert data[:4] == MAGIC, "bad magic"
231 (count,) = struct.unpack_from("<I", data, 4)
232 assert count == expected_count, f"count mismatch: {count} != {expected_count}"
233
234 def decode_at(off):
235 # Returns (next_offset, rating, move_count).
236 rating = struct.unpack_from("<H", data, off + 34)[0]
237 mcount = data[off + 36]
238 return off + 37 + 2 * mcount, rating, mcount
239
240 off = 8
241 next_off, first_rating, first_moves = decode_at(off)
242 assert first_moves >= 1, "first record has no moves"
243 # Walk to the last record to confirm the whole blob parses cleanly.
244 last_rating = first_rating
245 for _ in range(count):
246 next_off, last_rating, mcount = decode_at(off)
247 assert mcount >= 1, "record with no moves"
248 off = next_off
249 assert off == len(data), f"trailing bytes: parsed to {off} of {len(data)}"
250 return first_rating, last_rating
251
252
253def main():
254 input_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_INPUT
255 output_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OUTPUT
256
257 if not os.path.exists(input_path):
258 print(f"Error: input not found: {input_path}", file=sys.stderr)
259 sys.exit(1)
260
261 print(f"Reading {input_path} ...")
262 kept, band_counts, total_rows = select_puzzles(input_path)
263 print(f"Scanned {total_rows:,} rows; kept {len(kept):,} puzzles.")
264 print("Per-band counts (band lo -> kept):")
265 for bi, c in enumerate(band_counts):
266 lo = BAND_MIN + bi * BAND_SIZE
267 print(f" {lo:>4}-{lo + BAND_SIZE - 1:<4}: {c:>6,}")
268
269 write_blob(output_path, kept)
270 size = os.path.getsize(output_path)
271 print(f"Wrote {output_path} ({size:,} bytes, {size / (1024 * 1024):.2f} MB)")
272
273 first_rating, last_rating = self_check(output_path, len(kept))
274 print(f"Self-check OK: first rating {first_rating}, last rating {last_rating}")
275
276
277if __name__ == "__main__":
278 main()