colordle-solver 0.1.0__tar.gz
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.
- colordle_solver-0.1.0/.gitattributes +2 -0
- colordle_solver-0.1.0/.github/workflows/publish.yml +60 -0
- colordle_solver-0.1.0/.github/workflows/tests.yml +38 -0
- colordle_solver-0.1.0/.gitignore +33 -0
- colordle_solver-0.1.0/LICENSE +21 -0
- colordle_solver-0.1.0/PKG-INFO +88 -0
- colordle_solver-0.1.0/README.md +68 -0
- colordle_solver-0.1.0/pyproject.toml +37 -0
- colordle_solver-0.1.0/scripts/build_openers.py +24 -0
- colordle_solver-0.1.0/src/colordle_solver/__init__.py +8 -0
- colordle_solver-0.1.0/src/colordle_solver/__main__.py +4 -0
- colordle_solver-0.1.0/src/colordle_solver/benchmark.py +181 -0
- colordle_solver-0.1.0/src/colordle_solver/cli.py +117 -0
- colordle_solver-0.1.0/src/colordle_solver/color.py +58 -0
- colordle_solver-0.1.0/src/colordle_solver/data/LICENSE-color-names +21 -0
- colordle_solver-0.1.0/src/colordle_solver/data/colornames.json +1 -0
- colordle_solver-0.1.0/src/colordle_solver/data/openers.json +3 -0
- colordle_solver-0.1.0/src/colordle_solver/solver.py +202 -0
- colordle_solver-0.1.0/src/colordle_solver/update.py +129 -0
- colordle_solver-0.1.0/tests/conftest.py +15 -0
- colordle_solver-0.1.0/tests/test_benchmark.py +67 -0
- colordle_solver-0.1.0/tests/test_color.py +20 -0
- colordle_solver-0.1.0/tests/test_opener.py +54 -0
- colordle_solver-0.1.0/tests/test_solver.py +48 -0
- colordle_solver-0.1.0/tests/test_update.py +116 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
# Runs when you publish a release on GitHub (Releases -> Draft a new release).
|
|
4
|
+
# Uses PyPI trusted publishing, so no password or API token is stored anywhere.
|
|
5
|
+
on:
|
|
6
|
+
release:
|
|
7
|
+
types: [published]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
name: Build and check
|
|
12
|
+
runs-on: ubuntu-24.04
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v5
|
|
15
|
+
|
|
16
|
+
- uses: actions/setup-python@v6
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.14"
|
|
19
|
+
|
|
20
|
+
- name: Run tests
|
|
21
|
+
run: |
|
|
22
|
+
python -m pip install -e ".[test]"
|
|
23
|
+
python -m pytest
|
|
24
|
+
|
|
25
|
+
- name: Check the release tag matches the package version
|
|
26
|
+
run: |
|
|
27
|
+
VERSION=$(python -c "import colordle_solver; print(colordle_solver.__version__)")
|
|
28
|
+
TAG="${GITHUB_REF_NAME#v}"
|
|
29
|
+
if [ "$VERSION" != "$TAG" ]; then
|
|
30
|
+
echo "::error::Release tag is $GITHUB_REF_NAME but __version__ is $VERSION. Update __init__.py or retag."
|
|
31
|
+
exit 1
|
|
32
|
+
fi
|
|
33
|
+
|
|
34
|
+
- name: Build wheel and source archive
|
|
35
|
+
run: |
|
|
36
|
+
python -m pip install build twine
|
|
37
|
+
python -m build
|
|
38
|
+
python -m twine check --strict dist/*
|
|
39
|
+
|
|
40
|
+
- uses: actions/upload-artifact@v6
|
|
41
|
+
with:
|
|
42
|
+
name: dist
|
|
43
|
+
path: dist/
|
|
44
|
+
|
|
45
|
+
publish:
|
|
46
|
+
name: Upload to PyPI
|
|
47
|
+
needs: build
|
|
48
|
+
runs-on: ubuntu-24.04
|
|
49
|
+
environment:
|
|
50
|
+
name: pypi
|
|
51
|
+
url: https://pypi.org/project/colordle-solver/
|
|
52
|
+
permissions:
|
|
53
|
+
id-token: write # lets PyPI confirm the upload comes from this workflow
|
|
54
|
+
steps:
|
|
55
|
+
- uses: actions/download-artifact@v6
|
|
56
|
+
with:
|
|
57
|
+
name: dist
|
|
58
|
+
path: dist/
|
|
59
|
+
|
|
60
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
name: Tests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
pull_request:
|
|
6
|
+
workflow_dispatch: # adds a "Run workflow" button on the Actions tab
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
name: ${{ matrix.os }} / Python ${{ matrix.python }}
|
|
11
|
+
runs-on: ${{ matrix.os }}
|
|
12
|
+
strategy:
|
|
13
|
+
fail-fast: false # finish every combination even if one fails
|
|
14
|
+
matrix:
|
|
15
|
+
# ubuntu-24.04 rather than ubuntu-latest: the newer Ubuntu image only has
|
|
16
|
+
# recent Python builds, so older versions like 3.9 fail to install there.
|
|
17
|
+
os: [ubuntu-24.04, windows-latest]
|
|
18
|
+
python: ["3.9", "3.14"] # oldest supported and newest
|
|
19
|
+
|
|
20
|
+
steps:
|
|
21
|
+
- uses: actions/checkout@v5
|
|
22
|
+
|
|
23
|
+
- uses: actions/setup-python@v6
|
|
24
|
+
with:
|
|
25
|
+
python-version: ${{ matrix.python }}
|
|
26
|
+
cache: pip
|
|
27
|
+
|
|
28
|
+
- name: Install package and test dependencies
|
|
29
|
+
run: python -m pip install -e ".[test]"
|
|
30
|
+
|
|
31
|
+
- name: Run tests
|
|
32
|
+
run: python -m pytest -v
|
|
33
|
+
|
|
34
|
+
- name: Check the package builds
|
|
35
|
+
if: matrix.os == 'ubuntu-24.04' && matrix.python == '3.14'
|
|
36
|
+
run: |
|
|
37
|
+
python -m pip install build
|
|
38
|
+
python -m build
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Python bytecode cache (created whenever the code runs)
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
|
|
5
|
+
# Build and install output
|
|
6
|
+
build/
|
|
7
|
+
dist/
|
|
8
|
+
*.egg-info/
|
|
9
|
+
|
|
10
|
+
# Virtual environments
|
|
11
|
+
.venv/
|
|
12
|
+
venv/
|
|
13
|
+
env/
|
|
14
|
+
|
|
15
|
+
# Test and tool caches
|
|
16
|
+
.pytest_cache/
|
|
17
|
+
.coverage
|
|
18
|
+
htmlcov/
|
|
19
|
+
.mypy_cache/
|
|
20
|
+
.ruff_cache/
|
|
21
|
+
|
|
22
|
+
# Colour lists downloaded by hand (the bundled one in src/ is still tracked)
|
|
23
|
+
/colors-api.json
|
|
24
|
+
/colornames.json
|
|
25
|
+
|
|
26
|
+
# Editor / OS files
|
|
27
|
+
.vscode/
|
|
28
|
+
.idea/
|
|
29
|
+
.DS_Store
|
|
30
|
+
Thumbs.db
|
|
31
|
+
|
|
32
|
+
# Benchmark results (colordle --benchmark)
|
|
33
|
+
benchmark*.csv
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joseph Butcher
|
|
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.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: colordle-solver
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Suggests guesses for the Colordle colour game from your previous scores
|
|
5
|
+
Project-URL: Homepage, https://github.com/joebutc/colordle_solver
|
|
6
|
+
Project-URL: Issues, https://github.com/joebutc/colordle_solver/issues
|
|
7
|
+
Author-email: Joseph Butcher <joebutch06@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ciede2000,color,colordle,game,solver
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Games/Entertainment :: Puzzle Games
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Requires-Dist: numpy
|
|
17
|
+
Provides-Extra: test
|
|
18
|
+
Requires-Dist: pytest; extra == 'test'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# colordle-solver
|
|
22
|
+
|
|
23
|
+
Suggests guesses for [Colordle](https://colordle.ryantanen.com/) based on the scores your earlier guesses got.
|
|
24
|
+
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
Colordle scores a guess as `|100 − ΔE2000|`, where ΔE2000 is the CIEDE2000 color difference. The solver starts with every color in the list. After each guess it drops any color that would not have produced the score you saw, then suggests the guess expected to leave the fewest colors. Most games take 3 to 6 guesses.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
pip install . # or: pip install -e ".[test]" for development
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Use
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
colordle # play along: type each score the game gives you
|
|
39
|
+
colordle --simulate 20 # test on random answers
|
|
40
|
+
colordle --calibrate game.json # compare predicted scores with a real game
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Gettting the latest color list
|
|
44
|
+
|
|
45
|
+
The package ships with a copy of the list. To download the newest one from the color-name API:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
colordle-update # saves it to your user data folder
|
|
49
|
+
colordle # now uses the downloaded list automatically
|
|
50
|
+
colordle --bundled # go back to the shipped list for one run
|
|
51
|
+
colordle-update -o mylist.json # or save it somewhere else and pass it in
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The downloaded lists is saved to `%LOCALAPPDATA%\colordle-solver\colornames.json` on Windows and `~/.local/share/colordle-solver/colornames.json` elsewhere. Delete that file to go back to the bundled list for good. If a download fails, your existing list is left as it was.
|
|
55
|
+
|
|
56
|
+
To report a guess you chose yourself, type `Color Name = 72.4`.
|
|
57
|
+
|
|
58
|
+
From Python:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from colordle_solver import Solver
|
|
62
|
+
|
|
63
|
+
s = Solver.from_bundled()
|
|
64
|
+
g = s.suggest()
|
|
65
|
+
s.record(g, 63.2)
|
|
66
|
+
print(s.remaining[:10])
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Benchmark
|
|
70
|
+
|
|
71
|
+
Play a game against every color in the list and see how the solver does:
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
colordle --benchmark # every color (about 10-40 minutes, depending on CPU)
|
|
75
|
+
colordle --benchmark --sample 1000 # a quick estimate from 1,000 random colors
|
|
76
|
+
colordle --benchmark --workers 4 # limit how many CPU cores it uses
|
|
77
|
+
colordle --benchmark --fresh # start over instead of resuming
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
It prints the average and median number of guesses, how many games took each number of guesses, and the worst and best colors. Every result is saved to `benchmark.csv` as it finishes (change with `--out`), so you can open it in a spreadsheet. If you stop a run with Ctrl+C, the same command picks up where it left off. Use `--fresh` after changing the solver, otherwise old results get mixed with new ones.
|
|
81
|
+
|
|
82
|
+
## Opening guess
|
|
83
|
+
|
|
84
|
+
The best first guess is the same every day for a given list, so it is worked out once and cached. The bundled list's opener (Cosmic Void) ships in `data/openers.json`, and `colordle-update` works out the opener for each list it downloads. If you replace the bundled list, run `python scripts/build_openers.py` (about 40 seconds) to regenerate it. A test fails if you forget.
|
|
85
|
+
|
|
86
|
+
## Credits
|
|
87
|
+
|
|
88
|
+
The color list comes from [meodai/color-names](https://github.com/meodai/color-names) (MIT licence, © 2017 David Aerne). Its licence is in `src/colordle_solver/data/LICENSE-color-names`.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# colordle-solver
|
|
2
|
+
|
|
3
|
+
Suggests guesses for [Colordle](https://colordle.ryantanen.com/) based on the scores your earlier guesses got.
|
|
4
|
+
|
|
5
|
+
## How it works
|
|
6
|
+
|
|
7
|
+
Colordle scores a guess as `|100 − ΔE2000|`, where ΔE2000 is the CIEDE2000 color difference. The solver starts with every color in the list. After each guess it drops any color that would not have produced the score you saw, then suggests the guess expected to leave the fewest colors. Most games take 3 to 6 guesses.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
pip install . # or: pip install -e ".[test]" for development
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
colordle # play along: type each score the game gives you
|
|
19
|
+
colordle --simulate 20 # test on random answers
|
|
20
|
+
colordle --calibrate game.json # compare predicted scores with a real game
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Gettting the latest color list
|
|
24
|
+
|
|
25
|
+
The package ships with a copy of the list. To download the newest one from the color-name API:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
colordle-update # saves it to your user data folder
|
|
29
|
+
colordle # now uses the downloaded list automatically
|
|
30
|
+
colordle --bundled # go back to the shipped list for one run
|
|
31
|
+
colordle-update -o mylist.json # or save it somewhere else and pass it in
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The downloaded lists is saved to `%LOCALAPPDATA%\colordle-solver\colornames.json` on Windows and `~/.local/share/colordle-solver/colornames.json` elsewhere. Delete that file to go back to the bundled list for good. If a download fails, your existing list is left as it was.
|
|
35
|
+
|
|
36
|
+
To report a guess you chose yourself, type `Color Name = 72.4`.
|
|
37
|
+
|
|
38
|
+
From Python:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from colordle_solver import Solver
|
|
42
|
+
|
|
43
|
+
s = Solver.from_bundled()
|
|
44
|
+
g = s.suggest()
|
|
45
|
+
s.record(g, 63.2)
|
|
46
|
+
print(s.remaining[:10])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Benchmark
|
|
50
|
+
|
|
51
|
+
Play a game against every color in the list and see how the solver does:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
colordle --benchmark # every color (about 10-40 minutes, depending on CPU)
|
|
55
|
+
colordle --benchmark --sample 1000 # a quick estimate from 1,000 random colors
|
|
56
|
+
colordle --benchmark --workers 4 # limit how many CPU cores it uses
|
|
57
|
+
colordle --benchmark --fresh # start over instead of resuming
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
It prints the average and median number of guesses, how many games took each number of guesses, and the worst and best colors. Every result is saved to `benchmark.csv` as it finishes (change with `--out`), so you can open it in a spreadsheet. If you stop a run with Ctrl+C, the same command picks up where it left off. Use `--fresh` after changing the solver, otherwise old results get mixed with new ones.
|
|
61
|
+
|
|
62
|
+
## Opening guess
|
|
63
|
+
|
|
64
|
+
The best first guess is the same every day for a given list, so it is worked out once and cached. The bundled list's opener (Cosmic Void) ships in `data/openers.json`, and `colordle-update` works out the opener for each list it downloads. If you replace the bundled list, run `python scripts/build_openers.py` (about 40 seconds) to regenerate it. A test fails if you forget.
|
|
65
|
+
|
|
66
|
+
## Credits
|
|
67
|
+
|
|
68
|
+
The color list comes from [meodai/color-names](https://github.com/meodai/color-names) (MIT licence, © 2017 David Aerne). Its licence is in `src/colordle_solver/data/LICENSE-color-names`.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling >= 1.26"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "colordle-solver"
|
|
7
|
+
keywords = ["colordle", "solver", "color", "game", "ciede2000"]
|
|
8
|
+
dynamic = ["version"]
|
|
9
|
+
authors = [
|
|
10
|
+
{ name="Joseph Butcher", email="joebutch06@gmail.com" },
|
|
11
|
+
]
|
|
12
|
+
description = "Suggests guesses for the Colordle colour game from your previous scores"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
requires-python = ">=3.9"
|
|
15
|
+
dependencies = ["numpy"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Environment :: Console",
|
|
20
|
+
"Topic :: Games/Entertainment :: Puzzle Games",
|
|
21
|
+
]
|
|
22
|
+
license = "MIT"
|
|
23
|
+
license-files = ["LICEN[CS]E*"]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
test = ["pytest"]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
colordle = "colordle_solver.cli:main"
|
|
30
|
+
colordle-update = "colordle_solver.update:main"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.version]
|
|
33
|
+
path = "src/colordle_solver/__init__.py"
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/joebutc/colordle_solver"
|
|
37
|
+
Issues = "https://github.com/joebutc/colordle_solver/issues"
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Regenerate src/colordle_solver/data/openers.json for the bundled color list.
|
|
3
|
+
|
|
4
|
+
Run this after replacing the bundled colornames.json, or after changing the
|
|
5
|
+
scoring or OPENER_CACHE_VERSION, so new installs get an instant first guess:
|
|
6
|
+
|
|
7
|
+
python scripts/build_openers.py
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from colordle_solver.solver import Solver, load_colors
|
|
14
|
+
|
|
15
|
+
out = Path(__file__).resolve().parent.parent / "src" / "colordle_solver" / "data" / "openers.json"
|
|
16
|
+
|
|
17
|
+
s = Solver(*load_colors(bundled=True))
|
|
18
|
+
start = time.time()
|
|
19
|
+
best = s.compute_opening_guess()
|
|
20
|
+
print(f"Opening guess: {s.names[best]} ({s.hexes[best]}), took {time.time() - start:.0f}s")
|
|
21
|
+
|
|
22
|
+
with open(out, "w", encoding="utf-8") as f:
|
|
23
|
+
json.dump({s.fingerprint: str(s.names[best])}, f, ensure_ascii=False, indent=1)
|
|
24
|
+
print(f"Saved to {out}")
|
|
@@ -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,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)
|