colordle-solver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ """Colordle solver: narrows down the daily color from your guesses' scores."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .color import ciede2000, rgb_to_lab, score
6
+ from .solver import Solver, load_colors
7
+
8
+ __all__ = ["Solver", "load_colors", "score", "ciede2000", "rgb_to_lab", "__version__"]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,181 @@
1
+ """
2
+ Play a full game against every color in the list (or a sample) and report
3
+ how many guesses the solver needs: average, spread, worst, and best colors.
4
+
5
+ Results are written to a CSV as they come in, so a long run can be stopped
6
+ with Ctrl+C and continued later by running the same command again/
7
+ """
8
+ import csv
9
+ import multiprocessing as mp
10
+ import os
11
+ import signal
12
+ import sys
13
+ import time
14
+ from collections import Counter
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ from .color import score
20
+ from .solver import Solver
21
+
22
+ MAX_TURNS = 30 # a game that reaches this counts as unsolved
23
+ FIELDS = ["name", "hex", "guesses", "solved"]
24
+
25
+
26
+ def play(solver, answer, seed=None, max_turns=MAX_TURNS):
27
+ """Play one game with a known answer. Returns (guesses used, solved?)."""
28
+ solver.reset(seed)
29
+ for turn in range(1, max_turns + 1):
30
+ g = solver.suggest()
31
+ if g == answer:
32
+ return turn, True
33
+ # The game shows scores to 2 decimal places
34
+ observed = round(float(score(solver.labs[g], solver.labs[[answer]])[0]), 2)
35
+ solver.record(g, observed)
36
+ if len(solver.alive) == 0:
37
+ break # shouldn't happen; counts as unsolved
38
+ return turn, False
39
+
40
+
41
+ # worker processes: each builds the solver once, then plays many games
42
+ _worker = None
43
+
44
+
45
+ def _init_worker(names, hexes, opener, tolerance):
46
+ global _worker
47
+ # Let the main process handle Ctrl+C, so workers don't each print a traceback
48
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
49
+ _worker = Solver(names, hexes, tolerance=tolerance)
50
+ _worker.opener = opener
51
+
52
+
53
+ def _play_one(answer):
54
+ turns, solved = play(_worker, answer, seed=answer) # seed = answer: repeatable
55
+ return answer, turns, solved
56
+
57
+
58
+ def read_results(path):
59
+ """Rows already in the CSV, keyed by color name."""
60
+ path = Path(path)
61
+ if not path.exists():
62
+ return {}
63
+ with open(path, newline="", encoding="utf-8") as f:
64
+ return {r["name"]: r for r in csv.DictReader(f)}
65
+
66
+
67
+ def summarise(rows, opener_name, top=10):
68
+ """Text summary of a list of result rows."""
69
+ if not rows:
70
+ return "No results yet."
71
+ guesses = np.array([int(r["guesses"]) for r in rows])
72
+ unsolved = [r for r in rows if r["solved"] != "True"]
73
+ lines = [
74
+ f"Colors tested: {len(rows):,}",
75
+ f"Average guesses: {guesses.mean():.3f}",
76
+ f"Median guesses: {np.median(guesses):g}",
77
+ f"Unsolved: {len(unsolved)} (gave up after {MAX_TURNS} guesses)",
78
+ "",
79
+ "Guesses needed:",
80
+ ]
81
+ counts = Counter(guesses.tolist())
82
+ biggest = max(counts.values())
83
+ for k in sorted(counts):
84
+ bar = "#" * max(1, round(40 * counts[k] / biggest))
85
+ lines.append(f" {k:>2} {counts[k]:>6,} {100 * counts[k] / len(rows):5.1f}% {bar}")
86
+
87
+ ordered = sorted(rows, key=lambda r: (-int(r["guesses"]), r["name"].lower()))
88
+ lines += ["", f"Worst {min(top, len(rows))} colors:"]
89
+ lines += [f" {int(r['guesses']):>2} {r['name']} ({r['hex']})" for r in ordered[:top]]
90
+
91
+ others = [r for r in rows if r["name"] != opener_name]
92
+ if others:
93
+ fewest = min(int(r["guesses"]) for r in others)
94
+ best = sorted((r for r in others if int(r["guesses"]) == fewest),
95
+ key=lambda r: r["name"].lower())
96
+ lines += ["", f"Best: {opener_name} takes 1 guess (it's the opening guess). "
97
+ f"After that, {len(best):,} color(s) take {fewest}, e.g.:"]
98
+ lines += [f" {r['name']} ({r['hex']})" for r in best[:top]]
99
+ return "\n".join(lines)
100
+
101
+
102
+ def run(names, hexes, out="benchmark.csv", sample=None, workers=None,
103
+ tolerance=0.6, fresh=False, seed=0, progress=True):
104
+ """
105
+ Benchmark the solver. Returns the summary text.
106
+
107
+ sample: only test this many randomly chosen colors (None = all of them)
108
+ workers: processes to use (default: all CPU cores; 1 = no extra processes)
109
+ fresh: ignore and overwrite an existing results file instead of resuming
110
+ """
111
+ out = Path(out)
112
+ solver = Solver(names, hexes, tolerance=tolerance)
113
+ opener = solver.opening_guess() # cached; worked out once if needed
114
+ opener_name = str(solver.names[opener])
115
+
116
+ answers = np.arange(len(names))
117
+ if sample:
118
+ answers = np.sort(np.random.default_rng(seed).choice(
119
+ len(names), min(sample, len(names)), replace=False))
120
+
121
+ if fresh and out.exists():
122
+ out.unlink()
123
+ done = read_results(out)
124
+ todo = [int(a) for a in answers if names[a] not in done]
125
+ if done:
126
+ print(f"Resuming: {len(done):,} colors already in {out}, {len(todo):,} to go.")
127
+ workers = max(1, workers or os.cpu_count() or 1)
128
+ if todo:
129
+ print(f"Playing {len(todo):,} games on {workers} worker(s). "
130
+ "Press Ctrl+C to stop; run again to continue.")
131
+
132
+ new_file = not out.exists()
133
+ f = open(out, "a", newline="", encoding="utf-8")
134
+ writer = csv.DictWriter(f, fieldnames=FIELDS)
135
+ if new_file:
136
+ writer.writeheader()
137
+
138
+ pool = None
139
+ start, finished, total_guesses = time.time(), 0, 0
140
+ try:
141
+ if workers == 1:
142
+ _init_worker(names, hexes, opener, tolerance)
143
+ results = map(_play_one, todo)
144
+ else:
145
+ pool = mp.Pool(workers, initializer=_init_worker,
146
+ initargs=(names, hexes, opener, tolerance))
147
+ results = pool.imap_unordered(_play_one, todo, chunksize=20)
148
+
149
+ last_print = 0.0
150
+ for answer, turns, solved in results:
151
+ writer.writerow({"name": names[answer], "hex": hexes[answer],
152
+ "guesses": turns, "solved": solved})
153
+ finished += 1
154
+ total_guesses += turns
155
+ now = time.time()
156
+ if progress and (now - last_print > 0.5 or finished == len(todo)):
157
+ last_print = now
158
+ rate = finished / (now - start)
159
+ eta = (len(todo) - finished) / rate if rate else 0
160
+ # The first few results come in unevenly, so wait before guessing an ETA
161
+ eta_text = (f"ETA {int(eta // 60)}m {int(eta % 60):02d}s"
162
+ if now - start > 5 else "ETA ...")
163
+ print(f"\r {finished:,}/{len(todo):,} "
164
+ f"({100 * finished / len(todo):.0f}%) "
165
+ f"avg {total_guesses / finished:.2f} {eta_text} ",
166
+ end="", file=sys.stderr, flush=True)
167
+ f.flush()
168
+ if progress and todo:
169
+ print(file=sys.stderr)
170
+ except KeyboardInterrupt:
171
+ print(f"\nStopped after {finished:,} new games. Run the same command "
172
+ "again to continue.", file=sys.stderr)
173
+ finally:
174
+ f.close()
175
+ if pool is not None:
176
+ pool.terminate()
177
+ pool.join()
178
+
179
+ wanted = {names[a] for a in answers}
180
+ rows = [r for r in read_results(out).values() if r["name"] in wanted]
181
+ return summarise(rows, opener_name)
colordle_solver/cli.py ADDED
@@ -0,0 +1,117 @@
1
+ """Command-line interface: `colordle` or `python -m colordle_solver`."""
2
+ import argparse
3
+ import json
4
+
5
+ import numpy as np
6
+
7
+ from . import __version__
8
+ from .benchmark import play, run as run_benchmark
9
+ from .color import hex_to_rgb, rgb_to_lab, score
10
+ from .solver import Solver, default_list_source, load_colors
11
+
12
+
13
+ def interactive(solver):
14
+ print(f"{len(solver.alive)} possible colors.")
15
+ print("After each guess, type the % score the game gave (e.g. 72.4).")
16
+ print("To report your OWN guess instead, type: Color Name = 72.4\n")
17
+ while True:
18
+ s = solver.suggest()
19
+ print(f"Suggested guess: {solver.names[s]} ({solver.hexes[s]}) "
20
+ f"[{len(solver.alive)} left]")
21
+ line = input("> ").strip()
22
+ if not line:
23
+ continue
24
+ if "=" in line:
25
+ name, val = line.rsplit("=", 1)
26
+ g = solver.lookup(name)
27
+ if g is None:
28
+ print(" Unknown color name, try again.")
29
+ continue
30
+ else:
31
+ g, val = s, line
32
+ try:
33
+ val = float(val.strip().rstrip("%"))
34
+ except ValueError:
35
+ print(" Couldn't read that score, try again.")
36
+ continue
37
+ if val >= 100:
38
+ print(f"Solved: {solver.names[g]}!")
39
+ return
40
+ solver.record(g, val)
41
+ if len(solver.alive) == 0:
42
+ print("No colors fit those scores. Check the numbers you typed, or "
43
+ "raise --tolerance.")
44
+ return
45
+ if len(solver.alive) <= 10:
46
+ print(" Still possible:", ", ".join(solver.remaining))
47
+
48
+
49
+ def simulate(names, hexes, games, seed, tolerance):
50
+ rng = np.random.default_rng(seed)
51
+ s = Solver(names, hexes, tolerance=tolerance)
52
+ turns = []
53
+ for _ in range(games):
54
+ answer = int(rng.integers(len(names)))
55
+ t, solved = play(s, answer, seed=int(rng.integers(1 << 31)))
56
+ turns.append(t)
57
+ note = "" if solved else " (gave up)"
58
+ print(f"answer={names[answer]!r:40} solved in {t} guesses{note}")
59
+ print(f"\naverage {np.mean(turns):.2f}, worst {max(turns)}")
60
+
61
+
62
+ def calibrate(names, hexes, path):
63
+ """
64
+ Compare predicted scores with a real game. GAME.json looks like:
65
+ {"answer": "Fairy Tale", "guesses": [["Sky Blue", 41.2], ["Mint", 66.9]]}
66
+ """
67
+ with open(path, encoding="utf-8") as f:
68
+ data = json.load(f)
69
+ idx = {n.lower(): i for i, n in enumerate(names)}
70
+ labs = rgb_to_lab(hex_to_rgb(hexes))
71
+ a = idx[data["answers"].lower()]
72
+ for name, real in data["guesses"]:
73
+ pred = float(score(labs[idx[name.lower()]], labs[[a]])[0])
74
+ print(f"{name:30} game={real:6.2f} predicted={pred:6.2f} diff{pred - real:+.2f}")
75
+
76
+
77
+ def main(argv=None):
78
+ p = argparse.ArgumentParser(prog="colordle", description="Colordle solver")
79
+ p.add_argument("colors", nargs="?",
80
+ help="color list file (default: the list from colordle-update "
81
+ "if you've run it, otherwise the bundled one")
82
+ p.add_argument("--bundled", action="store_true",
83
+ help="use the list shipped with the package, ignoring any update")
84
+ p.add_argument("--simulate", type=int, metavar="N", help="play N random games")
85
+ p.add_argument("--benchmark", action="store_true",
86
+ help="play a game for every color and report the result")
87
+ p.add_argument("--sample", type=int, metavar="N",
88
+ help="with --benchmark: only test N random colors")
89
+ p.add_argument("--workers", type=int, metavar="N",
90
+ help="with --benchmark: processes to use (default: all CPU cores)")
91
+ p.add_argument("--out", default="benchmark.csv", metavar="FILE",
92
+ help="with --benchmark: results file (default: benchmark.csv)")
93
+ p.add_argument("--fresh", action="store_true",
94
+ help="with --benchmark: start over instead of resuming")
95
+ p.add_argument("--calibrate", metavar="GAME.json", help="check scores from a real game")
96
+ p.add_argument("--tolerance", type=float, default=0.6)
97
+ p.add_argument("--seed", type=int, default=None)
98
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
99
+ args = p.parse_args(argv)
100
+
101
+ source = args.colors or default_list_source(args.bundled)
102
+ names, hexes = load_colors(source)
103
+ print(f"Using color list: {source}")
104
+ if args.calibrate:
105
+ calibrate(names, hexes, args.calibrate)
106
+ elif args.benchmark:
107
+ print()
108
+ print(run_benchmark(names, hexes, out=args.out, sample=args.sample,
109
+ workers=args.workers, tolerance=args.tolerance,
110
+ fresh=args.fresh, seed=args.seed or 0))
111
+ elif args.simulate:
112
+ simulate(names, hexes, args.simulate, args.seed, args.tolerance)
113
+ else:
114
+ try:
115
+ interactive(Solver(names, hexes, tolerance=args.tolerance, seed=args.seed))
116
+ except (KeyboardInterrupt, EOFError):
117
+ print()
@@ -0,0 +1,58 @@
1
+ """Color conversion and the Colordle scoring formula."""
2
+ import numpy as np
3
+
4
+
5
+ def hex_to_rgb(hexes):
6
+ return np.array([[int(h[i:i + 2], 16) for i in (1, 3, 5)] for h in hexes], float) / 255
7
+
8
+
9
+ def rgb_to_lab(rgb):
10
+ """sRGB (0-1) -> CIELAB (D65)."""
11
+ lin = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
12
+ m = np.array([[0.4124564, 0.3575761, 0.1804375],
13
+ [0.2126729, 0.7151522, 0.0721750],
14
+ [0.0193339, 0.1191920, 0.9503041]])
15
+ xyz = lin @ m.T / np.array([0.95047, 1.0, 1.08883])
16
+ f = np.where(xyz > 216 / 24389, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)
17
+ return np.stack([116 * f[:, 1] - 16,
18
+ 500 * (f[:, 0] - f[:, 1]),
19
+ 200 * (f[:, 1] - f[:, 2])], axis=1)
20
+
21
+
22
+ def ciede2000(lab1, lab2):
23
+ """Delta E 2000 between one color (lab1, shape (3,)) and many (lab2, shape (n,3))."""
24
+ L1, a1, b1 = lab1
25
+ L2, a2, b2 = lab2[:, 0], lab2[:, 1], lab2[:, 2]
26
+ C1, C2 = np.hypot(a1, b1), np.hypot(a2, b2)
27
+ Cb7 = ((C1 + C2) / 2) ** 7
28
+ G = 0.5 * (1 - np.sqrt(Cb7 / (Cb7 + 25 ** 7)))
29
+ a1p, a2p = a1 * (1 + G), a2 * (1 + G)
30
+ C1p, C2p = np.hypot(a1p, b1), np.hypot(a2p, b2)
31
+ h1p = np.degrees(np.arctan2(b1, a1p)) % 360
32
+ h2p = np.degrees(np.arctan2(b2, a2p)) % 360
33
+ dLp, dCp = L2 - L1, C2p - C1p
34
+ dh = h2p - h1p
35
+ dh = np.where(dh > 180, dh - 360, np.where(dh < -180, dh + 360, dh))
36
+ dh = np.where(C1p * C2p == 0, 0, dh)
37
+ dHp = 2 * np.sqrt(C1p * C2p) * np.sin(np.radians(dh / 2))
38
+ Lbp, Cbp = (L1 + L2) / 2, (C1p + C2p) / 2
39
+ hs = h1p + h2p
40
+ hbp = np.where(np.abs(h1p - h2p) > 180, np.where(hs < 360, hs + 360, hs - 360), hs) / 2
41
+ hbp = np.where(C1p * C2p == 0, hs, hbp)
42
+ T = (1 - 0.17 * np.cos(np.radians(hbp - 30)) + 0.24 * np.cos(np.radians(2 * hbp))
43
+ + 0.32 * np.cos(np.radians(3 * hbp + 6)) - 0.20 * np.cos(np.radians(4 * hbp - 63)))
44
+ SL = 1 + 0.015 * (Lbp - 50) ** 2 / np.sqrt(20 + (Lbp - 50) ** 2)
45
+ SC, SH = 1 + 0.045 * Cbp, 1 + 0.015 * Cbp * T
46
+ Cbp7 = Cbp ** 7
47
+ RT = (-2 * np.sqrt(Cbp7 / (Cbp7 + 25 ** 7))
48
+ * np.sin(np.radians(60 * np.exp(-(((hbp - 275) / 25) ** 2)))))
49
+ return np.sqrt((dLp / SL) ** 2 + (dCp / SC) ** 2 + (dHp / SH) ** 2
50
+ + RT * (dCp / SC) * (dHp / SH))
51
+
52
+
53
+ def score(guess_lab, cand_labs):
54
+ """
55
+ Predicted Colordle score for a guess against each candidate.
56
+ Matches the game's own code: Math.abs(100 - DeltaE.getDeltaE00(lab1, lab2))
57
+ """
58
+ return np.abs(100 - ciede2000(guess_lab, cand_labs))
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 David Aerne
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.