File size: 5,373 Bytes
3afc63f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Build test sets at a fixed clue count, for a like-for-like comparison.

Our own benchmark is made of *minimal* puzzles, so its clue count is whatever
minimality happens to leave (21-28, mean 24.3). The NCM paper instead defines
difficulty by a fixed clue count: 40 easy, 35 medium, 30 hard. Comparing a
model trained at 30 clues against a test set at 24 confounds architecture with
distribution shift, so this script generates sets at their clue counts using
the same solution sampler and the same uniqueness guarantee as our generator.

The difference from `src/gen_hard_sudoku.py` is only the stopping rule: cells
are removed until the target clue count is reached rather than until nothing
more can be removed. Uniqueness is still re-verified after every removal, so
board accuracy stays well defined.

    python ncm/make_clue_sets.py --clues 30 --n 1000 --out data/sudoku_c30

Pass --train_sol to assert the new set shares no solution with our training
split, including under digit relabelling.
"""
import argparse
import os
import sys
import time
from functools import partial
from multiprocessing import Pool
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from gen_hard_sudoku import CELLS, canon, count_solutions, random_solution  # noqa: E402
from gen_hard_sudoku import make_one as make_minimal  # noqa: E402


def make_one(seed, clues):
    """One puzzle with exactly `clues` givens, unique at every step.

    Returns (puzzle, solution) or None if this grid could not be thinned that
    far while staying unique, which the caller retries with another seed.
    """
    rng = np.random.default_rng(seed)
    sol = random_solution(rng)
    g = sol.copy()
    order = rng.permutation(CELLS)
    remaining = CELLS

    for i in order:
        if remaining <= clues:
            break
        keep = g[i]
        g[i] = 0
        if count_solutions(g, 2) == 1:
            remaining -= 1
        else:
            g[i] = keep

    return (g, sol) if remaining == clues else None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--clues", type=int, default=0, help="givens per puzzle, e.g. 30")
    ap.add_argument("--minimal", action="store_true",
                    help="generate minimal puzzles instead, as the project's own test set is "
                         "built; clue count then falls where it falls and is reported")
    ap.add_argument("--n", type=int, default=1000, help="puzzles to produce")
    ap.add_argument("--out", required=True)
    ap.add_argument("--split", default="test", help="file prefix, e.g. test -> test_puz.npy")
    ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
    ap.add_argument("--seed0", type=int, default=0,
                    help="first worker seed. 0 means 1,000,000 x clues: src/gen_hard_sudoku.py "
                         "drew the training and test splits from seeds 0..100,999 with the same "
                         "solution sampler, so low seeds regenerate training solutions exactly")
    ap.add_argument("--train_sol", default="", help="training solutions to check against")
    a = ap.parse_args()

    if a.minimal == bool(a.clues):
        raise SystemExit("pass either --clues N or --minimal, not both and not neither")
    if a.clues and not 17 <= a.clues <= 60:
        raise SystemExit("--clues outside the sensible range 17-60")

    if a.seed0 == 0:
        a.seed0 = 1_000_000 * (a.clues or 1)
    worker = make_minimal if a.minimal else partial(make_one, clues=a.clues)

    t0 = time.time()
    got, seed, batch = [], a.seed0, max(a.n, 64)
    with Pool(a.workers) as pool:
        while len(got) < a.n:
            seeds = range(seed, seed + batch)
            seed += batch
            for r in pool.map(worker, seeds, chunksize=4):
                if r is not None:
                    got.append(r)
            print(f"  {len(got)}/{a.n} after {time.time() - t0:.0f}s", flush=True)

    got = got[:a.n]
    P = np.stack([g for g, _ in got]).astype(np.uint8)
    S = np.stack([s for _, s in got]).astype(np.uint8)

    counts = (P > 0).sum(1)
    if a.minimal:
        hist = {int(c): int((counts == c).sum()) for c in sorted(set(counts))}
        print(f"clues: min={counts.min()} max={counts.max()} mean={counts.mean():.1f}  {hist}")
    else:
        assert counts.min() == counts.max() == a.clues, f"clue counts drifted: {sorted(set(counts))}"

    # every puzzle must still admit exactly one solution
    bad = sum(count_solutions(P[i], 2) != 1 for i in range(0, len(P), 25))
    assert bad == 0, f"{bad} sampled puzzles are not unique"

    # the solutions themselves must be distinct, up to digit relabelling
    canon_sols = {canon(s) for s in S}
    print(f"distinct solutions up to relabelling: {len(canon_sols)}/{len(S)}")

    if a.train_sol:
        tr = {canon(s) for s in np.load(a.train_sol)}
        leak = sum(canon(s) in tr for s in S)
        print(f"solutions also in training (up to relabelling): {leak}")
        assert leak == 0, "leakage against the training split"

    os.makedirs(a.out, exist_ok=True)
    np.save(os.path.join(a.out, f"{a.split}_puz.npy"), P)
    np.save(os.path.join(a.out, f"{a.split}_sol.npy"), S)
    print(f"saved {P.shape} puzzles to {a.out} in {time.time() - t0:.0f}s")


if __name__ == "__main__":
    main()