From 20d102427072b1902c0508867bc095844e1b8cb9 Mon Sep 17 00:00:00 2001 From: Christopher Junius Date: Sun, 30 Aug 2026 08:56:40 -0400 Subject: [PATCH 1/8] Restructure engine, package as src/pychess, and add tooling ## Search: composition instead of a mixin stack `NegamaxEngine` was one class fused from seven mixins via the MRO, with collaborators communicating through `self` and hook-method overrides. That was fragile (alphabetising the base list silently disabled the TT), untestable in pieces, and required no-op stub hooks on the base. - `Negamax` now takes an evaluator, move orderer, transposition table, and clock as constructor arguments. Quiescence folds into it. - `TranspositionTable` and `SharedTT` share a real `key`/`probe`/`store` interface; the searcher is handed whichever one. - `Clock` replaces the `_can_abort`/`_deadline`/`_stop_flag` attribute-poking. - `lazy_smp.search` returns a `SearchResult`; all UCI `info`/`bestmove` formatting moved to the UCI layer. The engine never prints. - The single-process search path is gone: `go` always runs Lazy SMP. - Score/flag constants centralised in `constants.py`. ## Packaging: src/pychess layout - `pyproject.toml` (hatchling) replaces `requirements.txt` and `pytest.ini`; version single-sourced from `__init__.py`. - `pychess` console entry point; `python -m pychess` also works. - `py.typed`; `GoLimits` TypedDict; `SupportsSearch` protocol. - License changed to Apache-2.0. ## Tooling - Ruff (lint + format), Mypy (strict on `src/`), pytest-cov with an 85% gate - all run in CI on Python 3.12 and 3.13, mirrored by pre-commit. - CI: `permissions`, `concurrency`, SHA-pinned actions, a `ci-ok` aggregate job to gate branch protection on, and a Codecov upload step. - Coverage is 92% (80 tests, up from 22); every module has a `test_.py`. ## Docs and repo hygiene - Deleted the legacy `archive/` tree and unused evaluation mixins. - README rewritten; deep reference lists moved to `docs/design.md`. `docs/` files lowercased; `STRENGTH.md` -> `docs/engine-strength.md`. - Added CONTRIBUTING, CHANGELOG, SECURITY, CODE_OF_CONDUCT, .editorconfig, .gitattributes, dependabot, issue/PR templates, `opening_book/README.md`. - `CLAUDE.md` + `AGENTS.md` symlink; skills in `.claude/skills/` (`update-docs`, `bench`, `pr-check`, `release`). Co-Authored-By: Claude Sonnet 5 --- .claude/skills/bench/SKILL.md | 86 ++ .claude/skills/pr-check/SKILL.md | 54 ++ .claude/skills/release/SKILL.md | 85 ++ .claude/skills/update-docs/SKILL.md | 79 ++ .editorconfig | 18 + .gitattributes | 8 + .github/ISSUE_TEMPLATE/bug_report.yml | 35 + .github/ISSUE_TEMPLATE/config.yml | 8 + .github/ISSUE_TEMPLATE/feature_request.yml | 26 + .github/PULL_REQUEST_TEMPLATE.md | 19 + .github/dependabot.yml | 14 + .github/workflows/ci.yml | 67 ++ .gitignore | 173 +--- .pre-commit-config.yaml | 19 + AGENTS.md | 1 + CHANGELOG.md | 38 + CLAUDE.md | 53 ++ CODE_OF_CONDUCT.md | 83 ++ CONTRIBUTING.md | 50 + LICENSE | 876 ++++-------------- README.md | 338 ++----- SECURITY.md | 29 + archive/__init__.py | 1 - archive/config.py | 31 - archive/evaluation.py | 137 --- archive/helper.py | 20 - archive/move_ordering.py | 103 -- archive/negamax.py | 111 --- archive/pyChess.py | 101 -- archive/quiescence_search.py | 56 -- archive/src/evaluation.py | 42 - archive/src/helpers.py | 32 - archive/src/limits.py | 8 - archive/src/psqt.py | 81 -- archive/src/search.py | 357 ------- archive/src/tt.py | 78 -- archive/test/puzzles.py | 171 ---- archive/test/test_evaluation.py | 25 - archive/test/test_puzzles.py | 55 -- archive/test/test_quiescence_search.py | 45 - archive/transposition_table.py | 40 - build.bat | 1 - codecov.yml | 18 + docs/design.md | 63 ++ STRENGTH.md => docs/engine-strength.md | 4 +- docs/performance.md | 52 ++ docs/tasks.md | 96 ++ engines.py | 19 - main.py | 208 ----- opening_book/README.md | 32 + parallel.py | 243 ----- pyproject.toml | 101 ++ pytest.ini | 2 - requirements.txt | 2 - search.py | 185 ---- src/pychess/__init__.py | 3 + src/pychess/__main__.py | 180 ++++ src/pychess/clock.py | 70 ++ src/pychess/constants.py | 20 + src/pychess/engine.py | 33 + eval_board.py => src/pychess/eval_board.py | 27 +- evaluation.py => src/pychess/evaluation.py | 173 +--- src/pychess/lazy_smp.py | 162 ++++ .../pychess/move_ordering.py | 53 +- src/pychess/negamax.py | 170 ++++ perft.py => src/pychess/perft.py | 21 +- .../test/__init__.py => src/pychess/py.typed | 0 shared_tt.py => src/pychess/shared_tt.py | 64 +- src/pychess/transposition.py | 55 ++ src/pychess/types.py | 17 + tests/__init__.py | 0 tests/test_clock.py | 51 + tests/test_engine.py | 61 ++ tests/test_evaluation.py | 26 + tests/test_move_ordering.py | 47 + tests/test_negamax.py | 69 ++ {test => tests}/test_perft.py | 3 +- tests/test_transposition.py | 62 ++ tests/test_uci.py | 147 +++ transposition.py | 74 -- 80 files changed, 2727 insertions(+), 3540 deletions(-) create mode 100644 .claude/skills/bench/SKILL.md create mode 100644 .claude/skills/pr-check/SKILL.md create mode 100644 .claude/skills/release/SKILL.md create mode 100644 .claude/skills/update-docs/SKILL.md create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .pre-commit-config.yaml create mode 120000 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CLAUDE.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md delete mode 100644 archive/__init__.py delete mode 100644 archive/config.py delete mode 100644 archive/evaluation.py delete mode 100644 archive/helper.py delete mode 100644 archive/move_ordering.py delete mode 100644 archive/negamax.py delete mode 100644 archive/pyChess.py delete mode 100644 archive/quiescence_search.py delete mode 100644 archive/src/evaluation.py delete mode 100644 archive/src/helpers.py delete mode 100644 archive/src/limits.py delete mode 100644 archive/src/psqt.py delete mode 100644 archive/src/search.py delete mode 100644 archive/src/tt.py delete mode 100644 archive/test/puzzles.py delete mode 100644 archive/test/test_evaluation.py delete mode 100644 archive/test/test_puzzles.py delete mode 100644 archive/test/test_quiescence_search.py delete mode 100644 archive/transposition_table.py delete mode 100644 build.bat create mode 100644 codecov.yml create mode 100644 docs/design.md rename STRENGTH.md => docs/engine-strength.md (97%) create mode 100644 docs/performance.md create mode 100644 docs/tasks.md delete mode 100644 engines.py delete mode 100644 main.py create mode 100644 opening_book/README.md delete mode 100644 parallel.py create mode 100644 pyproject.toml delete mode 100644 pytest.ini delete mode 100644 requirements.txt delete mode 100644 search.py create mode 100644 src/pychess/__init__.py create mode 100644 src/pychess/__main__.py create mode 100644 src/pychess/clock.py create mode 100644 src/pychess/constants.py create mode 100644 src/pychess/engine.py rename eval_board.py => src/pychess/eval_board.py (76%) rename evaluation.py => src/pychess/evaluation.py (52%) create mode 100644 src/pychess/lazy_smp.py rename move_ordering.py => src/pychess/move_ordering.py (63%) create mode 100644 src/pychess/negamax.py rename perft.py => src/pychess/perft.py (75%) rename archive/test/__init__.py => src/pychess/py.typed (100%) rename shared_tt.py => src/pychess/shared_tt.py (68%) create mode 100644 src/pychess/transposition.py create mode 100644 src/pychess/types.py create mode 100644 tests/__init__.py create mode 100644 tests/test_clock.py create mode 100644 tests/test_engine.py create mode 100644 tests/test_evaluation.py create mode 100644 tests/test_move_ordering.py create mode 100644 tests/test_negamax.py rename {test => tests}/test_perft.py (96%) create mode 100644 tests/test_transposition.py create mode 100644 tests/test_uci.py delete mode 100644 transposition.py diff --git a/.claude/skills/bench/SKILL.md b/.claude/skills/bench/SKILL.md new file mode 100644 index 0000000..0c726b4 --- /dev/null +++ b/.claude/skills/bench/SKILL.md @@ -0,0 +1,86 @@ +--- +name: bench +description: > + Run the search benchmarks and regenerate the tables in docs/performance.md + with fresh, real numbers. Use when the user asks to "run the benchmarks", + "update performance numbers", or after a change that should affect speed. +--- + +# bench + +`docs/performance.md` must only ever contain **measured** numbers. This skill +produces them; never hand-edit timings. + +## 1. Environment + +```bash +pip install -e ".[dev]" +python -c "import platform, os; print(platform.processor() or platform.machine(), os.cpu_count(), 'cores'); print(platform.python_version())" +``` + +Record the machine and Python version - the tables in `docs/performance.md` +are labelled with them and results are machine-specific. + +## 2. Fixed-depth single-process search (start position) + +Regenerates the "After" column of the "Single process, fixed-depth `search()`" +table. A fresh `Negamax` per depth (cold TT), un-armed clock so it never aborts. +"Nodes" is `searcher.nodes` (main search + quiescence). + +```python +import time +from pychess.clock import Clock +from pychess.constants import INF +from pychess.eval_board import EvalBoard +from pychess.evaluation import PestoEvaluator +from pychess.move_ordering import MoveOrderer +from pychess.negamax import Negamax +from pychess.transposition import TranspositionTable + +for depth in range(2, 8): + s = Negamax(PestoEvaluator(), MoveOrderer(), TranspositionTable(), Clock()) + t = time.time() + s.search(EvalBoard(), -INF, INF, depth) + print(f"| {depth} | {time.time() - t:.3f}s / {s.nodes:,} |") +``` + +## 3. Lazy SMP (start position) + +Regenerates the "After" column of the "What `go` runs today: Lazy SMP" table. +Use a generous `movetime` so the run isn't deadline-capped. + +```python +import time +from pychess.eval_board import EvalBoard +from pychess.engine import Engine + +for depth in (6, 7, 8): + t = time.time() + r = Engine().search(EvalBoard(), {"depth": depth, "movetime": 120000}) + print(f"| {depth} | reached d{r.depth} | {time.time() - t:.2f}s | {r.nodes:,} nodes |") +``` + +Run each script with `.venv/bin/python` (or the active env). Steps 2 and 3 +together take roughly a minute. + +## 4. Update `docs/performance.md` + +- Replace the "After (time / nodes)" cells in the fixed-depth table and the + Lazy SMP table with the new numbers. +- Update the machine / Python-version sentence at the top of the file. +- **Leave alone:** the "Before" columns (pre-review engine, not reproducible), + the M1 reference paragraph, and the "Single-process iterative deepening + (removed)" table. +- Recompute the "speed-up" column from the new numbers. + +## 5. Cross-check + +If speed changed materially, check whether these still hold and flag (don't +silently rewrite) any that drifted: + +- the `~45-50k nps` figure and the "depth ~6-8 in blitz" notes in + `docs/engine-strength.md`. + +## 6. Report + +Show the old vs new table rows and the environment they were measured on. diff --git a/.claude/skills/pr-check/SKILL.md b/.claude/skills/pr-check/SKILL.md new file mode 100644 index 0000000..71a704d --- /dev/null +++ b/.claude/skills/pr-check/SKILL.md @@ -0,0 +1,54 @@ +--- +name: pr-check +description: > + Run the full CI gate locally and check the softer PR requirements (tests, + changelog, docs) against the diff. Use before opening or updating a pull + request, or when the user asks to "check my PR" / "am I ready to push". +--- + +# pr-check + +Mirror what CI and review will check, and report a pass/fail list matching +`.github/PULL_REQUEST_TEMPLATE.md`. Stop at the first hard failure and show its +output. + +## 1. Hard gate (same as CI, in order) + +```bash +pip install -e ".[dev]" +ruff check . +ruff format --check . +mypy +pytest +``` + +- `ruff check` / `ruff format --check` - style. If it fails, `ruff check --fix` + and `ruff format` fix most of it. +- `mypy` - strict on `src/`. New public functions need full annotations. +- `pytest` - all tests pass and coverage stays >= 85% (the run fails the build + otherwise). `pytest` also runs with `filterwarnings = ["error"]`, so a new + warning is a failure. + +## 2. Soft checks against the diff + +```bash +git fetch origin main +git diff --stat origin/main...HEAD +git diff origin/main...HEAD +``` + +Then verify: + +| Check | How | +|---|---| +| Tests for the change | `src/` behaviour changed -> a matching `tests/test_.py` change is in the diff. New module -> new test file. | +| Changelog | `CHANGELOG.md` has a new bullet under `## [Unreleased]`. | +| Docs | the diff touches something `README.md` or `docs/` describes (a module, a UCI command, the layout, an architecture claim, a feature list). If so, those files are updated - run `/update-docs` if not. | +| No stray debug | no leftover `print(...)` in `src/` outside `__main__.py`, no commented-out code, no `# type: ignore` without a reason. | +| Public API typed | any new function/method in `src/` has argument and return annotations (mypy strict enforces this, but confirm). | + +## 3. Report + +Produce the checklist from the PR template with each item marked pass / fail / +n/a, plus a one-line note on anything that needs the author's attention. If +everything passes, say so and give the branch name for the PR. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..19820bf --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,85 @@ +--- +name: release +description: > + Cut a new release: bump the version, roll the changelog, run the full gate, + commit, and tag. Use when the user asks to "cut a release", "tag a version", + or "release vX.Y.Z". +--- + +# release + +The version is single-sourced from `src/pychess/__init__.py` (`__version__`); +`pyproject.toml` reads it via `[tool.hatch.version]`. Do **not** edit the +version anywhere else. + +## 1. Preconditions + +```bash +git status # working tree must be clean +git fetch && git status # branch must not be behind its upstream +git log -1 --format='%H %s' # note the commit being released +``` + +- Be on `main` (or a `release/*` branch the user names). +- The latest `main` CI run (`ci-ok`) must be green. If you can't verify it, ask. +- If the tree is dirty or the branch is behind, stop and tell the user. + +## 2. Choose the version + +Read `## [Unreleased]` in `CHANGELOG.md` and the current `__version__`. Pick the +next version by semver from what's in Unreleased: + +- breaking API / CLI change -> major +- new user-facing capability -> minor +- fixes / internal only -> patch + +Confirm the number with the user before writing anything. (For the very first +release, `__version__` may already equal the target.) + +## 3. Apply the changes + +1. Set `__version__` in `src/pychess/__init__.py` to `X.Y.Z`. +2. In `CHANGELOG.md`: + - rename `## [Unreleased]` to `## [X.Y.Z] - ` + - add a fresh empty `## [Unreleased]` section above it + - if Unreleased was empty, stop - there's nothing to release. + +Get today's date with `date +%F` (do not guess it). + +## 4. Verify + +```bash +pip install -e ".[dev]" +ruff check . && ruff format --check . && mypy && pytest +python -c "import pychess; print(pychess.__version__)" # == X.Y.Z +pip install . # throwaway build sanity check (in a temp venv if possible) +``` + +## 5. Commit and tag + +```bash +git add src/pychess/__init__.py CHANGELOG.md +git commit -m "chore(release): vX.Y.Z" +git tag -a vX.Y.Z -m "vX.Y.Z" +``` + +## 6. Hand off (do not push without the user's OK) + +Pushing and publishing are outward-facing. Print these for the user to run: + +```bash +git push origin --follow-tags +``` + +Then draft the GitHub Release from the `CHANGELOG.md` section for this version: + +```bash +gh release create vX.Y.Z --title "vX.Y.Z" --notes-file <(sed -n '/## \[X.Y.Z\]/,/## \[/p' CHANGELOG.md | sed '$d') +``` + +or paste that changelog section into the Release UI. + +## 7. Report + +State the new version, the files changed, the tag name, and the exact push / +release commands the user still needs to run. diff --git a/.claude/skills/update-docs/SKILL.md b/.claude/skills/update-docs/SKILL.md new file mode 100644 index 0000000..ebbabbe --- /dev/null +++ b/.claude/skills/update-docs/SKILL.md @@ -0,0 +1,79 @@ +--- +name: update-docs +description: > + Review the current changes and update README.md and every markdown file under + docs/ so the documentation matches the code. Use after implementing a feature, + refactor, or structural change, or when the user asks to "update the docs". +--- + +# update-docs + +Bring `README.md` and `docs/*.md` back in sync with the code. Only reflect +changes that are actually in the diff - never invent features or numbers. + +## 1. Find what changed + +Determine the review range: + +- If the user named a base (branch, tag, commit), diff against that. +- Else if the branch is not `main`, use `git diff main...HEAD` plus any + uncommitted changes (`git diff` / `git status`). +- Else review uncommitted changes only. + +```bash +git status +git diff ...HEAD +git diff # unstaged +``` + +Summarise, for yourself, what changed: new/removed/renamed modules, changed +public APIs or class names, new/changed UCI commands or `go` options, new CLI +entry points, dependency or Python-version changes, tooling changes, and any +behaviour change a user or contributor would notice. + +## 2. Read the current docs + +Read `README.md` and each file in `docs/` (currently `design.md`, +`engine-strength.md`, `performance.md`, `tasks.md`). Note their structure and +tone so edits blend in. + +## 3. Update each file where the diff touches it + +Match the existing style; make the smallest edit that makes the doc correct. + +| File | Update when the change affects... | +|---|---| +| `README.md` | the one-paragraph description, badges, quick-start commands, UCI usage, the repository-layout tree, or the development commands | +| `docs/design.md` | architecture (collaborators, coordinator, layers), the "Implemented" list, or the "Backlog" list | +| `docs/engine-strength.md` | evaluation/search features that move the estimate, or the calibration/time-control notes. **Do not change Elo numbers** unless the diff contains a measured result. | +| `docs/performance.md` | only when the diff includes fresh benchmark numbers. Never fabricate timings. | +| `docs/tasks.md` | a roadmap item was implemented (move it into "Recently completed" and delete it from the numbered list), or a housekeeping item was done | + +Also check: the repo-layout tree in `README.md` lists every `src/pychess/*.py` +module with a one-line description - add/rename/remove rows to match. + +Cross-references: if you rename or move a doc, fix every link to it in the other +docs and the README. + +## 4. Adjacent files (mention, don't silently skip) + +- `CLAUDE.md` - update the architecture map / gotchas if a module moved or a + convention changed. +- `CHANGELOG.md` - add a bullet under `## [Unreleased]`. This is outside the + skill's core scope; do it if it's clearly missing, otherwise flag it. + +## 5. Verify + +- Every relative link in the edited files resolves (`ls` the targets). +- Every shell command / code snippet shown in the docs still runs or matches + current config (`pyproject.toml`, `.github/workflows/ci.yml`). +- No stale references to removed names: + ```bash + git grep -nE 'removed_name_1|removed_name_2' -- '*.md' + ``` + +## 6. Report + +List each file you changed and the one-line reason, and each doc you +deliberately left alone. If a change needs numbers you can't derive (Elo, +benchmarks), say so and leave a clear TODO rather than guessing. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..aade86d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space + +[*.py] +indent_size = 4 +max_line_length = 100 + +[*.{yml,yaml,toml,json}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cd7b13f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto eol=lf + +*.bin binary +*.png binary +*.jpg binary + +docs/** linguist-documentation +opening_book/bookfish.bin linguist-vendored diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..74d5dd6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,35 @@ +name: Bug report +description: Something the engine does wrong or a crash. +labels: [bug] +body: + - type: textarea + id: what-happened + attributes: + label: What happened + description: What you expected vs. what actually happened. + validations: + required: true + - type: textarea + id: repro + attributes: + label: Steps to reproduce + description: > + The UCI commands you sent, or a FEN and `go` limits. A full transcript + (`position ... / go ...` and the engine's output) is ideal. + render: text + validations: + required: true + - type: input + id: version + attributes: + label: Version / commit + description: Output of `pip show pychess` or the commit SHA. + validations: + required: true + - type: input + id: python + attributes: + label: Python version and OS + placeholder: "3.12 on macOS 14 / 3.13 on Ubuntu 24.04" + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..e81d84f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Question or discussion + url: https://github.com/cjunius/pyChess/discussions + about: Ask usage questions or propose ideas here. + - name: Security vulnerability + url: https://github.com/cjunius/pyChess/security/advisories/new + about: Report security issues privately, not as a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..fecfd25 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,26 @@ +name: Feature request +description: A search / evaluation technique or a usability improvement. +labels: [enhancement] +body: + - type: textarea + id: proposal + attributes: + label: Proposal + description: What should the engine do, and roughly how? + validations: + required: true + - type: textarea + id: motivation + attributes: + label: Motivation + description: > + Expected benefit - Elo, speed, ergonomics. Link the relevant + Chess Programming Wiki page if there is one. + validations: + required: false + - type: checkboxes + id: roadmap + attributes: + label: Roadmap + options: + - label: I checked [docs/tasks.md](../blob/main/docs/tasks.md) and this isn't already listed. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..5a722db --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ +## Summary + + + +## Testing + + + +## Checklist + +With Claude Code, `/pr-check` runs the whole list below. + +- [ ] `ruff check .` and `ruff format --check .` pass +- [ ] `mypy` passes (strict on `src/`) +- [ ] `pytest` passes; coverage stays >= 85% +- [ ] Tests added or updated for the change +- [ ] `CHANGELOG.md` updated under `## [Unreleased]` +- [ ] `README.md` / `docs/*.md` updated if behaviour or structure changed (`/update-docs`) +- [ ] `docs/performance.md` refreshed if search speed changed (`/bench`) diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f2a4f9a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +version: 2 +updates: + - package-ecosystem: pip + directory: / + schedule: + interval: weekly + groups: + dev-tools: + patterns: ["ruff", "mypy", "pytest*"] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0472917 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,67 @@ +name: ci + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + - run: pip install -e ".[dev]" + - name: Ruff (lint) + run: ruff check . + - name: Ruff (format) + run: ruff format --check . + - name: Mypy + run: mypy + + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.12", "3.13"] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - run: pip install -e ".[dev]" + - name: Pytest + run: pytest --cov-report=xml + - name: Upload coverage to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: coverage.xml + flags: py${{ matrix.python-version }} + fail_ci_if_error: true + + # Single check to gate branch protection on, so the matrix can change freely. + ci-ok: + if: always() + needs: [lint, test] + runs-on: ubuntu-latest + steps: + - name: Verify lint and test succeeded + run: | + if [ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" = "true" ]; then + echo "A required job failed or was cancelled." + exit 1 + fi diff --git a/.gitignore b/.gitignore index 9a45fc0..5212704 100644 --- a/.gitignore +++ b/.gitignore @@ -1,166 +1,25 @@ -# Byte-compiled / optimized / DLL files +# Python __pycache__/ *.py[cod] -*$py.class - -# python virtual environment -pychess/** - -# C extensions -*.so - -# Distribution / packaging -.Python +*.egg-info/ build/ -develop-eggs/ dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/#use-with-ide -.pdm.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ +# Virtual environments +.venv/ venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site +env/ -# mypy +# Tooling caches +.ruff_cache/ .mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ +.pytest_cache/ +.coverage +htmlcov/ +coverage.xml -# VSCode -.vscode +# Editors / OS +.idea/ +.vscode/ +*.swp +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..74803bb --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,19 @@ +# Install once with: pre-commit install +# Keeps the same checks as CI. Keep the revs below in step with the dev pins in +# pyproject.toml (run `pre-commit autoupdate` and bump pyproject together). +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.14.4 + hooks: + - id: ruff-check + args: [--fix] + - id: ruff-format + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.18.2 + hooks: + - id: mypy + pass_filenames: false + additional_dependencies: + - chess==1.10.0 + - pytest==9.0.3 diff --git a/AGENTS.md b/AGENTS.md new file mode 120000 index 0000000..681311e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..323d527 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,38 @@ +# Changelog + +All notable changes to this project are documented here. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project aims to +follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Lazy SMP parallel search: one iterative-deepening worker per core sharing a + lock-free shared-memory transposition table. +- Tapered PeSTO evaluation with an incremental accumulator on `EvalBoard`. +- Check-aware, depth-bounded, fail-soft quiescence search. +- Zobrist-keyed transposition table with EXACT / LOWER / UPPER bounds. +- Move ordering: TT move, MVV-LVA captures, promotions, killers, history. +- UCI time management (`movetime`, clock + increment, `infinite`). +- Polyglot opening book support, overridable via `PYCHESS_BOOK`. +- Packaging: `src/pychess/` layout, `pyproject.toml`, `pychess` console script, + `py.typed`. +- Tooling: Ruff (lint + format), Mypy, pytest-cov (85% gate), `pre-commit`, all + run in CI on Python 3.12 and 3.13. +- `perft` regression tests against published node counts; unit tests for every + module. + +### Changed + +- Search rebuilt as composed collaborators (`Negamax` is handed an evaluator, + move orderer, TT, and clock) instead of a cooperative-multiple-inheritance + mixin stack. +- Engine layer no longer prints UCI protocol - `lazy_smp.search` returns a + `SearchResult` and `__main__` does all formatting. +- License changed to Apache-2.0. + +### Removed + +- The single-process search path; `go` always runs Lazy SMP. +- Legacy `archive/` tree and unused evaluation mixins. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..c86432c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,53 @@ +# Agent guide + +`pychess` is a UCI chess engine: Lazy SMP negamax with a tapered PeSTO +evaluation. `src/` layout, Python 3.12+. + +## Commands + +```bash +pip install -e ".[dev]" # required - tests import the installed package + +ruff check . # lint (also: ruff check --fix .) +ruff format . # format +mypy # strict on src/, relaxed for tests/ +pytest # tests + coverage; gate is 85% +``` + +All tool config lives in `pyproject.toml`. CI (`.github/workflows/ci.yml`) runs +exactly these on 3.12 and 3.13; `pre-commit` mirrors lint/format/type locally. + +Skills in `.claude/skills/`: `/pr-check`, `/update-docs`, `/bench`, `/release`. + +## Architecture + +- `negamax.py` - `Negamax`: fail-soft alpha-beta + quiescence. Takes an + evaluator, move orderer, TT, and clock as constructor args (composition, not + inheritance). Raises `SearchAbortError` when the clock says stop. +- `lazy_smp.py` - `search()` spawns one iterative-deepening `Negamax` per core + against a shared-memory TT (`SharedTT`) and returns a `SearchResult`. + `_worker` runs in a spawned subprocess. +- `transposition.py` / `shared_tt.py` - same `key`/`probe`/`store` interface; + in-process dict vs lock-free shared memory. +- `evaluation.py` + `eval_board.py` - PeSTO tables and an incremental + accumulator on `EvalBoard`. +- `__main__.py` - the UCI protocol loop and the ONLY place that prints + `info` / `bestmove`. The engine layer returns data, never prints. +- `clock.py`, `move_ordering.py`, `constants.py`, `types.py` - supporting bits. + +See `docs/design.md` for the full picture, `docs/tasks.md` for the roadmap. + +## Conventions & gotchas + +- **Don't hand-format.** `ruff format` owns layout. The piece-square-table + literals in `evaluation.py` are fenced with `# fmt: off` - leave them. +- `mypy` is `strict` for `src/`; annotate new public functions fully. +- One `tests/test_.py` per source module. New behaviour needs a test. +- `pytest` runs with `filterwarnings = ["error"]` - a new warning fails CI. +- The GitHub repo is `pyChess`, the package is `pychess`. On a case-insensitive + filesystem these collide; rename dirs via a temp name. +- `opening_book/bookfish.bin` is an 18 MB vendored binary - don't move or + regenerate it casually (see `opening_book/README.md`). +- Update `CHANGELOG.md` (`## [Unreleased]`) and `docs/` when behaviour changes. + +`AGENTS.md` is a symlink to this file. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6f69694 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,83 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers responsible for enforcement by opening a [private security advisory](https://github.com/cjunius/pyChess/security/advisories/new) or contacting @cjunius directly. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3c2264e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing + +## Setup + +```bash +python3.12 -m venv .venv && source .venv/bin/activate +pip install -e ".[dev]" +pre-commit install +``` + +## Before opening a PR + +The CI gate is: + +```bash +ruff check . +ruff format --check . +mypy +pytest # coverage must stay >= 85% +``` + +`pre-commit` runs the first three on every commit. All tool configuration lives +in `pyproject.toml`. + +## Claude Code skills + +Repo workflows are packaged as skills in `.claude/skills/`: + +| Skill | Does | +|---|---| +| `/pr-check` | runs the gate above + checks tests / changelog / docs against the diff | +| `/update-docs` | reviews the diff and updates `README.md` + `docs/*.md` | +| `/bench` | runs the search benchmarks and refreshes `docs/performance.md` | +| `/release` | bumps the version, rolls `CHANGELOG.md`, runs the gate, commits, tags | + +## Conventions + +- Python is formatted by `ruff format` (line length 100). Don't hand-format; + data tables that must keep a fixed layout are fenced with `# fmt: off`. +- `mypy` runs in `strict` mode on `src/`. Tests are checked too but don't + require annotations on the test functions themselves. +- One `tests/test_.py` per source module. New behaviour needs a test. +- Keep `docs/` in sync when behaviour changes, and add a `CHANGELOG.md` entry + under `## [Unreleased]` (see `/update-docs`). + +## Commit / PR + +- Branch off `main`; keep PRs focused. +- Reference an issue where one exists. +- Formatting-only changes go in their own commit, separate from logic changes. diff --git a/LICENSE b/LICENSE index f288702..dd43dd7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,202 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 cjunius + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 9957341..df984a0 100644 --- a/README.md +++ b/README.md @@ -1,250 +1,106 @@ -# pyChess +# pychess -UCI Python Chess Engine +[![ci](https://github.com/cjunius/pyChess/actions/workflows/ci.yml/badge.svg)](https://github.com/cjunius/pyChess/actions/workflows/ci.yml) +[![python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue)](pyproject.toml) +[![codecov](https://codecov.io/gh/cjunius/pyChess/branch/main/graph/badge.svg)](https://codecov.io/gh/cjunius/pyChess) +[![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) +[![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) -## Quick Start +A UCI chess engine in Python. `Negamax` (fail-soft alpha-beta with a +check-aware quiescence search) is the core; it takes an evaluator, a move +orderer, a transposition table, and a clock as constructor arguments. +`lazy_smp.search` runs one iterative-deepening `Negamax` per worker process +against a shared-memory transposition table and returns the deepest completed +line. Evaluation is PeSTO - tapered mid/endgame piece-square tables kept as an +incremental accumulator on the board. See [docs/design.md](docs/design.md) for +the full feature list and backlog. -Requires Python 3.12 +## Estimated Engine Strength + +Around **1800–2000 Elo** at blitz, most likely ~1900. This is a feature-based +estimate from the search and evaluation, **not a measured result** - no games +against rated opposition have been run yet. + +| Time control | Estimate | Why | +|---|---|---| +| Bullet (1+0) | ~1600–1750 | Python per-move overhead dominates. | +| Blitz (3+2 / 5+3) | ~1850–2000 | Reaches depth 6–8. | +| Rapid / Classical | ~2000–2150 | Reaches depth 9–10+; PeSTO scales well with depth. | +| Lichess bot pool | ~1950–2200 blitz | Bot ratings there tend to run higher than CCRL. | + +See [docs/engine-strength.md](docs/engine-strength.md) for how the number is +derived, calibration against known engines, and how to turn it into a measured +rating; [docs/performance.md](docs/performance.md) for search-speed benchmarks. + +## Quick start + +Requires Python 3.12+. ```bash git clone https://github.com/cjunius/pyChess.git cd pyChess -pip install -r requirements.txt -python main.py +pip install -e . # add ".[dev]" for the test / lint tools +pychess # UCI loop on stdin/stdout (also: python -m pychess) ``` -### UCI Commands - -- uci - - returns the ngine name, author, and "uciok" -- ucinewgame - - resets the chess board -- position [fen <%fen> | startpos] moves <%move1> ... <%moveN> - - sets the position of the chess board from a known fen or starting position -- isready - - returns "readyok" -- go [depth ] - - returns the next move with an optional search depth (default=5) -- quit - - exits the program - -#### Custom UCI Commands - -- perft <%depth> - returns the number of leaf nodes at the given depth (default=4) -- printBoard - - prints an ascii version of the board -- printLegalMoves - - returns the list of legal moves for the current position -- printMoveStack - - returns the list of moves in the board's move stack -- go_parallel [same args as `go`] - - returns the next move using Lazy SMP (multiple processes sharing a transposition table) - -## To Do - -The next five changes, in the order most likely to gain the most playing -strength. Each is a self-contained addition to `NegamaxMixin.search` / -`QuiescenceSearchMixin` unless noted. - -### 1. Null-move pruning - -If giving the opponent a free move (a "null move") still fails high at reduced -depth (`R = 2..3`), the position is almost certainly a cut-off - return `beta` -without searching the real moves. Skip it when side-to-move is in check, in a -likely zugzwang (king + pawns only), or when depth is very low. Add a -verification search at high depth to avoid zugzwang blunders. Needs a -`board.push(chess.Move.null())` path and a `_null_ok` guard in the search. -Typically the single largest Elo jump available (~50-100). - -### 2. Principal Variation Search (NegaScout) - -Search the first (best-ordered) move with the full `(-beta, -alpha)` window, -then every later move with a null window `(-alpha-1, -alpha)`; only re-search -with the full window on the rare fail-high. With the move ordering already in -place (TT move, MVV-LVA, killers, history) the first move is usually best, so -most nodes get the cheaper scout search. ~20-40 Elo and it compounds with -everything below. - -### 3. Late Move Reductions (LMR) - -Once past the first few moves at a node, search quiet, non-checking, non-TT -moves at `depth - 1 - reduction` (reduction grows with move index and depth, -shrink it for killers / good history). Re-search at full depth if the reduced -search beats `alpha`. Combined with PVS this is usually the biggest tree -reduction after null-move - effective branching factor drops sharply, so -iterative deepening reaches 2-4 plies deeper in the same time. - -### 4. Correct draw, repetition and mate scoring - -- Detect threefold repetition and the 50-move rule *inside* the search tree - (`board.is_repetition(3)`, `board.halfmove_clock`), not just the automatic - five-fold / seventy-five-move draws in `is_drawn`. -- Score every draw a flat `0` (currently negamax returns `0 - depth`), with an - optional small contempt value. -- Store mate scores in the TT as distance-to-mate relative to the current ply - (`score +/- ply` on store/probe) so `MATE_GUARD` can be removed and mate - cut-offs actually propagate. This fixes real half-point losses and lets the - engine convert forced mates faster. - -### 5. Evaluation upgrade - -PeSTO piece-square tables capture a lot of positional understanding but miss -king safety and pawn structure, which is where a mid-level engine gains most. -Add, keeping the incremental accumulator where possible and a pawn-hash cache -for the rest: - -- King safety: attacker count / attack weight on the squares around the king, - pawn-shield intactness, open files next to the king. -- Passed pawns (bonus scaled by rank and king distance), isolated / doubled / - backward pawns. -- Bishop pair, rook on open / half-open file, knight outposts. -- Tempo bonus. - -Then wire in [Syzygy endgame tablebases](https://python-chess.readthedocs.io/en/latest/syzygy.html) -(`chess.syzygy`) for perfect play with <= 6 pieces. - ---- - -*Recently completed (from the previous review pass): move ordering, transposition -table, single-process iterative deepening + UCI time management, perft fix + -tests, quiescence rewrite (bounded, check-aware, fail-soft), tapered PeSTO -evaluation with an incremental accumulator, standard `info` output, resource-leak -fixes, and Lazy SMP (`go_parallel`) with a lock-free shared-memory TT.* - -## Chess Engine - -### [Search](https://www.chessprogramming.org/Search) - -- [Negamax](https://www.chessprogramming.org/Negamax) - fail-soft -- [Move Ordering](https://www.chessprogramming.org/Move_Ordering) - TT move, captures, promotions, killers, history - - [MVV-LVA Captures](https://www.chessprogramming.org/MVV-LVA) - - [Killer Heuristic](https://www.chessprogramming.org/Killer_Heuristic) - - [History Heuristic](https://www.chessprogramming.org/History_Heuristic) -- [Alpha-Beta Pruning](https://www.chessprogramming.org/Alpha-Beta) - - [Quiescence Search](https://www.chessprogramming.org/Quiescence_Search) - fail-soft, depth-bounded, check-aware - - [Transposition Table](https://www.chessprogramming.org/Transposition_Table) - Zobrist-keyed, EXACT/LOWER/UPPER bounds - - [Iterative Deepening](https://www.chessprogramming.org/Iterative_Deepening) - single-process, with UCI time management -- [Lazy SMP](https://www.chessprogramming.org/Lazy_SMP) - `go_parallel`, workers share a lock-free shared-memory TT -- Opening Book - -#### Optimizations still to be researched and implemented - -- Move Ordering - - Captures - - [Dedicated Piece-Square Table](https://www.chessprogramming.org/Piece-Square_Tables) - - [Static Exchange Evaluation](https://www.chessprogramming.org/Static_Exchange_Evaluation) - - Non-Captures - - [Killer Heuristic](https://www.chessprogramming.org/Killer_Heuristic) - - [History Heuristic](https://www.chessprogramming.org/History_Heuristic) - - [Relative History Heuristic](https://www.chessprogramming.org/Relative_History_Heuristic) -- Alpha Beta Optimizations - - [Aspiration Windows](https://www.chessprogramming.org/Aspiration_Windows) - - [Null Move Pruning](https://www.chessprogramming.org/Null_Move_Pruning) - - [Principal Variation Search](https://www.chessprogramming.org/Principal_Variation_Search) - - [Late Move Reductions](https://www.chessprogramming.org/Late_Move_Reductions) -- Endgame Tablebase - -#### Additional Engines to research - -- [NegaScout](https://www.chessprogramming.org/NegaScout) -- [NegaC*](https://www.chessprogramming.org/NegaC*) -- [MTD(f)](https://www.chessprogramming.org/MTD\(f\)) - -### [Evaluation](https://www.chessprogramming.org/Evaluation) - -- [PeSTO](https://www.chessprogramming.org/PeSTO%27s_Evaluation_Function) - tapered mid-/end-game piece-square tables, interpolated by game phase - - [Material Balance](https://www.chessprogramming.org/Material) / [Point Value](https://www.chessprogramming.org/Point_Value) - - [Piece-Square Tables](https://www.chessprogramming.org/Piece-Square_Tables) - [incrementally updated](https://www.chessprogramming.org/Incremental_Updates) on `EvalBoard.push`/`pop` -- [Pawn Structure: Doubled, Blocked, and Isolated Pawns](https://www.chessprogramming.org/Pawn_Structure) -- [Mobility](https://www.chessprogramming.org/Mobility) -- [Center Control](https://www.chessprogramming.org/Center_Control) -- [Connectivity](https://www.chessprogramming.org/Connectivity) -- [Trapped Pieces](https://www.chessprogramming.org/Trapped_Pieces) -- [King Safety](https://www.chessprogramming.org/King_Safety) -- [Space](https://www.chessprogramming.org/Space) -- [Tempo](https://www.chessprogramming.org/Tempo) - -#### Optimizations to Consider/Research - -- [Evaluation Hash Table](https://www.chessprogramming.org/Evaluation_Hash_Table) -- [Material Hash Table](https://www.chessprogramming.org/Material_Hash_Table) -- [Pawn Hash Table](https://www.chessprogramming.org/Pawn_Hash_Table) - -- Evaluate the board before making any moves -- Substract the value of the piece being moved in the from position -- Add the value of the piece being moved in the to position - -### Tests - -Run with `pytest` (config in `pytest.ini`, tests under `test/`). - -- `test/test_perft.py` - move generation validated against published perft node counts -- Mate in 1, 2, 3, 4 & 5 (given depth = 2n-1) -- Captures - - Counting Attackers vs Defenders -- Tactics - - Discovered Attacks - - Forks - - Pins - - Removing the Defender - - Skewers -- Classic Games - -## Playing Strength - -Estimated at **~1800–2000 Elo** (blitz, FIDE/CCRL-ish scale), most likely around -1900. This is a feature-based estimate, not a measured result - see -[STRENGTH.md](STRENGTH.md) for the reasoning, calibration against known engines, -time-control sensitivity, and how to measure it properly. - -## Performance Results - -All figures below are a fresh benchmark on one machine (Apple Silicon, 10 -cores, Python 3.13), fixed-depth search from the starting position. "Before" -is the pre-review engine (plain negamax, no move ordering, no working TT, -unbounded quiescence, from-scratch material+PST eval); "After" is the current -engine. Both columns were run on the *same* machine, so this is a like-for-like -comparison rather than a comparison against the older M1 numbers. - -For reference, the original M1 run recorded depth 5 = 1.42s, depth 6 = 10.0s, -depth 7 = 215s single-process (and the old "parallel" mode was *slower*: depth -7 = 430s). - -### Single process, fixed-depth `search()` from the start position - -| depth | Before (time / nodes) | After (time / nodes) | speed-up | -|------:|----------------------:|---------------------:|---------:| -| 2 | 0.002s / 87 | 0.002s / 79 | ~1x | -| 3 | 0.015s / 802 | 0.012s / 657 | 1.3x | -| 4 | 0.091s / 3,991 | 0.064s / 2,387 | 1.4x | -| 5 | 1.157s / 46,875 | 0.321s / 15,139 | 3.6x | -| 6 | 8.169s / 317,377 | 1.770s / 72,048 | 4.6x | -| 7 | 152.4s / 5,451,009 | 9.565s / 453,119 | **16x** | - -The gap widens every ply because move ordering (TT move, MVV-LVA, killers, -history) and the transposition table compound. "Nodes" is `board.push` calls -(main search + quiescence). - -### Current engine, iterative deepening (what `go` / `go depth N` actually runs) - -| target depth | time | nodes | -|-------------:|-----:|------:| -| 5 | 0.24s | 12k | -| 6 | 1.38s | 53k | -| 7 | 5.11s | 236k | -| 8 | 38.6s | 2.1M | - -Iterative deepening is roughly 2x faster than a cold fixed-depth search -(each iteration seeds the next through the TT and improves move ordering). - -### Parallel from the start position (`go_parallel`) - -| depth | Before ("parallel", root-split) | After (Lazy SMP, 9 workers, shared TT) | -|------:|--------------------------------:|--------------------------------------:| -| 6 | 10.6s | 0.84s | -| 7 | 430s | 3.77s | -| 8 | — | 17.9s | - -The old parallel mode lost to its own single-threaded search (full windows, no -shared table). Lazy SMP is ~1.5x faster than the current single-threaded -iterative deepening at depth 6-7 and ~2x by depth 8, on this 10-core machine. \ No newline at end of file +Point any UCI GUI (CuteChess, Arena, a Lichess bot harness) at the `pychess` +command. + +## Usage + +Standard UCI: `uci`, `isready`, `ucinewgame`, `position`, `go`, `stop`, `quit`. + +`go` accepts `depth `, `movetime `, `nodes `, `wtime/btime/winc/binc/movestogo `, +or `infinite`; a bare `go` searches for ~4s. Every search runs Lazy SMP - one +worker process per core, sharing a lock-free transposition table. + +Extra commands: `perft `, `selfPlay`, `printBoard`, `printLegalMoves`, +`printMoveStack`. + +## Repository layout + +``` +pychess/ +├── pyproject.toml packaging, dependencies, ruff / mypy / pytest / coverage config +├── src/pychess/ +│ ├── __main__.py UCI protocol loop; `pychess` / `python -m pychess` entry point +│ ├── engine.py Engine - assembles the default search +│ ├── lazy_smp.py Lazy SMP coordinator + worker; returns a SearchResult +│ ├── negamax.py Negamax - fail-soft negamax + quiescence over injected pieces +│ ├── move_ordering.py MoveOrderer - TT move / MVV-LVA / killers / history +│ ├── evaluation.py PeSTO tables + PestoEvaluator +│ ├── eval_board.py EvalBoard - chess.Board with an incremental eval accumulator +│ ├── transposition.py TranspositionTable - in-process dict +│ ├── shared_tt.py SharedTT / SharedFlag - lock-free shared-memory table +│ ├── clock.py Clock + deadline_from_limits (UCI time management) +│ ├── constants.py mate / window / TT-flag constants +│ ├── types.py shared type aliases (GoLimits) +│ └── perft.py move-generation node counter +├── tests/ pytest suite, one test_.py per source module +├── opening_book/ Polyglot opening book (see opening_book/README.md) +└── docs/ + ├── design.md architecture, feature list, backlog + ├── engine-strength.md playing-strength estimate and how to measure it + ├── performance.md benchmark tables (search speed, Lazy SMP scaling) + └── tasks.md prioritised roadmap + what's already done +``` + +## Development + +```bash +pip install -e ".[dev]" +pre-commit install # optional: runs the checks below on every commit + +ruff check . # lint +ruff format --check . # formatting +mypy # type-check src/ (strict) and tests/ +pytest # tests + coverage (gate: 85%) +``` + +CI (`.github/workflows/ci.yml`) runs lint + format + type-check once and the +test suite on Python 3.12 and 3.13. All tool config lives in `pyproject.toml`. + +## License + +[Apache-2.0](LICENSE). The bundled opening book has separate provenance - +see [opening_book/README.md](opening_book/README.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..cf2da34 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,29 @@ +# Security Policy + +## Supported versions + +This project is pre-1.0 and moves fast. Only `main` receives fixes. + +| Version | Supported | +|---------|-----------| +| `main` | ✅ | +| tagged releases | latest only | + +## Reporting a vulnerability + +Please **do not open a public issue** for security problems. + +Report privately via GitHub: +[**Open a security advisory**](https://github.com/cjunius/pyChess/security/advisories/new). + +Include a description, reproduction steps, and the affected commit or version. +You can expect an acknowledgement within a few days. There is no bug-bounty +program. + +## Scope + +This is a chess engine that reads UCI commands on stdin and an optional Polyglot +opening-book file. Relevant concerns include malformed UCI / FEN input, +crafted opening-book files, and the `multiprocessing` shared-memory transposition +table. The bundled `opening_book/bookfish.bin` is third-party data — see +[opening_book/README.md](opening_book/README.md). diff --git a/archive/__init__.py b/archive/__init__.py deleted file mode 100644 index c7df41c..0000000 --- a/archive/__init__.py +++ /dev/null @@ -1 +0,0 @@ -import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__))) \ No newline at end of file diff --git a/archive/config.py b/archive/config.py deleted file mode 100644 index 2e4bee4..0000000 --- a/archive/config.py +++ /dev/null @@ -1,31 +0,0 @@ -import chess -from dataclasses import dataclass - -@dataclass -class Config: - depth: int = 4 - nodes: int = 0 - opening_book: str = "opening_book/cerebellum.bin" - threads: int = 1 - log_file: str = "" - ttsize: int = 10**7 - - # PESTO CONSTANTS - - MG_PIECE_VALUES = [ - (chess.PAWN, 82), - (chess.KNIGHT, 337), - (chess.BISHOP, 365), - (chess.ROOK, 477), - (chess.QUEEN, 1025), - (chess.KING, 0) - ] - - EG_PIECE_VALUES = [ - (chess.PAWN, 94), - (chess.KNIGHT, 281), - (chess.BISHOP, 297), - (chess.ROOK, 512), - (chess.QUEEN, 936), - (chess.KING, 0) - ] \ No newline at end of file diff --git a/archive/evaluation.py b/archive/evaluation.py deleted file mode 100644 index 0902c1a..0000000 --- a/archive/evaluation.py +++ /dev/null @@ -1,137 +0,0 @@ -import chess -from chess import Board - -PAWN_TABLE = [ - 0, 0, 0, 0, 0, 0, 0, 0, - 50, 50, 50, 50, 50, 50, 50, 50, - 10, 10, 20, 30, 30, 20, 10, 10, - 5, 5, 10, 25, 25, 10, 5, 5, - 0, 0, 0, 20, 20, 0, 0, 0, - 5, -5,-10, 0, 0,-10, -5, 5, - 5, 10, 10,-20,-20, 10, 10, 5, - 0, 0, 0, 0, 0, 0, 0, 0 -] - -KNIGHT_TABLE = [ - -50,-40,-30,-30,-30,-30,-40,-50, - -40,-20, 0, 0, 0, 0,-20,-40, - -30, 0, 10, 15, 15, 10, 0,-30, - -30, 5, 15, 20, 20, 15, 5,-30, - -30, 0, 15, 20, 20, 15, 0,-30, - -30, 5, 10, 15, 15, 10, 5,-30, - -40,-20, 0, 5, 5, 0,-20,-40, - -50,-40,-30,-30,-30,-30,-40,-50 -] - -BISHOP_TABLE = [ - -20,-10,-10,-10,-10,-10,-10,-20, - -10, 0, 0, 0, 0, 0, 0,-10, - -10, 0, 5, 10, 10, 5, 0,-10, - -10, 5, 5, 10, 10, 5, 5,-10, - -10, 0, 10, 10, 10, 10, 0,-10, - -10, 10, 10, 10, 10, 10, 10,-10, - -10, 5, 0, 0, 0, 0, 5,-10, - -20,-10,-10,-10,-10,-10,-10,-20 -] - -ROOK_TABLE = [ - 0, 0, 0, 0, 0, 0, 0, 0, - 5, 10, 10, 10, 10, 10, 10, 5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - 0, 0, 0, 5, 5, 0, 0, 0 -] - -QUEEN_TABLE = [ - -20,-10,-10, -5, -5,-10,-10,-20, - -10, 0, 0, 0, 0, 0, 0,-10, - -10, 0, 5, 5, 5, 5, 0,-10, - -5, 0, 5, 5, 5, 5, 0, -5, - 0, 0, 5, 5, 5, 5, 0, -5, - -10, 5, 5, 5, 5, 5, 0,-10, - -10, 0, 5, 0, 0, 0, 0,-10, - -20,-10,-10, -5, -5,-10,-10,-20 -] - -KING_TABLE = [ - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -30,-40,-40,-50,-50,-40,-40,-30, - -20,-30,-30,-40,-40,-30,-30,-20, - -10,-20,-20,-20,-20,-20,-20,-10, - 20, 20, 0, 0, 0, 0, 20, 20, - 20, 30, 10, 0, 0, 10, 30, 20 -] - -PIECE_VALUE_SQUARE_TABLES = [ - (chess.PAWN, 100, PAWN_TABLE), - (chess.KNIGHT, 350, KNIGHT_TABLE), - (chess.BISHOP, 350, BISHOP_TABLE), - (chess.ROOK, 525, ROOK_TABLE), - (chess.QUEEN, 1000, QUEEN_TABLE), - (chess.KING, 2000, KING_TABLE) -] - -# ToDo: -# - Material Evaluation - COMPLETE -# - Double, Isolated, and Backward Pawns -# - Bishop Pair -# - Open and Semi-Open Rooks -# - King Safety -# - Piece Square Table Evaluation - COMPLETE -# - Tapered evaluation between middlegame and endgame - PeSTO -# - Tempo evaluation - COMPLETE - -def evaluate_board(board: Board) -> int: - eval = -50 if board.is_check() else 0 - #eval += evaluate_material_balance(board) - eval += evaluate_piece_square_table(board) - eval += 5*evaluate_mobility(board) - return eval - - -def evaluate_material_balance(board: Board) -> int: - eval = 0 - for piece, value, _ in PIECE_VALUE_SQUARE_TABLES: - if piece == chess.KING: continue # Kings cancel each other - eval += value * (len(board.pieces(piece, board.turn)) - len(board.pieces(piece, not board.turn))) - return eval - - -def evaluate_piece_square_table(board: Board) -> int: - eval = 0 - for piece, value, pst in PIECE_VALUE_SQUARE_TABLES: - eval += sum([pst[i]+value for i in board.pieces(piece, chess.WHITE)]) - eval -= sum([pst[chess.square_mirror(i)]+value for i in board.pieces(piece, chess.BLACK)]) - return eval if board.turn else -eval - -def board_control(board: Board) -> int: - eval = 0 - for square in chess.SquareSet(board.occupied_co[board.turn]): - eval += len(board.attacks(square)) - - for square in chess.SquareSet(board.occupied_co[not board.turn]): - eval -= len(board.attacks(square)) - - return eval - -def evaluate_mobility(board: Board) -> int: - if len(list(board.move_stack)) == 0: - return 0 - - last_move = board.pop() - countA = len(list(board.legal_moves)) - board.push(last_move) - countB = len(list(board.legal_moves)) - return countA - countB - -def evaluate_pawn_structure(board: Board) -> int: - # D, S, I = doubled, blocked and isolated pawns - # return -0.5(D-D' + S-S' + I-I') - eval = 0 - return eval - diff --git a/archive/helper.py b/archive/helper.py deleted file mode 100644 index 532d4e0..0000000 --- a/archive/helper.py +++ /dev/null @@ -1,20 +0,0 @@ -from archive.negamax import NegamaxEngine -from archive.random import RandomEngine -from archive.firstMove import FirstMoveEngine -from archive.lastMove import LastMoveEngine -from archive.config import Config - -def get_engines(config: Config = Config()): - return [NegamaxEngine(config=config), RandomEngine(config=config), FirstMoveEngine(config=config), LastMoveEngine(config=config)] - -def get_negamax_engine(config: Config = Config()): - return NegamaxEngine(config=config) - -def get_random_engine(config: Config = Config()): - return RandomEngine(config=config) - -def get_firstmove_engine(config: Config = Config()): - return FirstMoveEngine(config=config) - -def get_lastmove_engine(config: Config = Config()): - return LastMoveEngine(config=config) \ No newline at end of file diff --git a/archive/move_ordering.py b/archive/move_ordering.py deleted file mode 100644 index 6db8a8b..0000000 --- a/archive/move_ordering.py +++ /dev/null @@ -1,103 +0,0 @@ -import random -from chess import Board, Move -from typing import List - -PIECE_VALUES = { - 'P': 1, 'p': 1, - 'N': 2, 'n': 2, - 'B': 3, 'b': 3, - 'R': 4, 'r': 4, - 'Q': 5, 'q': 5, - 'K': 6, 'k': 6, - None: 0 - } - -# Castling (King Safety) -# Mate -# Checks -# Captures (mvv-lva) -# Threats ?? -# Non-Captures - -# Typical Move Ordering from chessprogramming.org/Move_Ordering -# 1. PV-Node of the principal variation from the previous iteration -# 2. Hash move from hash tables -# 3. Winning Captures/Promotions -# 4. Equal Captures/Promotions -# 5. Killer moves (non capture), often with mate killers first -# 6. Non-captures sorted by history heuristic and that like -# 7. Losing captures - -def order_moves(board: Board) -> List[Move]: - - checks = [] - captures = [] - threats = [] - promotions = [] - castling = [] - non_captures = [] - - for move in board.legal_moves: - if board.gives_check(move): - board.push(move) - if board.is_checkmate(): - board.pop() - return [move] #no point in searching other moves if checkmate exists - board.pop() - checks.append(move) - elif board.is_capture(move): - captures.append(move) - elif board.is_castling(move): - castling.append(move) - elif not move.promotion == None: - promotions.append(move) - else: - non_captures.append(move) - - checks.sort(reverse=True, key=lambda move: _rank_checks(board, move)) - captures.sort(reverse=True, key=lambda move: _rank_captures(board, move)) - non_captures.sort(reverse=True, key=lambda move: _rank_non_captures(board, move)) - - return castling + checks + captures + threats + promotions + non_captures - - -def _rank_checks(board: Board, move: Move) -> int: - try: - board.push(move) - if board.is_checkmate(): - board.pop() - return 2 - board.pop() - - return 1 - except: - return 0 - - -def _rank_captures(board: Board, move: Move) -> int: - try: - victim = board.piece_at(move.to_square).symbol() - attacker = board.piece_at(move.from_square).symbol() - return 10*PIECE_VALUES[victim] - PIECE_VALUES[attacker] # Most Valuable Victim - Least Valuable Attacker - except: - return 0 - -# ToDo: Rank by Piece Square Table value on move.to_square -def _rank_non_captures(board: Board, move: Move) -> int: - try: - return PIECE_VALUES[board.piece_at(move.from_square).symbol()] - except: - return 0 - -def order_moves_quiescence(board: Board) -> List[Move]: - captures = [] - for move in board.legal_moves: - if board.gives_check(move): - captures.append(move) - elif board.is_capture(move): - captures.append(move) - elif not move.promotion == None: - captures.append(move) - - random.shuffle(captures) - return captures \ No newline at end of file diff --git a/archive/negamax.py b/archive/negamax.py deleted file mode 100644 index 426129c..0000000 --- a/archive/negamax.py +++ /dev/null @@ -1,111 +0,0 @@ -import chess - -from chess import Board, polyglot -from archive.config import Config -import pygame -from copy import copy -from archive.transposition_table import TransTable, TransTableEntry, FLAG -import archive.move_ordering as move_ordering -import archive.quiescence_search as quiescence_search -import multiprocessing -import multiprocessing.pool - -class NegamaxEngine: - - def __init__(self, config: Config = Config()): - self.config = config - self.tt = TransTable() - self.move_stack = [] - - def get_name(self): - return "Negamax Engine" - - def find_move(self, board: Board): - try: - return polyglot.MemoryMappedReader(self.config.opening_book).weighted_choice(board).move - except: - best_move = chess.Move.null() - #best_move, best_score = self.negamaxRoot(board, self.config.depth, -999999, 999999) - - for i in range(1, self.config.depth + 1): - best_move, best_score = self.negamaxRoot(board, i, -999999, 999999) - if board.gives_check(best_move): - board.push(best_move) - if board.is_checkmate(): - board.pop() - break - board.pop() - return best_move - - def negamaxRoot(self, board, depth, alpha, beta): - best_move: chess.Move = chess.Move.null() - best_score = -999999 - - moves = move_ordering.order_moves(board) - for move in moves: - board.push(move) - score = -self.negamax(board, depth-1, -beta, -alpha) - board.pop() - - if score > best_score: - best_score = score - best_move = move - print("info bestmove {}".format(board.san(best_move))) - alpha = max(alpha, score) - - return best_move, best_score - - - def negamax(self, board: Board, depth: int, alpha: int, beta: int) -> int: - - alpha_prime = alpha - - hash = polyglot.zobrist_hash(board=board) - ttEntry = self.tt.getEntry(hash) - if ttEntry and ttEntry.depth >= depth: - if ttEntry.flag == FLAG.EXACT: - return ttEntry.value - elif ttEntry.flag == FLAG.LOWER_BOUND: - alpha = max(alpha, ttEntry.value) - elif ttEntry.flag == FLAG.UPPER_BOUND: - beta = min(beta, ttEntry.value) - - if alpha >= beta: - return ttEntry.value - - if depth <= 0 or board.is_game_over(): - return quiescence_search.quiescence_search(board=board, alpha=alpha, beta=beta, depth=depth) - - # ToDo: Null Move pruning here - - best_score = -999999 - moves = move_ordering.order_moves(board) - pygame.event.pump() #Prevent OS from thinking pygame has gone unresponsive - for move in moves: - self.move_stack.append(board.san(move)) - board.push(move) - score = -self.negamax(board, depth-1, -beta, -alpha) - - hash = polyglot.zobrist_hash(board=board) - ttEntry = TransTableEntry(hash=hash) - ttEntry.value = score - ttEntry.depth = depth - if score <= alpha_prime: - ttEntry.flag = FLAG.LOWER_BOUND - elif score >= beta: - ttEntry.flag = FLAG.UPPER_BOUND - else: - ttEntry.flag = FLAG.EXACT - - self.tt.update_ttable(ttEntry) - board.pop() - self.move_stack.remove(board.san(move)) - - if score >= beta: - return score - best_score = max(best_score, score) - alpha = max(alpha, score) - if alpha >= beta: - break - - return best_score diff --git a/archive/pyChess.py b/archive/pyChess.py deleted file mode 100644 index 3e9a90c..0000000 --- a/archive/pyChess.py +++ /dev/null @@ -1,101 +0,0 @@ -import signal -import sys -import chess -import chess.svg -from chessboard import display - - - -import archive.helper as helper - -# Catch KeyboardInterrupt and quit -def catchthesignal(signal, frame): - sys.exit(0) -signal.signal(signal.SIGINT, catchthesignal) - -game_board = None - -def main(): - - bot1_wins = 0 - bot2_wins = 0 - draws = 0 - - engine1 = choose_engine("Player 1") - engine2 = choose_engine("Player 2") - print("\n" + engine1.get_name() + " vs " + engine2.get_name()) - game_board = display.start() - - for i in range(0, 9): - - board = chess.Board() - display.update(board.fen(), game_board) - - winner = None - while not board.outcome(): - - if i%2 == 0: - winner = validate_move(board, engine1.find_move(board.copy(stack=False)) ) - display.update(board.fen(), game_board) - if not winner == None: - break - - winner = validate_move(board, engine2.find_move(board.copy(stack=False)) ) - display.update(board.fen(), game_board) - if not winner == None: - break - - if i%2 == 1: - winner = validate_move(board, engine1.find_move(board.copy(stack=False)) ) - display.update(board.fen(), game_board) - if not winner == None: - break - - if (winner == "White" and i%2 == 0) or (winner == "Black" and i%2 == 1): - bot1_wins += 1 - elif (winner == "Black" and i%2 == 0) or (winner == "White" and i%2 == 1): - bot2_wins += 1 - else: - draws += 1 - - bot1_score = bot1_wins + draws * 0.5 - bot2_score = bot2_wins + draws * 0.5 - print(engine1.get_name() + " " + str(bot1_score) + " - " + str(bot2_score) + " " + engine2.get_name()) - - board.clear() - board.reset() - - display.terminate() - -def choose_engine(player: str): - ENGINES = helper.get_engines() - print("") - for idx, engine in enumerate(ENGINES): - print('{num}: {name}'.format(num=idx+1,name=engine.get_name())) - - x = input('Choose ' + player + ': ') - engine = ENGINES[int(x)-1] - return engine - -def validate_move(board: chess.Board, move: chess.Move): - if move in board.legal_moves: - board.push(move) - outcome = board.outcome() - if outcome: - if chess.WHITE == outcome.winner: - return "White" - elif chess.BLACK == outcome.winner: - return "Black" - else: - return "Draw" - else: - if chess.WHITE == board.turn: - print("Illegal move detected\n") - return "Black" - else: - print("Illegal move detected\n") - return "White" - return None - -if __name__ == "__main__": - main() diff --git a/archive/quiescence_search.py b/archive/quiescence_search.py deleted file mode 100644 index b534025..0000000 --- a/archive/quiescence_search.py +++ /dev/null @@ -1,56 +0,0 @@ -import random -from typing import List -from chess import Board, Move -import archive.evaluation as evaluation -import archive.move_ordering as move_ordering - -# Quiescence Search -# https://www.chessprogramming.org/Quiescence_Search -def quiescence_search(board: Board, alpha: int, beta: int, depth: int) -> int: - if board.is_game_over(): - if board.is_checkmate(): - return -9999 - depth - if board.is_stalemate(): - return 0 - if board.is_insufficient_material(): - return 0 - if board.is_fivefold_repetition(): - return 0 - if board.is_seventyfive_moves(): - return 0 - - if board.is_repetition(): - return 0 - - stand_pat = evaluation.evaluate_board(board) - if stand_pat >= beta: - return beta - alpha = max(alpha, stand_pat) - - def order_moves_quiescence() -> List[Move]: - captures = [] - for move in board.legal_moves: - if board.gives_check(move): - captures.append(move) - elif board.is_capture(move): - captures.append(move) - elif not move.promotion == None: - captures.append(move) - - random.shuffle(captures) - return captures - - moves = order_moves_quiescence(board) - for move in moves: - - #ToDo: Delta Pruning - - board.push(move) - score = -quiescence_search(-beta, -alpha, depth-1) - board.pop() - - if score >= beta: - return beta - alpha = max(alpha, score) - - return alpha \ No newline at end of file diff --git a/archive/src/evaluation.py b/archive/src/evaluation.py deleted file mode 100644 index 53ebd2a..0000000 --- a/archive/src/evaluation.py +++ /dev/null @@ -1,42 +0,0 @@ -from helpers import * -from psqt import * - -# External -import chess - - -class Evaluation: - @staticmethod - def eval_side(board: chess.Board, color: chess.Color) -> int: - occupied = board.occupied_co[color] - - material = 0 - psqt = 0 - - # loop over all set bits - while occupied: - # find the least significant bit - square = lsb(occupied) - - piece = board.piece_type_at(square) - - # add material - material += piece_values[piece] - - # add piece square table value - psqt += ( - list(reversed(psqt_values[piece]))[square] - if color == chess.BLACK - else psqt_values[piece][square] - ) - - # remove lsb - occupied = poplsb(occupied) - - return material + psqt - - @staticmethod - def evaluate(board: chess.Board) -> int: - return Evaluation.eval_side(board, chess.WHITE) - Evaluation.eval_side( - board, chess.BLACK - ) \ No newline at end of file diff --git a/archive/src/helpers.py b/archive/src/helpers.py deleted file mode 100644 index 363214d..0000000 --- a/archive/src/helpers.py +++ /dev/null @@ -1,32 +0,0 @@ -MAX_PLY = 60 -CHECK_RATE = 256 - -VALUE_INFINITE = 32001 -VALUE_NONE = 32002 -VALUE_MATE = 32000 -VALUE_MATE_IN_PLY = VALUE_MATE - MAX_PLY -VALUE_MATED_IN_PLY = -VALUE_MATE_IN_PLY - -# Theres no TB support but it useful for other people who port this to another language to respect the TB value ranges -VALUE_TB_WIN = VALUE_MATE_IN_PLY -VALUE_TB_LOSS = -VALUE_TB_WIN -VALUE_TB_WIN_IN_MAX_PLY = VALUE_TB_WIN - MAX_PLY -VALUE_TB_LOSS_IN_MAX_PLY = -VALUE_TB_WIN_IN_MAX_PLY - - -# least significant bit -def lsb(x: int) -> int: - return (x & -x).bit_length() - 1 - - -def poplsb(x: int) -> int: - x &= x - 1 - return x - - -def mate_in(ply: int) -> int: - return VALUE_MATE - ply - - -def mated_in(ply: int) -> int: - return ply - VALUE_MATE \ No newline at end of file diff --git a/archive/src/limits.py b/archive/src/limits.py deleted file mode 100644 index bb394f2..0000000 --- a/archive/src/limits.py +++ /dev/null @@ -1,8 +0,0 @@ -class Limits: - def __init__( - self, - nodes: int, - depth: int, - time: int, - ) -> None: - self.limited = {"nodes": nodes, "depth": depth, "time": time} \ No newline at end of file diff --git a/archive/src/psqt.py b/archive/src/psqt.py deleted file mode 100644 index 439397f..0000000 --- a/archive/src/psqt.py +++ /dev/null @@ -1,81 +0,0 @@ -import chess - -# fmt: off -piece_values = { - None: 0, - chess.PAWN: 100, - chess.KNIGHT: 320, - chess.BISHOP: 330, - chess.ROOK: 500, - chess.QUEEN: 900, - chess.KING: 10000, -} - -""" -These PSQT are taken from https://www.chessprogramming.org/Simplified_Evaluation_Function -and are more or less widely used in beginner chess engines. -""" -psqt_values = { - chess.PAWN: [ - 0, 0, 0, 0, 0, 0, 0, 0, - 5, 10, 10, -20, -20, 10, 10, 5, - 5, -5, -10, 0, 0, -10, -5, 5, - 0, 0, 0, 20, 20, 0, 0, 0, - 5, 5, 10, 25, 25, 10, 5, 5, - 10, 10, 20, 30, 30, 20, 10, 10, - 50, 50, 50, 50, 50, 50, 50, 50, - 0, 0, 0, 0, 0, 0, 0, 0 - ], - chess.KNIGHT: [ - -50, -40, -30, -30, -30, -30, -40, -50, - -40, -20, 0, 0, 0, 0, -20, -40, - -30, 0, 10, 15, 15, 10, 0, -30, - -30, 5, 15, 20, 20, 15, 5, -30, - -30, 0, 15, 20, 20, 15, 0, -30, - -30, 5, 10, 15, 15, 10, 5, -30, - -40, -20, 0, 5, 5, 0, -20, -40, - -50, -40, -30, -30, -30, -30, -40, -50 - ], - chess.BISHOP: [ - -20, -10, -10, -10, -10, -10, -10, -20, - -10, 5, 0, 0, 0, 0, 5, -10, - -10, 10, 10, 10, 10, 10, 10, -10, - -10, 0, 10, 10, 10, 10, 0, -10, - -10, 5, 5, 10, 10, 5, 5, -10, - -10, 0, 5, 10, 10, 5, 0, -10, - -10, 0, 0, 0, 0, 0, 0, -10, - -20, -10, -10, -10, -10, -10, -10, -20 - ], - chess.ROOK: [ - 0, 0, 0, 5, 5, 0, 0, 0, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - 5, 10, 10, 10, 10, 10, 10, 5, - 0, 0, 0, 0, 0, 0, 0, 0 - ], - chess.QUEEN: [ - -20, -10, -10, -5, -5, -10, -10, -20, - -10, 0, 0, 0, 0, 0, 0, -10, - -10, 0, 5, 5, 5, 5, 0, -10, - -5, 0, 5, 5, 5, 5, 0, -5, - 0, 0, 5, 5, 5, 5, 0, -5, - -10, 5, 5, 5, 5, 5, 0, -10, - -10, 0, 5, 0, 0, 0, 0, -10, - -20, -10, -10, -5, -5, -10, -10, -20 - ], - chess.KING: [ - 20, 30, 10, 0, 0, 10, 30, 20, - 20, 20, 0, 0, 0, 0, 20, 20, - -10, -20, -20, -20, -20, -20, -20, -10, - 20, -30, -30, -40, -40, -30, -30, -20, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30 - ], -} - -# fmt: on \ No newline at end of file diff --git a/archive/src/search.py b/archive/src/search.py deleted file mode 100644 index 3457a87..0000000 --- a/archive/src/search.py +++ /dev/null @@ -1,357 +0,0 @@ -import time -import tt as TT -from evaluation import Evaluation -import psqt as PQST - -import chess -from chess import polyglot -from chess import Move -from helpers import * -from limits import * -from sys import stdout - - -class Search: - def __init__(self, board: chess.Board) -> None: - self.board = board - self.transposition_table = TT.TranspositionTable() - self.pvLength = [0] * MAX_PLY - self.pvTable = [[Move.null()] * MAX_PLY for _ in range(MAX_PLY)] - self.nodes = 0 - self.limit = Limits(0, MAX_PLY, 0) - self.stop = False - self.checks = CHECK_RATE - self.hashHistory: list[int] = [] - self.htable = [[[0 for x in range(64)] for y in range(64)] for z in range(2)] - - def qsearch(self, alpha: int, beta: int, ply: int) -> int: - if self.stop or self.checkTime(): - return 0 - - bestValue = Evaluation.evaluate(self.board) - - if ply >= MAX_PLY: - return bestValue - - if bestValue >= beta: - return bestValue - - alpha = max(alpha, bestValue) - - moves = sorted( - self.board.generate_legal_captures(), - key=lambda move: self.scoreQMove(move), - reverse=True, - ) - - for move in moves: - self.nodes += 1 - - captured = self.board.piece_type_at(move.to_square) - - # Delta Pruning - if (PQST.piece_values[captured] + 400 + bestValue < alpha and not move.promotion): - continue - - self.board.push(move) - score = -self.qsearch(-beta, -alpha, ply + 1) - self.board.pop() - - if score > bestValue: - bestValue = score - - if score > alpha: - alpha = score - - if score >= beta: - break - - return bestValue - - def absearch(self, alpha: int, beta: int, depth: int, ply: int) -> int: - if self.checkTime(): - return 0 - - if ply >= MAX_PLY: - return Evaluation.evaluate(self.board) - - self.pvLength[ply] = ply - RootNode = ply == 0 - hashKey = self.getHash() - - if not RootNode: - if self.isRepetition(hashKey): - return -5 - - if self.board.halfmove_clock >= 100: - return 0 - - alpha = max(alpha, mated_in(ply)) - beta = min(beta, mate_in(ply + 1)) - if alpha >= beta: - return alpha - - if depth <= 0: - return self.qsearch(alpha, beta, ply) - - tte = self.transposition_table.probeEntry(hashKey) - ttHit = hashKey == tte.key - ttMove = tte.move if ttHit else Move.null() - - ttScore = ( - self.transposition_table.scoreFromTT(tte.score, ply) - if ttHit - else VALUE_NONE - ) - - if not RootNode and tte.depth >= depth and ttHit: - if tte.flag == TT.Flag.LOWERBOUND: - alpha = max(alpha, ttScore) - elif tte.flag == TT.Flag.UPPERBOUND: - beta = min(beta, ttScore) - - if alpha >= beta: - return ttScore - - inCheck = self.board.is_check() - - if depth >= 3 and not inCheck: - self.board.push(Move.null()) - - score = -self.absearch(-beta, -beta + 1, depth - 2, ply + 1) - - self.board.pop() - - if score >= beta: - if score >= VALUE_TB_WIN_IN_MAX_PLY: - score = beta - - return score - - oldAlpha = alpha - bestScore = -VALUE_INFINITE - bestMove = Move.null() - madeMoves = 0 - - moves = sorted( - self.board.legal_moves, - key=lambda move: self.scoreMove(move, ttMove), - reverse=True, - ) - - for move in moves: - madeMoves += 1 - self.nodes += 1 - - self.board.push(move) - self.hashHistory.append(hashKey) - - score = -self.absearch(-beta, -alpha, depth - 1, ply + 1) - - self.board.pop() - self.hashHistory.pop() - - if score > bestScore: - bestScore = score - bestMove = move - self.pvTable[ply][ply] = move - - for i in range(ply + 1, self.pvLength[ply + 1]): - self.pvTable[ply][i] = self.pvTable[ply + 1][i] - - self.pvLength[ply] = self.pvLength[ply + 1] - - if score > alpha: - alpha = score - - if score >= beta: - if not self.board.is_capture(move): - bonus = depth * depth - hhBonus = ( - bonus - - self.htable[self.board.turn][move.from_square][ - move.to_square - ] - * abs(bonus) - / 16384 - ) - - self.htable[self.board.turn][move.from_square][ - move.to_square - ] += hhBonus - break - - if madeMoves == 0: - if inCheck: - return mated_in(ply) - else: - return 0 - - bound = TT.Flag.NONEBOUND - - if bestScore >= beta: - bound = TT.Flag.LOWERBOUND - else: - if alpha != oldAlpha: - bound = TT.Flag.EXACTBOUND - else: - bound = TT.Flag.UPPERBOUND - - if not self.checkTime(): - self.transposition_table.storeEntry( - hashKey, depth, bound, bestScore, bestMove, ply - ) - - return bestScore - - def iterativeDeepening(self) -> None: - self.nodes = 0 - - score = -VALUE_INFINITE - bestmove = Move.null() - - self.t0 = time.time_ns() - - for d in range(1, self.limit.limited["depth"] + 1): - score = self.absearch(-VALUE_INFINITE, VALUE_INFINITE, d, 0) - - if self.stop or self.checkTime(True): - break - - bestmove = self.pvTable[0][0] - - now = time.time_ns() - stdout.write(self.stats(d, score, now - self.t0) + "\n") - stdout.flush() - - if bestmove == Move.null(): - bestmove = self.pvTable[0][0] - - stdout.write("bestmove " + str(bestmove) + "\n") - stdout.flush() - - def isRepetition(self, key: int, draw: int = 1) -> bool: - count = 0 - size = len(self.hashHistory) - - for i in range(size - 1, -1, -2): - if i >= size - self.board.halfmove_clock: - if self.hashHistory[i] == key: - count += 1 - if count == draw: - return True - - return False - - def mvvlva(self, move: chess.Move) -> int: - mvvlva: list[list[int]] = [ - [0, 0, 0, 0, 0, 0, 0], - [0, 105, 104, 103, 102, 101, 100], - [0, 205, 204, 203, 202, 201, 200], - [0, 305, 304, 303, 302, 301, 300], - [0, 405, 404, 403, 402, 401, 400], - [0, 505, 504, 503, 502, 501, 500], - [0, 605, 604, 603, 602, 601, 600], - ] - - from_square = move.from_square - to_square = move.to_square - attacker = self.board.piece_type_at(from_square) - victim = self.board.piece_type_at(to_square) - - if victim is None: - victim = 1 - return mvvlva[victim][attacker] - - def scoreQMove(self, move: chess.Move) -> int: - return self.mvvlva(move) - - def scoreMove(self, move: chess.Move, ttMove: chess.Move) -> int: - if move == ttMove: - return 1_000_000 - elif self.board.is_capture(move): - return 32_000 + self.mvvlva(move) - return self.htable[self.board.turn][move.from_square][move.to_square] - - def getHash(self) -> int: - return polyglot.zobrist_hash(self.board) - - def checkTime(self, iter: bool = False) -> bool: - if self.stop: - return True - - if ( - self.limit.limited["nodes"] != 0 - and self.nodes >= self.limit.limited["nodes"] - ): - return True - - if self.checks > 0 and not iter: - self.checks -= 1 - return False - - self.checks = CHECK_RATE - - if self.limit.limited["time"] == 0: - return False - - timeNow = time.time_ns() - if (timeNow - self.t0) / 1_000_000 > self.limit.limited["time"]: - return True - - return False - - def getPV(self) -> str: - pv = "" - - for i in range(0, self.pvLength[0]): - pv += " " + str(self.pvTable[0][i]) - - return pv - - def convert_score(self, score: int) -> str: - if score >= VALUE_MATE_IN_PLY: - return "mate " + str( - ((VALUE_MATE - score) // 2) + ((VALUE_MATE - score) & 1) - ) - elif score <= VALUE_MATED_IN_PLY: - return "mate " + str( - -((VALUE_MATE + score) // 2) + ((VALUE_MATE + score) & 1) - ) - else: - return "cp " + str(score) - - def stats(self, depth: int, score: int, time: int) -> str: - time_in_ms = int(time / 1_000_000) - time_in_seconds = max(1, time_in_ms / 1_000) - info = ( - "info depth " - + str(depth) - + " score " - + str(self.convert_score(score)) - + " nodes " - + str(self.nodes) - + " nps " - + str(int(self.nodes / time_in_seconds)) - + " time " - + str(round(time / 1_000_000)) - + " pv" - + self.getPV() - ) - return info - - def reset(self) -> None: - self.pvLength[0] = 0 - self.nodes = 0 - self.t0 = 0 - self.stop = False - self.checks = CHECK_RATE - self.hashHistory = [] - self.htable = [[[0 for x in range(64)] for y in range(64)] for z in range(2)] - - -if __name__ == "__main__": - board = chess.Board() - search = Search(board) - search.limit.limited["depth"] = 6 - search.iterativeDeepening() \ No newline at end of file diff --git a/archive/src/tt.py b/archive/src/tt.py deleted file mode 100644 index 38e7a39..0000000 --- a/archive/src/tt.py +++ /dev/null @@ -1,78 +0,0 @@ -from helpers import * - -# External -import chess -from enum import Enum - -Flag = Enum("Flag", ["NONEBOUND", "UPPERBOUND", "LOWERBOUND", "EXACTBOUND"]) - -""" -This is an entry in our TT, it saves -information about the score, flag and most -importantly the move. -""" - - -class TEntry: - def __init__(self) -> None: - self.key = 0 - self.depth = 0 - self.flag = Flag.NONEBOUND - self.score = VALUE_NONE - self.move = chess.Move.null() - - -class TranspositionTable: - def __init__(self) -> None: - # Higher values take rather long to initialize - self.tt_size = 2**19 - 1 - self.transposition_table = [TEntry() for _ in range(self.tt_size)] - - # Calculate "array" index - def ttIndex(self, key: int) -> int: - return key % self.tt_size - - # store an entry in the TT - def storeEntry( - self, key: int, depth: int, flag: Flag, score: int, move: chess.Move, ply: int - ) -> None: - index = self.ttIndex(key) - entry = self.transposition_table[index] - - # Replacement schema - if entry.key != key or entry.move != move: - entry.move = move - - if entry.key != key or flag == Flag.EXACTBOUND or depth + 4 > entry.depth: - entry.depth = depth - entry.score = self.scoreToTT(score, ply) - entry.key = key - entry.flag = flag - - # self.transposition_table[index] = entry - - def probeEntry(self, key: int) -> TEntry: - index = self.ttIndex(key) - entry = self.transposition_table[index] - - return entry - - # if we want to save correct mate scores we have to adjust the distance - def scoreToTT(self, s: int, plies: int) -> int: - if s >= VALUE_TB_WIN_IN_MAX_PLY: - return s + plies - else: - if s <= VALUE_TB_LOSS_IN_MAX_PLY: - return s - plies - else: - return s - - # undo the previous adjustment - def scoreFromTT(self, s: int, plies: int) -> int: - if s >= VALUE_TB_WIN_IN_MAX_PLY: - return s - plies - else: - if s <= VALUE_TB_LOSS_IN_MAX_PLY: - return s + plies - else: - return s \ No newline at end of file diff --git a/archive/test/puzzles.py b/archive/test/puzzles.py deleted file mode 100644 index f3e5469..0000000 --- a/archive/test/puzzles.py +++ /dev/null @@ -1,171 +0,0 @@ -MATE_IN_1 = [ - # https://chessfox.com/checkmate-patterns/ - ("8/4N1pk/8/8/8/4R3/8/6K1 w - - 0 1","Rh3#"), # Anastasia's Mate - ("6k1/6P1/5K2/8/8/8/7R/8 w - - 0 1", "Rh8#"), # Anderssen's Mate - ("7k/1R6/5N2/8/8/8/8/6K1 w - - 0 1", "Rh7#"), # Arabian Mate - ("6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1", "Rd8#"), # Back Rank Mate - ("4k3/8/5Q2/8/8/5B2/8/6K1 w - - 0 1", "Bc6#"), # Balestra Mate - ("5rk1/8/8/6N1/8/3B4/1B6/6K1 w - - 0 1", "Bh7#"), # Blackburne's Mate - ("5rk1/1R5R/8/8/8/8/8/6K1 w - - 0 1", "Rbg7#"), # Blind Swine Mate - ("2kr4/3p4/8/8/5B2/3B4/8/2K5 w - - 0 1", "Ba6#"), # Boden's Mate - ("7k/7p/8/4N3/8/8/8/2K3R1 w - - 0 1", "Nf7#"), # Corner Mate - ("8/2k5/8/8/7Q/8/8/1R1R2K1 w - - 0 1", "Qc4#"), # Corridor Mate - ("6bk/7p/8/8/8/6B1/8/6K1 w - - 0 1", "Be5#"), # Diagonal Corridor Mate - ("8/8/8/6p1/5qk1/2Q5/6K1/8 w - - 0 1", "Qh3#"), # Cozio's Mate (Dovetail Mate) - ("5rk1/6p1/6P1/8/8/7Q/8/6K1 w - - 0 1", "Qh7#"), # Damiano's Mate - ("8/8/1R6/5pkp/8/5KPP/8/8 w - - 0 1", "h4#"), # David and Goliath Mate - ("3rkr2/8/8/8/2Q5/8/8/6K1 w - - 0 1", "Qe6#"), # Epaulette Mate - ("7k/6p1/8/8/2B5/8/8/2KR4 w - - 0 1", "Rh1#"), # Graco's Mate - ("6k1/6P1/5K2/8/8/8/8/7R w - - 0 1", "Rh8#"), # H-file Mate - ("2R5/6pk/6N1/5P2/8/8/8/6K1 w - - 0 1", "Rh8#"), # Hook Mate - ("2k5/8/1Q1R4/8/8/8/8/6K1 w - - 0 1", "Rd8#"), # Kill Box Mate - ("7k/1R6/R7/8/8/8/8/6K1 w - - 0 1", "Ra8#"), # Lawnmower Mate - ("6k1/5p1p/5PpQ/8/8/8/8/6K1 w - - 0 1", "Qg7#"), # Lolli's Mate - ("4Q3/5Bpk/7p/8/8/8/8/6K1 w - - 0 1", "Qg8#"), # Max Lange's Mate - ("4k3/4pp2/8/B7/8/8/8/3R2K1 w - - 0 1", "Rd8#"), # Mayet's Mate - ("7k/7p/8/8/8/4B3/8/2K3R1 w - - 0 1", "Bd4#"), # Morphy's Mate - ("1n2kb1r/p4ppp/4q3/4p1B1/4P3/8/PPP2PPP/2KR4 w k - 0 1", "Rd8#"), # Opera Mate - ("5rk1/p4p1p/8/8/8/2B5/8/2KR4 w - - 0 1", "Rg1#"), # Pillsbury's Mate - ("rnb5/ppk5/2p5/6B1/8/8/5PPP/3R2K1 w - - 0 1", "Bd8#"), # Reti's Mate - ("r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq - 0 1", "Qxf7#"), # Scholar's Mate - ("6rk/6pp/8/6N1/8/8/8/6K1 w - - 0 1", "Nf7#"), # Smothered MAte - ("5rk1/5p1p/8/3N4/8/8/1B6/6K1 w - - 0 1", "Ne7#"), # Suffocation Mate - ("8/5p1p/6k1/8/6K1/4Q3/8/8 w - - 0 1", "Qg5#"), # Swallow's Tail Mate (Gueridon Mate) - ("8/6p1/6kR/8/5Q2/8/8/6K1 w - - 0 1", "Qf6#"), # Triangle Mate - ("5k2/2R5/4PN2/8/8/8/8/6K1 w - - 0 1", "Rf7#"), # Vukovic Mate - ("rnbqkbnr/pppp1ppp/8/4p3/6P1/5P2/PPPPP2P/RNBQKBNR b KQkq - 0 1", "Qh4#"), # Fool's Mate -] - -MATE_IN_2 = [ - ("1k6/6R1/7P/8/8/8/8/6K1 w - - 0 1", "h7"), # Mate in 2, p1, pawn push - ("2k5/6RP/8/8/8/8/8/6K1 w - - 1 2", "h8=Q#"), # Mate in 2, p2 , continuation - - ("r2qkbnr/ppp2ppp/2np4/4N3/2B1P3/2N4P/PPPP1PP1/R1BbK2R w KQkq - 0 1", "Bxf7+"), # Legal's Mate - part 1 - ("r2q1bnr/ppp1kBpp/2np4/4N3/4P3/2N4P/PPPP1PP1/R1BbK2R w KQ - 0 1", "Nd5#"), # Legal's Mate - part 2 - - ("8/6k1/8/5Q1R/8/8/8/6K1 w - - 0 1", "Rh7+"), # Railroad Mate - Part 1 - ("6k1/7R/8/5Q2/8/8/8/6K1 w - - 0 1", "Qf7#"), # Railroad Mate - part 2 - - ("1k6/8/8/8/8/p7/1r6/6K1 b - - 0 1", "a2"), # Mate in 2, p1, pawn push - ("1k6/8/8/8/8/8/pr6/5K2 b - - 1 2", "a1=Q#"), # Mate in 2, p2 , continuation - - ("1k6/8/8/2q5/8/r7/1K6/8 b - - 0 1", "Qc3+"), # Railroad Mate - Part 1 - ("1k6/8/8/8/8/r1q5/8/1K6 b - - 2 2", "Ra1#"), # Railroad Mate - part 2 -] - -MATE_IN_3 = [ - ("1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - 0 1", "Qd1+"), # Mate in 3 - Part 1 - Qd1+ (Sacrifice), Kxd1, - ("1k1r4/pp1b1R2/6pp/4p3/2B5/4Q3/PPP2B2/3K4 b - - 0 2", "Bg4+"), # Mate in 3 - Part 2 - Bg4+, Kc1 or Ke1 - ("1k1r4/pp3R2/6pp/4p3/2B3b1/4Q3/PPP2B2/2K5 b - - 2 3", "Rd1#"), # Mate in 3 - Part 3 - Rd1# - ("1k1r4/pp3R2/6pp/4p3/2B3b1/4Q3/PPP2B2/4K3 b - - 2 3", "Rd1#"), # Mate in 3 - Part 3 alt - Rd1# - - ("5k2/2b2ppp/3q4/5b2/3P4/PP2Q3/2r1B1PP/4R1K1 w - - 0 1", "Qe8+"), # Same as above with pieces flipped color - ("4k3/2b2ppp/3q4/5b2/3P4/PP6/2r1B1PP/4R1K1 w - - 0 2", "Bb5+"), - ("5k2/2b2ppp/3q4/1B3b2/3P4/PP6/2r3PP/4R1K1 w - - 2 3", "Re8#"), - ("3k4/2b2ppp/3q4/1B3b2/3P4/PP6/2r3PP/4R1K1 w - - 2 3", "Re8#") -] - -SIMPLE_CAPTURES = [ - ("6k1/2q2pp1/7p/8/8/7P/2Q2PP1/6K1 w - - 0 1", "Qxc7"), # White Queen takes Queen - ("6k1/2r2pp1/7p/8/8/7P/2Q2PP1/6K1 w - - 0 1", "Qxc7"), # White Queen takes Rook - ("6k1/2b2pp1/7p/8/8/7P/2Q2PP1/6K1 w - - 0 1", "Qxc7"), # White Queen takes Bishop - ("6k1/2n2pp1/7p/8/8/7P/2Q2PP1/6K1 w - - 0 1", "Qxc7"), # White Queen takes Knight - ("6k1/2p2pp1/7p/8/8/7P/2Q2PP1/6K1 w - - 0 1", "Qxc7"), # White Queen takes Pawn - ("6k1/2q2pp1/7p/8/8/7P/2R2PP1/6K1 w - - 0 1", "Rxc7"), # White Rook takes Queen - ("6k1/2r2pp1/7p/8/8/7P/2R2PP1/6K1 w - - 0 1", "Rxc7"), # White Rook takes Rook - ("6k1/2b2pp1/7p/8/8/7P/2R2PP1/6K1 w - - 0 1", "Rxc7"), # White Rook takes Bishop - ("6k1/2n2pp1/7p/8/8/7P/2R2PP1/6K1 w - - 0 1", "Rxc7"), # White Rook takes Knight - ("6k1/2p2pp1/7p/8/8/7P/2R2PP1/6K1 w - - 0 1", "Rxc7"), # White Rook takes Pawn - ("6k1/2q2ppp/8/8/8/6B1/5PPP/6K1 w - - 0 1", "Bxc7"), # White Bishop takes Queen - ("6k1/2r2ppp/8/8/8/6B1/5PPP/6K1 w - - 0 1", "Bxc7"), # White Bishop takes Rook - ("6k1/2b2ppp/8/8/8/6B1/5PPP/6K1 w - - 0 1", "Bxc7"), # White Bishop takes Bishop - ("6k1/2n2ppp/8/8/8/6B1/5PPP/6K1 w - - 0 1", "Bxc7"), # White Bishop takes Knight - ("6k1/2p2ppp/8/8/8/6B1/5PPP/6K1 w - - 0 1", "Bxc7"), # White Bishop takes Pawn - ("6k1/2q2ppp/8/3N4/8/8/5PPP/6K1 w - - 0 1", "Nxc7"), # White Knight takes Queen - ("6k1/2r2ppp/8/3N4/8/8/5PPP/6K1 w - - 0 1", "Nxc7"), # White Knight takes Rook - ("6k1/2b2ppp/8/3N4/8/8/5PPP/6K1 w - - 0 1", "Nxc7"), # White Knight takes Bishop - ("6k1/2n2ppp/8/3N4/8/8/5PPP/6K1 w - - 0 1", "Nxc7"), # White Knight takes Knight - ("6k1/2p2ppp/8/3N4/8/8/5PPP/6K1 w - - 0 1", "Nxc7"), # White Knight takes Pawn - ("5k2/2q5/3P4/8/8/8/8/5K2 w - - 0 1", "dxc7"), # White Pawn takes Queen - ("5k2/2r5/3P4/8/8/8/8/5K2 w - - 0 1", "dxc7"), # White Pawn takes Rook - ("5k2/2b5/3P4/8/8/8/8/5K2 w - - 0 1", "dxc7"), # White Pawn takes Bishop - ("5k2/2k5/3P4/8/8/8/8/5K2 w - - 0 1", "dxc7"), # White Pawn takes Knight - ("5k2/2p5/3P4/8/8/8/8/5K2 w - - 0 1", "dxc7"), # White Pawn takes Pawn - - ("6k1/2q2pp1/7p/8/8/7P/2Q2PP1/6K1 b - - 0 1", "Qxc2"), # Black Queen takes Queen - ("6k1/2q2pp1/7p/8/8/7P/2R2PP1/6K1 b - - 0 1", "Qxc2"), # Black Queen takes Rook - ("6k1/2q2pp1/7p/8/8/7P/2B2PP1/6K1 b - - 0 1", "Qxc2"), # Black Queen takes Bishop - ("6k1/2q2pp1/7p/8/8/7P/2N2PP1/6K1 b - - 0 1", "Qxc2"), # Black Queen takes Knight - ("6k1/2q2pp1/7p/8/8/7P/2P2PP1/6K1 b - - 0 1", "Qxc2"), # Black Queen takes Pawn -] - -SIMPLE_FORKS = [ - ("6k1/5pp1/1b1n3p/8/2PP4/7P/5PP1/6K1 w - - 0 1", "c5"), # Pawn Fork - ("r3k1nr/ppp2ppp/2np4/2bNp3/2B1P1b1/3P1N2/PPP2PPP/R1B1K2R w KQkq - 0 1", "Nxc7+"), # White Knight forks King and Rook - ("8/8/4K3/7n/6k1/3Q4/8/8 b - - 0 1", "Nf4+"), # Black Knight forks King and Queen - ("4r3/k7/4r3/8/2K3N1/8/8/8 b - - 0 1", "Re4+"), # Black Rook forks King and Knight - ("1k1b4/8/7R/8/8/8/8/2K5 b - - 0 1", "Bg5+"), # Black Bishop forks King and Rook - ("8/8/3K4/7k/3nb3/8/8/8 w - - 0 1", "Ke5"), # White King forks Bishop and Knight -] - -COMPLEX_FORKS = [ - ("r5k1/p2n1p1p/1pb1pp2/7N/2P5/P7/5PPP/3RK2R w - - 0 1", "Rxd7"), # Part 1: White Rook takes Knight to Setup Knight Fork if Bishop Takes - ("r5k1/p2b1p1p/1p2pp2/7N/2P5/P7/5PPP/4K2R w - - 0 2", "Nxf6+"), # Part 2: White Knight forks King and Bishop - ("r7/p2b1pkp/1p2pN2/8/2P5/P7/5PPP/4K2R w - - 1 3", "Nxd7"), # Part 3: White Knight takes Bishop and is up a Knight) - - ("r5k1/p2qn2p/1r4p1/3bBp2/1Qp2PP1/2P2B2/7P/1R1R2K1 w - - 0 1", "Qxe7"), # Part 1: White Queen takes Knight, Black Queen takes Queen - ("r5k1/p3q2p/1r4p1/3bBp2/2p2PP1/2P2B2/7P/1R1R2K1 w - - 0 2", "Bxd5+"), # Part 2: White Bishop takes Bishop, forking King and Rook - #("r4k2/p3q2p/1r4p1/3BBp2/2p2PP1/2P5/7P/1R1R2K1 w - - 1 3", "Bxa8"), # Part 3: White Bishop takes Rook, Black Rook takes Rook #ToDo: Alternative Rxb6 leads to similar position (2nd best stockfish move +0.6) Stockfish +1.9 for Rxa8 - ("B4k2/p3q2p/6p1/4Bp2/2p2PP1/2P5/7P/1r1R2K1 w - - 0 4", "Rxb1"), # Part 4: White Rook takes Rook, White is up 2 Bishops and a Rook to Blacks Queen and Pawn -] - -# Pins -# - Relative Pin -# - Absolute Pin -# - Double Pin - -# Discovered Checks -# - Discovered Double Check - -# Mates -# - Mate in 4 -# - Mate in 5 -# - Smothered Mate with a Pin -# - Two Pawn Checkmate - -# Endgames -# - K+Q vs K -# - R+R+K vs K -# - Q+R+K vs K - -# Cross Check -# Classical Games - -OTHER = [ - # Forcing a draw/stalemate - - # Other - ("3r1k2/4npp1/1ppr3p/p6P/P2PPPP1/1NR5/5K2/2R5 w - - 0 1", "d5"), - ("2q1rr1k/3bbnnp/p2p1pp1/2pPp3/PpP1P1P1/1P2BNNP/2BQ1PRK/7R b - - 0 1", "f5"), - ("rnbqkb1r/p3pppp/1p6/2ppP3/3N4/2P5/PPP1QPPP/R1B1KB1R w KQkq - 0 1", "e6"), - ("r1b2rk1/2q1b1pp/p2ppn2/1p6/3QP3/1BN1B3/PPP3PP/R4RK1 w - - 0 1", "a4"), - ("2r3k1/pppR1pp1/4p3/4P1P1/5P2/1P4K1/P1P5/8 w - - 0 1", "g6"), - ("1nk1r1r1/pp2n1pp/4p3/q2pPp1N/b1pP1P2/B1P2R2/2P1B1PP/R2Q2K1 w - - 0 1", "Nf6"), - ("4b3/p3kp2/6p1/3pP2p/2pP1P2/4K1P1/P3N2P/8 w - - 0 1", "f5"), - ("2kr1bnr/pbpq4/2n1pp2/3p3p/3P1P1B/2N2N1Q/PPP3PP/2KR1B1R w - - 0 1", "f5"), - ("3rr1k1/pp3pp1/1qn2np1/8/3p4/PP1R1P2/2P1NQPP/R1B3K1 b - - 0 1", "Ne5"), - ("2r1nrk1/p2q1ppp/bp1p4/n1pPp3/P1P1P3/2PBB1N1/4QPPP/R4RK1 w - - 0 1", "f4"), - ("r3r1k1/ppqb1ppp/8/4p1NQ/8/2P5/PP3PPP/R3R1K1 b - - 0 1", "Bf5"), - ("r2q1rk1/4bppp/p2p4/2pP4/3pP3/3Q4/PP1B1PPP/R3R1K1 w - - 0 1", "b4"), - #("rnb2r1k/pp2p2p/2pp2p1/q2P1p2/8/1Pb2NP1/PB2PPBP/R2Q1RK1 w - - 0 1", "Qd2 Qe1"), - ("2r3k1/1p2q1pp/2b1pr2/p1pp4/6Q1/1P1PP1R1/P1PN2PP/5RK1 w - - 0 1", "Qxg7+"), - ("r1bqkb1r/4npp1/p1p4p/1p1pP1B1/8/1B6/PPPN1PPP/R2Q1RK1 w kq - 0 1", "Ne4"), - ("r2q1rk1/1ppnbppp/p2p1nb1/3Pp3/2P1P1P1/2N2N1P/PPB1QP2/R1B2RK1 b - - 0 1", "h5"), - ("r1bq1rk1/pp2ppbp/2np2p1/2n5/P3PP2/N1P2N2/1PB3PP/R1B1QRK1 b - - 0 1", "Nb3"), - ("3rr3/2pq2pk/p2p1pnp/8/2QBPP2/1P6/P5PP/4RRK1 b - - 0 1", "Rxe4"), - ("r4k2/pb2bp1r/1p1qp2p/3pNp2/3P1P2/2N3P1/PPP1Q2P/2KRR3 w - - 0 1", "g4"), - ("3rn2k/ppb2rpp/2ppqp2/5N2/2P1P3/1P5Q/PB3PPP/3RR1K1 w - - 0 1", "Nh6"), - ("2r2rk1/1bqnbpp1/1p1ppn1p/pP6/N1P1P3/P2B1N1P/1B2QPP1/R2R2K1 b - - 0 1", "Bxe4"), - ("r1bqk2r/pp2bppp/2p5/3pP3/P2Q1P2/2N1B3/1PP3PP/R4RK1 b kq - 0 1", "f6"), - ("r2qnrnk/p2b2b1/1p1p2pp/2pPpp2/1PP1P3/PRNBB3/3QNPPP/5RK1 w - - 0 1", "f4") -] \ No newline at end of file diff --git a/archive/test/test_evaluation.py b/archive/test/test_evaluation.py deleted file mode 100644 index fb48ed8..0000000 --- a/archive/test/test_evaluation.py +++ /dev/null @@ -1,25 +0,0 @@ -import chess - -import archive.evaluation as evaluation - -class TestEvaluation: - def test_material_balance_new_game(self): - board = chess.Board() - score = evaluation.evaluate_material_balance(board) - assert score == 0 - - def test_piece_square_table_new_game(self): - board = chess.Board() - score = evaluation.evaluate_piece_square_table(board) - assert score == 0 - - def test_mobility_new_game(self): - board = chess.Board() - score = evaluation.evaluate_mobility(board) - assert score == 0 - - def test_board_control_new_game(self): - board = chess.Board() - score = evaluation.board_control(board) - assert score == 0 - diff --git a/archive/test/test_puzzles.py b/archive/test/test_puzzles.py deleted file mode 100644 index 7bb62a4..0000000 --- a/archive/test/test_puzzles.py +++ /dev/null @@ -1,55 +0,0 @@ -import chess -import pytest - -from archive.config import Config -import archive.helper as helper -from .puzzles import MATE_IN_1, MATE_IN_2, MATE_IN_3, SIMPLE_CAPTURES, SIMPLE_FORKS, COMPLEX_FORKS - -class TestPuzzles: - @pytest.mark.parametrize("fen,expected_move", MATE_IN_1) - def test_negamax_mateIn1(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=1)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move - - @pytest.mark.parametrize("fen,expected_move", MATE_IN_2) - def test_negamax_mateIn2(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=3)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move - - @pytest.mark.parametrize("fen,expected_move", MATE_IN_3) - def test_negamax_mateIn3(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=5)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move - - @pytest.mark.parametrize("fen,expected_move", SIMPLE_CAPTURES) - def test_negamax_simple_captures(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=3)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move - - @pytest.mark.parametrize("fen,expected_move", SIMPLE_FORKS) - def test_negamax_simple_forks(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=3)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move - - @pytest.mark.parametrize("fen,expected_move", COMPLEX_FORKS) - def test_negamax_complex_forks(self, fen, expected_move): - board = chess.Board(fen) - negamaxEngine = helper.get_negamax_engine(config=Config(depth=5)) - actual_move = negamaxEngine.find_move(board) - print("{}: expected {} actual {} - {}".format(negamaxEngine.get_name(), expected_move, board.san(actual_move), fen)) - assert board.san(actual_move) == expected_move diff --git a/archive/test/test_quiescence_search.py b/archive/test/test_quiescence_search.py deleted file mode 100644 index afc35c0..0000000 --- a/archive/test/test_quiescence_search.py +++ /dev/null @@ -1,45 +0,0 @@ -from chess import Board - -import archive.quiescence_search as quiescence_search - -class TestEvaluation: - - def test_quiescence_search_checkmate(self): - board = Board("r1bqkbnr/ppp2Qpp/2np4/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4") - score = quiescence_search.quiescence_search(board, -999999, 999999, 0) - assert score == -9999 - - def test_quiescence_search_checkmate_with_depth(self): - board = Board("r1bqkbnr/ppp2Qpp/2np4/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4") - score = quiescence_search.quiescence_search(board, -999999, 999999, 1) - assert score == -10000 - - def test_quiescence_search_stalemate(self): - board = Board("k7/8/KR6/8/8/8/8/8 b - - 0 37") - score = quiescence_search.quiescence_search(board, -999999, 999999, 0) - assert score == 0 - - def test_quiescence_search_insufficient_material(self): - board = Board("8/8/K7/8/8/k7/8/8 b - - 0 37") - score = quiescence_search.quiescence_search(board, -999999, 999999, 0) - assert score == 0 - - # ToDo: Add test for fivefold repetition - - def test_quiescence_search_seventyfive_moves(self): - board = Board("k7/8/K7/R7/8/8/8/8 b - - 0 150") - board.halfmove_clock = 150 - score = quiescence_search.quiescence_search(board, -999999, 999999, 0) - assert score == 0 - - def test_quiescence_search_new_game(self): - board = Board() - score = quiescence_search.quiescence_search(board, -999999, 999999, 0) - assert score == 0 - - def test_quiescence_search_new_game_return_beta(self): - board = Board() - score = quiescence_search.quiescence_search(board, -999999, -999999, 0) - assert score == -999999 - - diff --git a/archive/transposition_table.py b/archive/transposition_table.py deleted file mode 100644 index 7530867..0000000 --- a/archive/transposition_table.py +++ /dev/null @@ -1,40 +0,0 @@ -import random -import time -from chess import Move -from enum import Enum - -class FLAG(Enum): - LOWER_BOUND = -1 - EXACT = 0 - UPPER_BOUND = 1 - -class TransTableEntry(): - __slots__ = ['z_key', 'best_move', 'depth', 'value', 'flag', 'age'] - - def __init__(self, hash: int): - self.z_key: int = hash - self.best_move: Move = Move.null() - self.depth: int = 0 - self.value: int = 0 - self.flag: FLAG = FLAG.EXACT - self.age: float = time.time() - -class TransTable(): - __slots__ = ['table', 'size', 'maxSize'] - - def __init__(self, init_size = 0, max_size = 10 ** 7): - self.table = {} - self.size: int = init_size - self.maxSize: int = max_size - - def update_ttable(self, entry: TransTableEntry): - if self.size == self.maxSize: - self.table.pop(random.choice(self.table.keys())) - self.size -= 1 - - self.table[entry.z_key] = entry - self.size += 1 - - def getEntry(self, hash: int): - return self.table.get(hash) - \ No newline at end of file diff --git a/build.bat b/build.bat deleted file mode 100644 index 687a15b..0000000 --- a/build.bat +++ /dev/null @@ -1 +0,0 @@ -pyinstaller --onedir --workpath ./build --distpath ./dist --specpath ./build -n chess-engine ./main.py \ No newline at end of file diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..8ec785c --- /dev/null +++ b/codecov.yml @@ -0,0 +1,18 @@ +coverage: + status: + project: + default: + target: auto # never drop below the current level + threshold: 1% + patch: + default: + target: 85% # new/changed lines must be 85% covered + +comment: + layout: "condensed_header, diff, files" + require_changes: true # only comment when coverage moves + +# Both matrix jobs upload; treat them as one combined report. +flag_management: + default_rules: + carryforward: true diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..27b3f80 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,63 @@ +# Design + +How the engine is put together, what each technique buys, and the backlog of +ideas not yet implemented. For a *prioritised* list of next steps see +[tasks.md](tasks.md); for strength and speed numbers see +[engine-strength.md](engine-strength.md) and [performance.md](performance.md). + +## Architecture + +`Negamax` is the search core. It holds four collaborators, each a plain object +with a small interface, injected at construction: + +| collaborator | responsibility | +|---|---| +| `PestoEvaluator` | static evaluation from the side-to-move's view | +| `MoveOrderer` | orders moves to maximise alpha-beta cut-offs; owns killer / history tables | +| `TranspositionTable` / `SharedTT` | Zobrist-keyed cache; same `key` / `probe` / `store` interface, one in-process, one in shared memory | +| `Clock` | turns `go` limits into a deadline / node budget and answers `should_stop` | + +`lazy_smp.search` is the coordinator: it spawns worker processes, each running +its own iterative deepening `Negamax` against a shared `SharedTT`, and returns +the best completed result as a `SearchResult`. `__main__.py` is the UCI protocol +layer and the only place that prints `info` / `bestmove`. + +## Implemented + +### [Search](https://www.chessprogramming.org/Search) + +- [Negamax](https://www.chessprogramming.org/Negamax) - fail-soft +- [Alpha-Beta Pruning](https://www.chessprogramming.org/Alpha-Beta) +- [Quiescence Search](https://www.chessprogramming.org/Quiescence_Search) - fail-soft, depth-bounded, check-aware +- [Transposition Table](https://www.chessprogramming.org/Transposition_Table) - Zobrist-keyed, EXACT / LOWER / UPPER bounds +- [Iterative Deepening](https://www.chessprogramming.org/Iterative_Deepening) - per worker, with UCI time management +- [Move Ordering](https://www.chessprogramming.org/Move_Ordering) - TT move, [MVV-LVA](https://www.chessprogramming.org/MVV-LVA) captures, promotions, [killers](https://www.chessprogramming.org/Killer_Heuristic), [history](https://www.chessprogramming.org/History_Heuristic) +- [Lazy SMP](https://www.chessprogramming.org/Lazy_SMP) - workers share a lock-free shared-memory TT +- Opening book (Stockfish-derived Polyglot) + +### [Evaluation](https://www.chessprogramming.org/Evaluation) + +- [PeSTO](https://www.chessprogramming.org/PeSTO%27s_Evaluation_Function) - tapered mid-/end-game [piece-square tables](https://www.chessprogramming.org/Piece-Square_Tables), interpolated by game phase, [incrementally updated](https://www.chessprogramming.org/Incremental_Updates) on `EvalBoard.push` / `pop` + +## Backlog + +### Search + +- [Static Exchange Evaluation](https://www.chessprogramming.org/Static_Exchange_Evaluation) for capture ordering +- [Relative History Heuristic](https://www.chessprogramming.org/Relative_History_Heuristic) +- [Aspiration Windows](https://www.chessprogramming.org/Aspiration_Windows) +- [Null Move Pruning](https://www.chessprogramming.org/Null_Move_Pruning) +- [Principal Variation Search](https://www.chessprogramming.org/Principal_Variation_Search) +- [Late Move Reductions](https://www.chessprogramming.org/Late_Move_Reductions) +- [Syzygy endgame tablebases](https://www.chessprogramming.org/Endgame_Tablebases) + +### Evaluation + +- [King safety](https://www.chessprogramming.org/King_Safety), [pawn structure](https://www.chessprogramming.org/Pawn_Structure) (doubled / isolated / passed), [mobility](https://www.chessprogramming.org/Mobility), [tempo](https://www.chessprogramming.org/Tempo) +- [Evaluation](https://www.chessprogramming.org/Evaluation_Hash_Table) / [material](https://www.chessprogramming.org/Material_Hash_Table) / [pawn](https://www.chessprogramming.org/Pawn_Hash_Table) hash tables + +### Alternative search algorithms to evaluate + +- [NegaScout](https://www.chessprogramming.org/NegaScout) +- [NegaC*](https://www.chessprogramming.org/NegaC*) +- [MTD(f)](https://www.chessprogramming.org/MTD\(f\)) diff --git a/STRENGTH.md b/docs/engine-strength.md similarity index 97% rename from STRENGTH.md rename to docs/engine-strength.md index 9afbd76..20c848b 100644 --- a/STRENGTH.md +++ b/docs/engine-strength.md @@ -1,4 +1,4 @@ -# Playing Strength Estimate +# Engine Strength **Estimated rating: ~1800–2000 Elo** (FIDE / CCRL-ish scale) at blitz, most likely around **1900**, with wide error bars (±150). @@ -52,7 +52,7 @@ have been run yet. See [Measuring it properly](#measuring-it-properly) below. ## Where the number would move -Completing the [README To Do list](README.md#to-do): +Completing the [roadmap](tasks.md): - Null-move pruning + LMR + PVS + aspiration windows: historically **+250–400 Elo**. - King-safety + pawn-structure evaluation terms: another **+100–200**. diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..3c17920 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,52 @@ +# Performance + +All figures below are a fresh benchmark on one machine (Apple Silicon, 10 +cores, Python 3.13), fixed-depth search from the starting position. "Before" +is the pre-review engine (plain negamax, no move ordering, no working TT, +unbounded quiescence, from-scratch material+PST eval); "After" is the current +engine. Both columns were run on the *same* machine, so this is a like-for-like +comparison rather than a comparison against the older M1 numbers. + +For reference, the original M1 run recorded depth 5 = 1.42s, depth 6 = 10.0s, +depth 7 = 215s single-process (and the old "parallel" mode was *slower*: depth +7 = 430s). + +## Single process, fixed-depth `search()` from the start position + +| depth | Before (time / nodes) | After (time / nodes) | speed-up | +|------:|----------------------:|---------------------:|---------:| +| 2 | 0.002s / 87 | 0.002s / 79 | ~1x | +| 3 | 0.015s / 802 | 0.012s / 657 | 1.3x | +| 4 | 0.091s / 3,991 | 0.064s / 2,387 | 1.4x | +| 5 | 1.157s / 46,875 | 0.321s / 15,139 | 3.6x | +| 6 | 8.169s / 317,377 | 1.770s / 72,048 | 4.6x | +| 7 | 152.4s / 5,451,009 | 9.565s / 453,119 | **16x** | + +The gap widens every ply because move ordering (TT move, MVV-LVA, killers, +history) and the transposition table compound. "Nodes" is `board.push` calls +(main search + quiescence). + +## Single-process iterative deepening (removed - kept here for reference) + +| target depth | time | nodes | +|-------------:|-----:|------:| +| 5 | 0.24s | 12k | +| 6 | 1.38s | 53k | +| 7 | 5.11s | 236k | +| 8 | 38.6s | 2.1M | + +This was the old `go` path (roughly 2x faster than a cold fixed-depth search, +since each iteration seeds the next through the TT). Lazy SMP beat it at every +depth on this machine, so it was dropped - `go` now always runs Lazy SMP. + +## What `go` / `go depth N` runs today: Lazy SMP from the start position + +| depth | Before ("parallel", root-split) | After (Lazy SMP, 9 workers, shared TT) | +|------:|--------------------------------:|--------------------------------------:| +| 6 | 10.6s | 0.84s | +| 7 | 430s | 3.77s | +| 8 | — | 17.9s | + +The old root-split parallel mode lost to its own single-threaded search (full +windows, no shared table). Lazy SMP is ~1.5x faster than the old single-process +iterative deepening at depth 6-7 and ~2x by depth 8, on this 10-core machine. diff --git a/docs/tasks.md b/docs/tasks.md new file mode 100644 index 0000000..d9ade89 --- /dev/null +++ b/docs/tasks.md @@ -0,0 +1,96 @@ +# Tasks + +The next five changes, in the order most likely to gain the most playing +strength. Each is a self-contained addition to `Negamax.search` / +`Negamax.quiesce` unless noted. + +## 1. Null-move pruning + +If giving the opponent a free move (a "null move") still fails high at reduced +depth (`R = 2..3`), the position is almost certainly a cut-off - return `beta` +without searching the real moves. Skip it when side-to-move is in check, in a +likely zugzwang (king + pawns only), or when depth is very low. Add a +verification search at high depth to avoid zugzwang blunders. Needs a +`board.push(chess.Move.null())` path and a `_null_ok` guard in the search. +Typically the single largest Elo jump available (~50-100). + +## 2. Principal Variation Search (NegaScout) + +Search the first (best-ordered) move with the full `(-beta, -alpha)` window, +then every later move with a null window `(-alpha-1, -alpha)`; only re-search +with the full window on the rare fail-high. With the move ordering already in +place (TT move, MVV-LVA, killers, history) the first move is usually best, so +most nodes get the cheaper scout search. ~20-40 Elo and it compounds with +everything below. + +## 3. Late Move Reductions (LMR) + +Once past the first few moves at a node, search quiet, non-checking, non-TT +moves at `depth - 1 - reduction` (reduction grows with move index and depth, +shrink it for killers / good history). Re-search at full depth if the reduced +search beats `alpha`. Combined with PVS this is usually the biggest tree +reduction after null-move - effective branching factor drops sharply, so +iterative deepening reaches 2-4 plies deeper in the same time. + +## 4. Correct draw, repetition and mate scoring + +- Detect threefold repetition and the 50-move rule *inside* the search tree + (`board.is_repetition(3)`, `board.halfmove_clock`), not just the automatic + five-fold / seventy-five-move draws in `is_drawn`. +- Score every draw a flat `0` (currently negamax returns `0 - depth`), with an + optional small contempt value. +- Store mate scores in the TT as distance-to-mate relative to the current ply + (`score +/- ply` on store/probe) so `MATE_GUARD` can be removed and mate + cut-offs actually propagate. This fixes real half-point losses and lets the + engine convert forced mates faster. + +## 5. Evaluation upgrade + +PeSTO piece-square tables capture a lot of positional understanding but miss +king safety and pawn structure, which is where a mid-level engine gains most. +Add, keeping the incremental accumulator where possible and a pawn-hash cache +for the rest: + +- King safety: attacker count / attack weight on the squares around the king, + pawn-shield intactness, open files next to the king. +- Passed pawns (bonus scaled by rank and king distance), isolated / doubled / + backward pawns. +- Bishop pair, rook on open / half-open file, knight outposts. +- Tempo bonus. + +Then wire in [Syzygy endgame tablebases](https://python-chess.readthedocs.io/en/latest/syzygy.html) +(`chess.syzygy`) for perfect play with <= 6 pieces. + +--- + +## Recently completed + +From the previous review passes: move ordering, transposition table, iterative +deepening + UCI time management, perft fix + tests, quiescence rewrite (bounded, +check-aware, fail-soft), tapered PeSTO evaluation with an incremental +accumulator, standard `info` output, resource-leak fixes, Lazy SMP with a +lock-free shared-memory TT (now the only search path - `go` always runs it), and +a rebuild of the search as composed collaborators (`Negamax` holds an evaluator +/ move orderer / TT / clock) instead of a mixin stack, with unit tests for each +piece. + +Packaging & tooling: `src/pychess/` package layout, `pyproject.toml` (replacing +`requirements.txt` / `pytest.ini`), a `pychess` console entry point, Apache-2.0 +license, `py.typed`, and Ruff (lint + format) + Mypy + pytest-cov (85% gate) in +CI, with `pre-commit` mirroring it locally. + +## Housekeeping + +### GitHub repo settings (do these in the repo UI - not tracked in files) + +- [ ] Rename the repo `pyChess` -> `pychess` so it matches the package name; + update the local remote afterwards. +- [ ] Tag `v0.1.0` and cut a **GitHub Release** from the `CHANGELOG.md` entry. + +### Opening book (`opening_book/bookfish.bin`) + +An ~18 MB binary lives in git history (see [opening_book/README.md](../opening_book/README.md)). +It works fine as-is, but for a cleaner repo consider one of: migrate it to Git +LFS, fetch it on first run instead of vendoring it, or document it as an +optional external download. Any of these needs a history rewrite to actually +shrink the pack, so it is a deliberate call, not a drive-by fix. diff --git a/engines.py b/engines.py deleted file mode 100644 index 0fb6fe6..0000000 --- a/engines.py +++ /dev/null @@ -1,19 +0,0 @@ -from evaluation import PeSTOEvaluationMixin -from move_ordering import MoveOrderingMixin -from transposition import TranspositionTableMixin -from parallel import IterativeDeepeningMixin, LazySMPMixin -from search import NegamaxMixin, QuiescenceSearchMixin, RandomMixin - -class NegamaxEngine( - LazySMPMixin, - IterativeDeepeningMixin, - MoveOrderingMixin, - TranspositionTableMixin, - NegamaxMixin, - QuiescenceSearchMixin, - PeSTOEvaluationMixin, -): - pass - -class RandomEngine(RandomMixin): - pass diff --git a/main.py b/main.py deleted file mode 100644 index 8ef3784..0000000 --- a/main.py +++ /dev/null @@ -1,208 +0,0 @@ -import time, sys, signal, multiprocessing - -from chess import Board, polyglot -from eval_board import EvalBoard -from engines import NegamaxEngine -from multiprocessing.pool import Pool -from operator import itemgetter -from perft import perft - -def catchKeyboardInterrupt(signal, frame): - sys.exit(0) -signal.signal(signal.SIGINT, catchKeyboardInterrupt) - -# UCI "go" parameters that take a single integer argument. -GO_INT_PARAMS = {"depth", "nodes", "movetime", - "wtime", "btime", "winc", "binc", "movestogo"} - -BOOK_PATH = "opening_book/bookfish.bin" - - -class UCI: - def __init__(self) -> None: - self.board = EvalBoard() - self.engine = NegamaxEngine() - self.depth = 4 - - - def processCommand(self, input: str) -> str: - args = input.split(" ") - match args[0]: - case "uci": - print("id name CJBot") - print("id author cjunius") - print("uciok") - case "debug": - pass - case "isready": - print("readyok") - case "setoption": - pass - case "register": - pass - case "ucinewgame": - self.board = EvalBoard() - self.engine = NegamaxEngine() - case "position": - self.position_handler(args) - case "go": - self.go_handler(False, args) - case "go_parallel": - self.go_handler(True, args) - case "stop": - pass - case "quit": - quit(0) - case "ponderhit": - pass - case "printBoard": - print(str(self.board)) - case "printLegalMoves": - moves = [self.board.san(m) for m in self.board.legal_moves] - print(str(moves)) - case "printMoveStack": - replay = self.board.root() - moves = [replay.san_and_push(m) for m in self.board.move_stack] - print(str(moves)) - case "perft": - self.perft_handler(args) - case "selfPlay": - self.selfPlay_handler(args) - case "selfPlay_parallel": - self.selfPlay_parallel_handler(args) - case _: - print("Unknown command") - - - def position_handler(self, args): - - if len(args) > 1 and args[1] == "fen": - try: - moves_idx = args.index("moves") - fen_string = " ".join(args[2:moves_idx]) - except ValueError: - fen_string = " ".join(args[2:]) - self.board = EvalBoard(fen_string) - else: - self.board = EvalBoard() - - moves_found = False - for i in range(1, len(args)): - - if moves_found: - self.board.push_uci(args[i]) - else: - if args[i] == "moves": - moves_found = True - - - def parse_go(self, args) -> dict: - limits = {} - i = 1 - while i < len(args): - token = args[i] - if token in GO_INT_PARAMS and i + 1 < len(args): - try: - limits[token] = int(args[i + 1]) - except ValueError: - pass - i += 2 - elif token == "infinite": - limits["infinite"] = True - i += 1 - else: - i += 1 - return limits - - - def book_move(self): - """Return a Polyglot book move for the current position, or None.""" - try: - with polyglot.MemoryMappedReader(BOOK_PATH) as reader: - return reader.weighted_choice(self.board).move - except (IndexError, FileNotFoundError, OSError): - return None - - - def perft_handler(self, args): - depth = int(args[1]) if len(args) > 1 else 4 - nodes, elapsed = perft(self.board, depth) - print("info depth {} nodes {} time {}".format(depth, nodes, elapsed)) - - - def go_handler(self, parallel: bool, args): - print("info starting search") - - move = self.book_move() - if move is not None: - print("info using book move") - print("bestmove " + move.uci()) - return - - limits = self.parse_go(args) - start = time.time() - if parallel: - best_score, pv = self.engine.parallel_search(self.board, limits) - else: - best_score, pv = self.engine.search_with_time(self.board, limits) - end = time.time() - pv_uci = " ".join(m.uci() for m in pv) - print('info score {} pv {} time {}'.format(best_score, pv_uci, end - start)) - print("bestmove " + (pv[0].uci() if pv else "0000")) - - - def selfPlay_handler(self, args): - while not self.board.is_game_over(): - move = self.book_move() - if move is not None: - print("info using book move") - print("bestmove " + move.uci()) - self.board.push(move) - continue - - start = time.time() - best_score, pv = self.engine.search_with_time(self.board, {"depth": self.depth}) - end = time.time() - if not pv: - break - print('info score {} pv {} time {}'.format( - best_score, " ".join(m.uci() for m in pv), end - start)) - print("bestmove " + pv[0].uci()) - self.board.push(pv[0]) - - print(str(self.board.result())) - - - def selfPlay_parallel_handler(self, args): - while not self.board.is_game_over(): - move = self.book_move() - if move is not None: - print("info using book move") - print("bestmove " + move.uci()) - self.board.push(move) - continue - - best_score, pv = self.engine.parallel_search(self.board, {"depth": self.depth}) - if not pv: - break - print('bestmove ' + pv[0].uci()) - self.board.push(pv[0]) - - print(str(self.board.result())) - - -def main() -> None: - uic = UCI() - while True: - command = input() - if not command == "quit": - uic.processCommand(command) - else: - break - - -if __name__ == "__main__": - # On Windows calling this function is necessary. - multiprocessing.freeze_support() - - main() \ No newline at end of file diff --git a/opening_book/README.md b/opening_book/README.md new file mode 100644 index 0000000..c6a62c7 --- /dev/null +++ b/opening_book/README.md @@ -0,0 +1,32 @@ +# Opening book + +`bookfish.bin` is an ~18 MB [Polyglot](http://hgm.nubati.net/book_format.html) +opening book (a "bookfish"-style book, i.e. derived from Stockfish analysis). +The engine reads it **read-only** for the opening: if the current position is in +the book it plays a weighted-random book move instead of searching. + +## Overriding / disabling + +Set `PYCHESS_BOOK` to point at a different `.bin`, or at a path that does not +exist to disable the book entirely (a missing book is not an error - the engine +just searches from move one). + +```bash +PYCHESS_BOOK=/path/to/other.bin pychess +``` + +## Licensing + +The book is bundled data, not part of the engine's source, and is provided for +convenience only. Polyglot books generated from engine analysis are widely +distributed as data; if you intend to redistribute this project commercially, +confirm the provenance of this file or swap in a book whose terms you are sure +of. + +## Notes for maintainers + +An 18 MB binary in git history is a wart. Options if it becomes a problem: +migrate to [Git LFS](https://git-lfs.com/), fetch the book on first run instead +of vendoring it, or make it a documented external download. It is already in +history, so shrinking that needs a coordinated rewrite - not worth doing +casually. diff --git a/parallel.py b/parallel.py deleted file mode 100644 index 7e411a2..0000000 --- a/parallel.py +++ /dev/null @@ -1,243 +0,0 @@ -import multiprocessing -import time - -from multiprocessing.pool import Pool - -import chess -from chess import Move -from search import BaseSearch, SearchAbort, MATE_VALUE - - -class BaseParallel(BaseSearch): - def __init__(self): - self.board = None - self.depth = 5 - - def parallel_search(self, board, limits=None): - raise NotImplementedError - - -def _lazy_smp_worker(payload): - """One Lazy SMP helper: iterative deepening against the shared TT. - - Runs in its own process. Workers are seeded with different start depths so - they populate the shared table along slightly different paths; the shared - entries then speed up every other worker. - """ - from engines import NegamaxEngine - from eval_board import EvalBoard - from shared_tt import SharedTT, SharedFlag - - (root_fen, moves, root_slice, max_depth, deadline, - tt_name, tt_slots, worker_id, stop_name) = payload - - tt = SharedTT(slots=tt_slots, name=tt_name, create=False) - stop = SharedFlag(name=stop_name, create=False) - board = EvalBoard(root_fen) - for uci in moves: - board.push_uci(uci) - - engine = NegamaxEngine() - engine._shared_tt = tt - engine._stop_flag = stop - engine._deadline = deadline - engine._node_limit = None - engine._nodes = 0 - engine._can_abort = False - if root_slice is not None: - engine._root_moves = {chess.Move.from_uci(u) for u in root_slice} - - best = (0, [], 0) - try: - for depth in range(1 + (worker_id % 3), max_depth + 1): - try: - score, pv = engine.search(board, -99999, 99999, depth) - except SearchAbort: - break - engine._can_abort = True - best = (score, [m.uci() for m in pv], depth) - if stop.is_set() or time.time() >= deadline: - break - if score >= MATE_VALUE - 100: # forced win found - everyone stops - stop.set() - break - if score <= -(MATE_VALUE - 100): # every move in this slice loses - break - finally: - tt.close() - stop.close() - return best - - -def _smp_result_key(result): - """Rank Lazy SMP worker results: a forced win beats everything (fastest - first), then deepest search, then best score; a forced loss is ranked - last (least bad, deepest).""" - score, _pv, depth = result - if score >= MATE_VALUE - 100: - return (2, score, depth) - if score <= -(MATE_VALUE - 100): - return (0, depth, score) - return (1, depth, score) - - -class LazySMPMixin(BaseParallel): - """`Lazy SMP `_. - - ``N`` worker processes each run their own iterative deepening on the root - position while sharing one lock-free transposition table in shared memory. - Divergent start depths plus TT contention make the workers explore - different subtrees; the deepest completed result wins. - - Process start-up (spawn) costs a fair bit on macOS/Windows, so this only - pays off for multi-second searches - short searches fall back to the - single-process ``search_with_time``. - """ - - SMP_TT_SLOTS = 1 << 20 # 1M entries * 16 bytes = 16 MB - - def parallel_search(self, board, limits=None): - from shared_tt import SharedTT, SharedFlag - - limits = limits or {} - start = time.time() - - n_workers = max(1, multiprocessing.cpu_count() - 1) - deadline = self._deadline_for(board, limits, start) \ - or (start + self.DEFAULT_MOVETIME) - max_depth = min(int(limits.get("depth") or self.MAX_DEPTH), self.MAX_DEPTH) - - if n_workers < 2 or (deadline - start) < 0.75: - return self.search_with_time(board, limits) - - root_fen = board.root().fen() - moves = [m.uci() for m in board.move_stack] - - # Worker 0 searches every root move (authoritative PV); the rest split - # the root moves so the expensive top-level subtrees are divided while - # still sharing everything below the root through the TT. - legal = [m.uci() for m in board.legal_moves] - splitters = max(1, n_workers - 1) - slices = [None] - for i in range(1, n_workers): - slices.append(legal[(i - 1) % splitters::splitters] or None) - - tt = SharedTT(slots=self.SMP_TT_SLOTS, create=True) - stop = SharedFlag(create=True) - payloads = [(root_fen, moves, slices[i], max_depth, deadline, - tt.name, tt.slots, i, stop.name) - for i in range(n_workers)] - try: - with Pool(n_workers) as pool: - async_res = pool.map_async(_lazy_smp_worker, payloads) - while not async_res.ready() and time.time() < deadline: - time.sleep(0.02) - stop.set() - results = async_res.get() - finally: - stop.close() - stop.unlink() - tt.close() - tt.unlink() - - results = [r for r in results if r and r[1]] - if not results: - return self.search_with_time(board, limits) - - score, pv_uci, depth = max(results, key=_smp_result_key) - pv = [chess.Move.from_uci(u) for u in pv_uci] - print("info depth {} score cp {} time {} pv {}".format( - depth, int(score), round(time.time() - start, 3), " ".join(pv_uci))) - return score, pv - - -class IterativeDeepeningMixin(BaseParallel): - """Single-process iterative deepening with UCI time management. - - Each iteration reuses the previous one through the transposition table - (both for cut-offs and for move ordering via the stored best move), so - deepening is nearly free when the position is stable. Iterations are - aborted cleanly via ``SearchAbort`` once a limit is hit; the last fully - completed iteration is returned. - """ - - MAX_DEPTH = 64 - DEFAULT_MOVETIME = 4.0 # seconds, used for a bare "go" - BRANCHING_ESTIMATE = 2.5 # predict next iteration cost - - _can_abort = False - _deadline = None - _node_limit = None - _stop_flag = None - - def stop_signal(self): - if not self._can_abort: - return False - if self._stop_flag is not None and self._stop_flag.is_set(): - return True - if self._node_limit is not None and self._nodes >= self._node_limit: - return True - if self._deadline is not None and time.time() >= self._deadline: - return True - return False - - def _deadline_for(self, board, limits, start): - if limits.get("movetime") is not None: - return start + limits["movetime"] / 1000.0 - my = limits.get("wtime") if board.turn == chess.WHITE else limits.get("btime") - if my is not None: - inc = (limits.get("winc") if board.turn == chess.WHITE - else limits.get("binc")) or 0 - movestogo = limits.get("movestogo") or 30 - budget = my / (movestogo + 1) + 0.75 * inc - budget = min(budget, 0.4 * my) - return start + max(budget, 10) / 1000.0 - if limits.get("infinite"): - return start + 60.0 - if limits.get("depth") is None and limits.get("nodes") is None: - return start + self.DEFAULT_MOVETIME - return None - - def search_with_time(self, board, limits=None): - limits = limits or {} - start = time.time() - - self._deadline = self._deadline_for(board, limits, start) - self._node_limit = limits.get("nodes") - self._nodes = 0 - self._can_abort = False - - max_depth = limits.get("depth") - if max_depth is None: - max_depth = self.MAX_DEPTH - max_depth = min(int(max_depth), self.MAX_DEPTH) - - root_len = len(board.move_stack) - best_score, best_pv = 0, [] - - for depth in range(1, max_depth + 1): - iter_start = time.time() - try: - score, pv = self.search(board, -99999, 99999, depth) - except SearchAbort: - while len(board.move_stack) > root_len: - board.pop() - break - - best_score, best_pv = score, pv - self._can_abort = True - elapsed = time.time() - start - print("info depth {} score cp {} nodes {} time {} pv {}".format( - depth, int(score), self._nodes, round(elapsed, 3), - " ".join(m.uci() for m in pv))) - - if abs(score) >= MATE_VALUE - 100: - break - if self._node_limit is not None and self._nodes >= self._node_limit: - break - iter_time = time.time() - iter_start - if self._deadline is not None and \ - time.time() + iter_time * self.BRANCHING_ESTIMATE > self._deadline: - break - - return best_score, best_pv \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..1ecc535 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,101 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "pychess" +description = "A UCI chess engine: Lazy SMP negamax with a tapered PeSTO evaluation." +readme = "README.md" +requires-python = ">=3.12" +license = { file = "LICENSE" } +authors = [{ name = "cjunius" }] +keywords = ["chess", "uci", "engine", "negamax", "lazy-smp", "pesto"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Games/Entertainment :: Board Games", + "Typing :: Typed", +] +dynamic = ["version"] +dependencies = ["chess==1.10.0"] + +[project.optional-dependencies] +dev = [ + "pytest==9.0.3", + "pytest-cov>=6", + "ruff==0.14.4", + "mypy==1.18.2", + "pre-commit>=3", +] + +[project.scripts] +pychess = "pychess.__main__:main" + +[project.urls] +Repository = "https://github.com/cjunius/pyChess" +Issues = "https://github.com/cjunius/pyChess/issues" +Changelog = "https://github.com/cjunius/pyChess/blob/main/CHANGELOG.md" + +[tool.hatch.version] +path = "src/pychess/__init__.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/pychess"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "--cov=pychess --cov-report=term-missing --strict-markers --strict-config" +xfail_strict = true +filterwarnings = ["error"] + +[tool.coverage.run] +branch = true +source = ["src/pychess"] + +[tool.coverage.report] +fail_under = 85 +show_missing = true +exclude_also = [ + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", + "raise NotImplementedError", +] + +[tool.ruff] +line-length = 100 +target-version = "py312" +src = ["src", "tests"] + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "N", # pep8-naming + "UP", # pyupgrade + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "PIE", # flake8-pie + "RET", # flake8-return + "SIM", # flake8-simplify + "RUF", # ruff-specific +] + +[tool.ruff.lint.isort] +known-first-party = ["pychess"] + +[tool.mypy] +python_version = "3.12" +files = ["src", "tests"] +strict = true + +[[tool.mypy.overrides]] +# Test functions don't need full annotations, but their bodies are still checked. +module = ["tests.*"] +disallow_untyped_defs = false +disallow_incomplete_defs = false +disallow_untyped_calls = false diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index 2266419..0000000 --- a/pytest.ini +++ /dev/null @@ -1,2 +0,0 @@ -[pytest] -testpaths = test diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 1c20468..0000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -chess==1.10.0 -pytest==9.0.3 \ No newline at end of file diff --git a/search.py b/search.py deleted file mode 100644 index 746c013..0000000 --- a/search.py +++ /dev/null @@ -1,185 +0,0 @@ -import random -from typing import List -from chess import Move, polyglot - -from transposition import TT_EXACT, TT_LOWER, TT_UPPER - -# Upper bound on quiescence extension (plies past the normal horizon). -Q_MAX_DEPTH = 8 -# Delta-pruning margin: a bit more than a queen. -Q_DELTA_MARGIN = 1100 -# Score magnitude at/above which a value is mate-related. -MATE_VALUE = 9999 - - -class SearchAbort(Exception): - """Raised inside the search when a time or node limit is hit; the caller - discards the partial iteration and keeps the previous one.""" - - -class BaseSearch(object): - - _nodes = 0 - - def stop_signal(self): - return False - - def mvvlva(self, board, move): - return 0 - - def is_drawn(self, board): - return board.is_fivefold_repetition() \ - or board.is_stalemate() \ - or board.is_seventyfive_moves() \ - or board.is_insufficient_material() - - def order_moves(self, board, tt_move=None, ply=0): - return board.legal_moves - - def evaluate_leaf_node(self, board, alpha, beta, depth): - return self.evaluate(), [] - - # --- transposition-table / heuristic hooks ------------------------- - # Overridden by TranspositionTableMixin / MoveOrderingMixin. The no-op - # defaults let NegamaxMixin run without those mixins mixed in. - - def tt_key(self, board): - return None - - def tt_probe(self, key, depth, alpha, beta): - return False, 0, None - - def tt_store(self, key, depth, value, flag, move): - pass - - def record_killer(self, ply, move): - pass - - def record_history(self, board, move, depth): - pass - -class RandomMixin(BaseSearch): - def search(self, board, alpha=0, beta=0, depth=0, ply=0): - return 0, [random.choice(list(board.legal_moves))] - - -class NegamaxMixin(BaseSearch): - - def search(self, board, alpha: float, beta: float, depth: float, ply: float=0) -> tuple[float, list[Move]]: - - self._nodes += 1 - if ply and not (self._nodes & 4095) and self.stop_signal(): - raise SearchAbort - - if depth <= 0 or board.is_game_over(): - if board.is_checkmate(): - return -9999 - depth, [] - elif self.is_drawn(board): - return 0 - depth, [] - else: - return self.evaluate_leaf_node(board, alpha, beta, depth), [] - - alpha_orig = alpha - - tt_key = self.tt_key(board) - tt_cutoff, tt_value, tt_move = self.tt_probe(tt_key, depth, alpha, beta) - if tt_cutoff and ply > 0: - return tt_value, [tt_move] if tt_move else [] - - best_score = -99999 - best_move = None - pv = [] - moves = self.order_moves(board, tt_move=tt_move, ply=ply) - for move in moves: - board.push(move) - try: - child_score, child_pv = self.search(board, -beta, -alpha, depth-1, ply+1) - except SearchAbort: - board.pop() - raise - child_score = -child_score - board.pop() - - if child_score > best_score: - best_score = child_score - best_move = move - pv = [move] + child_pv - - if best_score > alpha: - alpha = best_score - - if alpha >= beta: - if not board.is_capture(move): - self.record_killer(ply, move) - self.record_history(board, move, depth) - break - - if best_score <= alpha_orig: - flag = TT_UPPER - elif best_score >= beta: - flag = TT_LOWER - else: - flag = TT_EXACT - self.tt_store(tt_key, depth, best_score, flag, best_move) - - return best_score, pv - -class QuiescenceSearchMixin(BaseSearch): - """Fail-soft quiescence search. - - - Depth-bounded: capture chains are cut off after ``Q_MAX_DEPTH`` plies. - - Check-aware: while in check every legal evasion is searched and there is - no stand-pat cut-off, so the side to move can never "pass" out of check. - - Non-check nodes search captures and promotions only, MVV-LVA ordered, - with stand-pat and delta pruning. - """ - - def evaluate_leaf_node(self, board, alpha, beta, depth): - return self.quiesce(board, alpha, beta, 0) - - def quiesce(self, board, alpha, beta, qply): - self._nodes += 1 - if not (self._nodes & 4095) and self.stop_signal(): - raise SearchAbort - - if board.is_checkmate(): - return qply - MATE_VALUE - if self.is_drawn(board) or board.is_repetition(3): - return 0 - - in_check = board.is_check() - - if in_check: - best = -99999 - if qply >= Q_MAX_DEPTH: - return self.evaluate(board) - moves = list(board.legal_moves) - else: - best = self.evaluate(board) - if best >= beta or qply >= Q_MAX_DEPTH: - return best - if best > alpha: - alpha = best - if best < alpha - Q_DELTA_MARGIN: # delta pruning - return best - moves = [m for m in board.legal_moves - if board.is_capture(m) or m.promotion] - moves.sort(key=lambda m: self.mvvlva(board, m), reverse=True) - - for move in moves: - board.push(move) - try: - score = -self.quiesce(board, -beta, -alpha, qply + 1) - except SearchAbort: - board.pop() - raise - board.pop() - - if score > best: - best = score - if best > alpha: - alpha = best - if alpha >= beta: - break - - return best diff --git a/src/pychess/__init__.py b/src/pychess/__init__.py new file mode 100644 index 0000000..18b5089 --- /dev/null +++ b/src/pychess/__init__.py @@ -0,0 +1,3 @@ +"""pychess - a UCI chess engine (Lazy SMP negamax + PeSTO evaluation).""" + +__version__ = "0.1.0" diff --git a/src/pychess/__main__.py b/src/pychess/__main__.py new file mode 100644 index 0000000..6a26cf9 --- /dev/null +++ b/src/pychess/__main__.py @@ -0,0 +1,180 @@ +import contextlib +import multiprocessing +import os +import signal +import sys +from pathlib import Path +from typing import cast + +import chess +from chess import polyglot + +from . import __version__ +from .engine import Engine, SupportsSearch +from .eval_board import EvalBoard +from .lazy_smp import SearchResult +from .perft import perft +from .types import GoLimits + +# UCI "go" parameters that take a single integer argument. +GO_INT_PARAMS = {"depth", "nodes", "movetime", "wtime", "btime", "winc", "binc", "movestogo"} + +# Polyglot opening book. Defaults to the copy in the source checkout; override +# with PYCHESS_BOOK when the package is installed elsewhere. A missing book is +# not an error - the engine just searches from move one. +BOOK_PATH = os.environ.get( + "PYCHESS_BOOK", + str(Path(__file__).resolve().parents[2] / "opening_book" / "bookfish.bin"), +) + + +class UCI: + def __init__(self) -> None: + self.board = EvalBoard() + self.engine: SupportsSearch = Engine() + self.depth = 4 + + def process_command(self, line: str) -> None: + args = line.split(" ") + match args[0]: + case "uci": + print(f"id name pychess {__version__}") + print("id author cjunius") + print("uciok") + case "debug": + pass + case "isready": + print("readyok") + case "setoption": + pass + case "register": + pass + case "ucinewgame": + self.board = EvalBoard() + self.engine = Engine() + case "position": + self.position_handler(args) + case "go": + self.go_handler(args) + case "stop": + pass + case "quit": + sys.exit(0) + case "ponderhit": + pass + case "printBoard": + print(str(self.board)) + case "printLegalMoves": + print(str([self.board.san(m) for m in self.board.legal_moves])) + case "printMoveStack": + replay = self.board.root() + print(str([replay.san_and_push(m) for m in self.board.move_stack])) + case "perft": + self.perft_handler(args) + case "selfPlay": + self.self_play_handler(args) + case _: + print("Unknown command") + + def position_handler(self, args: list[str]) -> None: + if len(args) > 1 and args[1] == "fen": + try: + moves_idx = args.index("moves") + fen_string = " ".join(args[2:moves_idx]) + except ValueError: + fen_string = " ".join(args[2:]) + self.board = EvalBoard(fen_string) + else: + self.board = EvalBoard() + + moves_found = False + for arg in args[1:]: + if moves_found: + self.board.push_uci(arg) + elif arg == "moves": + moves_found = True + + def parse_go(self, args: list[str]) -> GoLimits: + limits: dict[str, int | bool] = {} + i = 1 + while i < len(args): + token = args[i] + if token in GO_INT_PARAMS and i + 1 < len(args): + with contextlib.suppress(ValueError): + limits[token] = int(args[i + 1]) + i += 2 + elif token == "infinite": + limits["infinite"] = True + i += 1 + else: + i += 1 + return cast(GoLimits, limits) + + def book_move(self) -> chess.Move | None: + """Return a Polyglot book move for the current position, or None.""" + try: + with polyglot.MemoryMappedReader(BOOK_PATH) as reader: + return reader.weighted_choice(self.board).move + except (IndexError, FileNotFoundError, OSError): + return None + + def print_info(self, result: SearchResult) -> None: + """Format one UCI ``info`` line from a SearchResult.""" + pv = " ".join(m.uci() for m in result.pv) + print( + f"info depth {result.depth} score cp {result.score} " + f"nodes {result.nodes} time {round(result.elapsed, 3)} pv {pv}" + ) + + def perft_handler(self, args: list[str]) -> None: + depth = int(args[1]) if len(args) > 1 else 4 + nodes, elapsed = perft(self.board, depth) + print(f"info depth {depth} nodes {nodes} time {elapsed}") + + def go_handler(self, args: list[str]) -> None: + print("info starting search") + + move = self.book_move() + if move is not None: + print("info using book move") + print("bestmove " + move.uci()) + return + + result = self.engine.search(self.board, self.parse_go(args)) + self.print_info(result) + print("bestmove " + (result.pv[0].uci() if result.pv else "0000")) + + def self_play_handler(self, args: list[str]) -> None: + while not self.board.is_game_over(): + move = self.book_move() + if move is not None: + print("info using book move") + print("bestmove " + move.uci()) + self.board.push(move) + continue + + result = self.engine.search(self.board, {"depth": self.depth}) + if not result.pv: + break + self.print_info(result) + print("bestmove " + result.pv[0].uci()) + self.board.push(result.pv[0]) + + print(str(self.board.result())) + + +def main() -> None: + """Run the UCI protocol loop on stdin/stdout.""" + signal.signal(signal.SIGINT, lambda *_: sys.exit(0)) + uci = UCI() + while True: + command = input() + if command == "quit": + break + uci.process_command(command) + + +if __name__ == "__main__": + # Harmless normally; needed only if the app is ever frozen (PyInstaller etc). + multiprocessing.freeze_support() + main() diff --git a/src/pychess/clock.py b/src/pychess/clock.py new file mode 100644 index 0000000..0617254 --- /dev/null +++ b/src/pychess/clock.py @@ -0,0 +1,70 @@ +"""UCI time management and the search-abort predicate. + +``deadline_from_limits`` turns the raw ``go`` limits into a wall-clock deadline; +``Clock`` is polled by the search (every few thousand nodes) and, once armed, +tells it to bail out via ``SearchAbortError``. +""" + +import time + +import chess + +from .shared_tt import SharedFlag +from .types import GoLimits + +MAX_DEPTH = 64 +DEFAULT_MOVETIME = 4.0 # seconds, used for a bare "go" + + +def deadline_from_limits(board: chess.Board, limits: GoLimits, start: float) -> float | None: + """Return the ``time.time()`` value the search must finish by, or ``None`` + when only ``depth`` / ``nodes`` bound it.""" + if limits.get("movetime") is not None: + return start + limits["movetime"] / 1000.0 + + my = limits.get("wtime") if board.turn == chess.WHITE else limits.get("btime") + if my is not None: + inc = (limits.get("winc") if board.turn == chess.WHITE else limits.get("binc")) or 0 + movestogo = limits.get("movestogo") or 30 + budget = my / (movestogo + 1) + 0.75 * inc + budget = min(budget, 0.4 * my) + return start + max(budget, 10) / 1000.0 + + if limits.get("infinite"): + return start + 60.0 + if limits.get("depth") is None and limits.get("nodes") is None: + return start + DEFAULT_MOVETIME + return None + + +class Clock: + """Stop predicate for one search. + + ``should_stop`` returns ``False`` until ``arm()`` is called, so the first + full iteration always completes and the search never returns without a + move. Lazy SMP workers share one ``stop_flag`` so a forced mate found by + any worker stops the rest. + """ + + def __init__( + self, + deadline: float | None = None, + node_limit: int | None = None, + stop_flag: SharedFlag | None = None, + ) -> None: + self.deadline = deadline + self.node_limit = node_limit + self.stop_flag = stop_flag + self._armed = False + + def arm(self) -> None: + self._armed = True + + def should_stop(self, nodes: int) -> bool: + if not self._armed: + return False + if self.stop_flag is not None and self.stop_flag.is_set(): + return True + if self.node_limit is not None and nodes >= self.node_limit: + return True + return self.deadline is not None and time.time() >= self.deadline diff --git a/src/pychess/constants.py b/src/pychess/constants.py new file mode 100644 index 0000000..6a6bac2 --- /dev/null +++ b/src/pychess/constants.py @@ -0,0 +1,20 @@ +"""Score conventions and transposition-table flags shared across the search. + +Mate is scored by *remaining depth* (``-MATE - depth``), not distance-to-root, +so mate scores are not safe to reuse as bounds across different depths: the +transposition table keeps the stored move for ordering but never returns a +value with ``abs(score) >= MATE_GUARD`` as a cut-off. + +``INF`` is the alpha-beta window sentinel; every real evaluation sits well +inside ``+/- MATE``. +""" + +INF = 99999 # alpha-beta window sentinel +MATE = 9999 # abs(score) at or above this is mate-related +MATE_IN_MAX = 9899 # MATE - 100: mate within ~100 plies (worker win/loss flag) +MATE_GUARD = 9000 # the TT never returns abs(score) >= this as a bound + +# Transposition-table entry bounds. +TT_EXACT = 0 +TT_LOWER = 1 # value is a lower bound (fail-high / beta cut-off) +TT_UPPER = 2 # value is an upper bound (fail-low / all moves searched) diff --git a/src/pychess/engine.py b/src/pychess/engine.py new file mode 100644 index 0000000..d4bbeda --- /dev/null +++ b/src/pychess/engine.py @@ -0,0 +1,33 @@ +import random +from typing import Protocol + +import chess + +from . import lazy_smp +from .lazy_smp import SearchResult +from .types import GoLimits + + +class SupportsSearch(Protocol): + """The interface the UCI layer needs from an engine.""" + + def search(self, board: chess.Board, limits: GoLimits | None = None) -> SearchResult: ... + + +class Engine: + """The default engine: Lazy SMP over a fail-soft negamax / PeSTO search. + + Stateless today - each ``search`` spins up its own shared transposition + table. Rebuilt on ``ucinewgame`` so any future per-game state is dropped. + """ + + def search(self, board: chess.Board, limits: GoLimits | None = None) -> SearchResult: + return lazy_smp.search(board, limits or {}) + + +class RandomEngine: + """Plays a uniformly random legal move. A baseline for testing.""" + + def search(self, board: chess.Board, limits: GoLimits | None = None) -> SearchResult: + move = random.choice(list(board.legal_moves)) + return SearchResult(score=0, pv=[move], depth=0, nodes=1, elapsed=0.0) diff --git a/eval_board.py b/src/pychess/eval_board.py similarity index 76% rename from eval_board.py rename to src/pychess/eval_board.py index b39d1f3..2b919f4 100644 --- a/eval_board.py +++ b/src/pychess/eval_board.py @@ -1,6 +1,6 @@ import chess -from evaluation import MG_VALUE, EG_VALUE, MG_PST, EG_PST, PHASE_INC +from .evaluation import EG_PST, EG_VALUE, MG_PST, MG_VALUE, PHASE_INC class EvalBoard(chess.Board): @@ -12,14 +12,14 @@ class EvalBoard(chess.Board): rarer promotion / castling / en-passant / null moves. """ - def __init__(self, fen=chess.STARTING_FEN, *, chess960=False): + def __init__(self, fen: str | None = chess.STARTING_FEN, *, chess960: bool = False) -> None: super().__init__(fen, chess960=chess960) - self._eval_stack = [] + self._eval_stack: list[tuple[int, int, int]] = [] self._recompute_eval() # -- accumulator --------------------------------------------------------- - def _recompute_eval(self): + def _recompute_eval(self) -> None: mg = eg = phase = 0 for square, piece in self.piece_map().items(): i = piece.piece_type - 1 @@ -30,7 +30,9 @@ def _recompute_eval(self): phase += PHASE_INC[i] self._mg, self._eg, self._phase = mg, eg, phase - def _acc(self, piece_type, color, square, sign): + def _acc( + self, piece_type: chess.PieceType, color: chess.Color, square: chess.Square, sign: int + ) -> None: i = piece_type - 1 s = square if color else square ^ 56 csign = sign if color else -sign @@ -40,12 +42,17 @@ def _acc(self, piece_type, color, square, sign): # -- move making ------------------------------------------------------- - def push(self, move): + def push(self, move: chess.Move) -> None: self._eval_stack.append((self._mg, self._eg, self._phase)) mover = self.piece_at(move.from_square) - if (not move or mover is None or move.promotion - or self.is_castling(move) or self.is_en_passant(move)): + if ( + not move + or mover is None + or move.promotion + or self.is_castling(move) + or self.is_en_passant(move) + ): super().push(move) self._recompute_eval() return @@ -57,14 +64,14 @@ def push(self, move): self._acc(mover.piece_type, mover.color, move.to_square, +1) super().push(move) - def pop(self): + def pop(self) -> chess.Move: move = super().pop() self._mg, self._eg, self._phase = self._eval_stack.pop() return move # -- copying ---------------------------------------------------------- - def copy(self, *, stack=True): + def copy(self, *, stack: bool | int = True) -> "EvalBoard": board = super().copy(stack=stack) board._mg, board._eg, board._phase = self._mg, self._eg, self._phase board._eval_stack = list(self._eval_stack) if stack else [] diff --git a/evaluation.py b/src/pychess/evaluation.py similarity index 52% rename from evaluation.py rename to src/pychess/evaluation.py index e279433..bea168f 100644 --- a/evaluation.py +++ b/src/pychess/evaluation.py @@ -1,70 +1,12 @@ +from typing import TYPE_CHECKING, cast + import chess -PIECE_VALUES = [None, 100, 320, 330, 500, 900, 0] +if TYPE_CHECKING: + from .eval_board import EvalBoard -PIECE_SQUARE_TABLES = [ - None, - [ # Pawn - 0, 0, 0, 0, 0, 0, 0, 0, - 5, 10, 10, -20, -20, 10, 10, 5, - 5, -5, -10, 0, 0, -10, -5, 5, - 0, 0, 0, 20, 20, 0, 0, 0, - 5, 5, 10, 25, 25, 10, 5, 5, - 10, 10, 20, 30, 30, 20, 10, 10, - 50, 50, 50, 50, 50, 50, 50, 50, - 0, 0, 0, 0, 0, 0, 0, 0 - ], - [ # Knight - -50, -40, -30, -30, -30, -30, -40, -50, - -40, -20, 0, 0, 0, 0, -20, -40, - -30, 5, 10, 15, 15, 10, 5, -30, - -30, 0, 15, 20, 20, 15, 0, -30, - -30, 0, 10, 15, 15, 10, 0, -30, - -30, 5, 15, 20, 20, 15, 5, -30, - -40, -20, 0, 5, 5, 0, -20, -40, - -50, -40, -30, -30, -30, -30, -40, -50 - ], - [ # Bishop - -20, -10, -10, -10, -10, -10, -10, -20, - -10, 5, 0, 0, 0, 0, 5, -10, - -10, 10, 10, 10, 10, 10, 10, -10, - -10, 0, 10, 10, 10, 10, 0, -10, - -10, 5, 5, 10, 10, 5, 5, -10, - -10, 0, 5, 10, 10, 5, 0, -10, - -10, 0, 0, 0, 0, 0, 0, -10, - -20, -10, -10, -10, -10, -10, -10, -20 - ], - [ # Rook - 0, 0, 0, 5, 5, 0, 0, 0, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - -5, 0, 0, 0, 0, 0, 0, -5, - 5, 10, 10, 10, 10, 10, 10, 5, - 0, 0, 0, 0, 0, 0, 0, 0 - ], - [ # Queen - -20, -10, -10, -5, -5, -10, -10, -20, - -10, 0, 5, 0, 0, 0, 0, -10, - -10, 5, 5, 5, 5, 5, 0, -10, - 0, 0, 5, 5, 5, 5, 0, -5, - -5, 0, 5, 5, 5, 5, 0, -5, - -10, 0, 5, 5, 5, 5, 0, -10, - -10, 0, 0, 0, 0, 0, 0, -10, - -20, -10, -10, -5, -5, -10, -10, -20 - ], - [ # King mid-game - 20, 30, 10, 0, 0, 10, 30, 20, - 20, 20, 0, 0, 0, 0, 20, 20, - -10, -20, -20, -20, -20, -20, -20, -10, - -20, -30, -30, -40, -40, -30, -30, -20, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30, - -30, -40, -40, -50, -50, -40, -40, -30, - ] -] +# Indexed by ``chess`` piece type (PAWN=1 .. KING=6); slot 0 is an unused pad. +PIECE_VALUES = [0, 100, 320, 330, 500, 900, 0] # --------------------------------------------------------------------------- # PeSTO tapered evaluation (Piece-Square Tables Only, Ronald Friederich) @@ -76,6 +18,7 @@ # (a1 = 0) at import time. # --------------------------------------------------------------------------- +# fmt: off MG_VALUE = [82, 337, 365, 477, 1025, 0] # P N B R Q K EG_VALUE = [94, 281, 297, 512, 936, 0] PHASE_INC = [0, 1, 1, 2, 4, 0] # summed over all pieces, max 24 @@ -200,20 +143,23 @@ -27, -11, 4, 13, 14, 4, -5, -17, -53, -34, -21, -11, -28, -14, -24, -43, ] +# fmt: on -def _to_a1_first(table): +def _to_a1_first(table: list[int]) -> list[int]: """Flip a rank-8-first table to python-chess square order (a1 = 0).""" return [table[(7 - (i // 8)) * 8 + (i % 8)] for i in range(64)] -MG_PST = [_to_a1_first(t) for t in - (_MG_PAWN, _MG_KNIGHT, _MG_BISHOP, _MG_ROOK, _MG_QUEEN, _MG_KING)] -EG_PST = [_to_a1_first(t) for t in - (_EG_PAWN, _EG_KNIGHT, _EG_BISHOP, _EG_ROOK, _EG_QUEEN, _EG_KING)] +MG_PST = [ + _to_a1_first(t) for t in (_MG_PAWN, _MG_KNIGHT, _MG_BISHOP, _MG_ROOK, _MG_QUEEN, _MG_KING) +] +EG_PST = [ + _to_a1_first(t) for t in (_EG_PAWN, _EG_KNIGHT, _EG_BISHOP, _EG_ROOK, _EG_QUEEN, _EG_KING) +] -def pesto_terms(board): +def pesto_terms(board: chess.Board) -> tuple[int, int, int]: """Return ``(mg, eg, phase)`` from White's point of view, computed from scratch over the current position.""" mg = eg = phase = 0 @@ -227,97 +173,24 @@ def pesto_terms(board): return mg, eg, phase -def taper(mg, eg, phase): +def taper(mg: int, eg: int, phase: int) -> int: """Interpolate between mid- and end-game scores (White's point of view).""" mg_phase = phase if phase < 24 else 24 return (mg * mg_phase + eg * (24 - mg_phase)) // 24 -class PeSTOEvaluationMixin(object): - """Tapered PeSTO evaluation returned from the side-to-move's perspective. +class PestoEvaluator: + """Tapered PeSTO evaluation, returned from the side-to-move's perspective. Uses the incrementally-maintained accumulator on ``EvalBoard`` when the board provides one, otherwise falls back to a full recompute. """ - def evaluate(self, board) -> int: - mg = getattr(board, "_mg", None) - if mg is None: + def evaluate(self, board: chess.Board) -> int: + if getattr(board, "_mg", None) is None: mg, eg, phase = pesto_terms(board) else: - eg, phase = board._eg, board._phase + acc = cast("EvalBoard", board) + mg, eg, phase = acc._mg, acc._eg, acc._phase score = taper(mg, eg, phase) return score if board.turn else -score - - -class BaseEvaluation(object): - def __init__(self): - pass - - def evaluate(self, board) -> int: - return 0 - - -class PieceValueMixin(BaseEvaluation): - def evaluate(self, board) -> int: - score: int = super(PieceValueMixin, self).evaluate(board) - for piece in chess.PIECE_TYPES: - pieces_mask_turn = board.pieces_mask(piece, board.turn) - score += chess.popcount(pieces_mask_turn) * PIECE_VALUES[piece] - - pieces_mask_not_turn = board.pieces_mask(piece, board.turn ^ 1) - score -= chess.popcount(pieces_mask_not_turn) * PIECE_VALUES[piece] - - return score - - -class PieceSquareTableMixin(BaseEvaluation): - def evaluate(self, board) -> int: - parent_score: int = super(PieceSquareTableMixin, self).evaluate(board) - score = 0 - for piece in chess.PIECE_TYPES: - for square in board.pieces(piece, chess.WHITE): - score += PIECE_SQUARE_TABLES[piece][square] - for square in board.pieces(piece, chess.BLACK): - score -= PIECE_SQUARE_TABLES[piece][square ^ 56] - if not board.turn: #Black to Move - score = -score - return parent_score + score - - -class PieceValueSquareTableMixin(BaseEvaluation): - def evaluate(self, board) -> int: - parent_score: int = super(PieceValueSquareTableMixin, self).evaluate(board) - score = 0 - for piece in chess.PIECE_TYPES: - for square in board.pieces(piece, chess.WHITE): - score += PIECE_SQUARE_TABLES[piece][square] + PIECE_VALUES[piece] - for square in board.pieces(piece, chess.BLACK): - score -= PIECE_SQUARE_TABLES[piece][square ^ 56] + PIECE_VALUES[piece] - if board.turn ^ 1: #Black to Move - score = -score - return score + parent_score - -class MobilityMixin(BaseEvaluation): - def evaluate(self, board) -> int: - parent_score: int = super(MobilityMixin, self).evaluate(board) - if len(list(board.move_stack)) == 0: - return 0 - - last_move = board.pop() - countA = len(list(board.legal_moves)) - board.push(last_move) - countB = len(list(board.legal_moves)) - return countA - countB + parent_score - - -class BoardControlEvaluationMixin(BaseEvaluation): - def evaluate(self, board) -> int: - eval: int = super(BoardControlEvaluationMixin, self).evaluate(board) - for square in chess.SquareSet(board.occupied_co[board.turn]): - eval += len(board.attacks(square)) - - for square in chess.SquareSet(board.occupied_co[board.turn ^ 1]): - eval -= len(board.attacks(square)) - - return eval \ No newline at end of file diff --git a/src/pychess/lazy_smp.py b/src/pychess/lazy_smp.py new file mode 100644 index 0000000..2b4da4d --- /dev/null +++ b/src/pychess/lazy_smp.py @@ -0,0 +1,162 @@ +"""`Lazy SMP `_. + +``N`` worker processes each run their own iterative deepening on the root +position while sharing one lock-free transposition table in shared memory. +Divergent start depths plus TT contention make the workers explore different +subtrees; the deepest completed result wins. +""" + +import multiprocessing +import time +from dataclasses import dataclass +from multiprocessing.pool import Pool +from typing import NamedTuple + +import chess + +from .clock import DEFAULT_MOVETIME, MAX_DEPTH, Clock, deadline_from_limits +from .constants import INF, MATE_IN_MAX +from .eval_board import EvalBoard +from .evaluation import PestoEvaluator +from .move_ordering import MoveOrderer +from .negamax import Negamax, SearchAbortError +from .shared_tt import SharedFlag, SharedTT +from .types import GoLimits + +SMP_TT_SLOTS = 1 << 20 # 1M entries * 16 bytes = 16 MB + +# The pickled payload each worker process receives. +_Payload = tuple[str, list[str], list[str] | None, int, float, str, int, int, str] + + +class _WorkerResult(NamedTuple): + """What a worker hands back: raw score, PV as uci strings, depth, nodes.""" + + score: int + pv: list[str] + depth: int + nodes: int + + +@dataclass +class SearchResult: + score: int + pv: list[chess.Move] + depth: int + nodes: int + elapsed: float # seconds + + +def _worker(payload: _Payload) -> _WorkerResult: + """One Lazy SMP helper: iterative deepening against the shared TT. + + Runs in its own process. Workers are seeded with different start depths so + they populate the shared table along slightly different paths; the shared + entries then speed up every other worker. + """ + (root_fen, moves, root_slice, max_depth, deadline, tt_name, tt_slots, worker_id, stop_name) = ( + payload + ) + + tt = SharedTT(slots=tt_slots, name=tt_name, create=False) + stop = SharedFlag(name=stop_name, create=False) + + board = EvalBoard(root_fen) + for uci in moves: + board.push_uci(uci) + + root_moves = None + if root_slice is not None: + root_moves = {chess.Move.from_uci(u) for u in root_slice} + + clock = Clock(deadline=deadline, stop_flag=stop) + searcher = Negamax(PestoEvaluator(), MoveOrderer(root_moves=root_moves), tt, clock) + + best = _WorkerResult(0, [], 0, 0) + try: + for depth in range(1 + (worker_id % 3), max_depth + 1): + try: + score, pv = searcher.search(board, -INF, INF, depth) + except SearchAbortError: + break + clock.arm() + best = _WorkerResult(score, [m.uci() for m in pv], depth, searcher.nodes) + if stop.is_set() or time.time() >= deadline: + break + if score >= MATE_IN_MAX: # forced win found - everyone stops + stop.set() + break + if score <= -MATE_IN_MAX: # every move in this slice loses + break + finally: + tt.close() + stop.close() + return best + + +def _result_rank(r: _WorkerResult) -> tuple[int, int, int]: + """Rank worker results: a forced win beats everything (fastest first), then + deepest search, then best score; a forced loss ranks last (least bad, + deepest).""" + if r.score >= MATE_IN_MAX: + return (2, r.score, r.depth) + if r.score <= -MATE_IN_MAX: + return (0, r.depth, r.score) + return (1, r.depth, r.score) + + +def search( + board: chess.Board, limits: GoLimits | None = None, *, tt_slots: int = SMP_TT_SLOTS +) -> SearchResult: + """Search ``board`` under UCI ``limits`` and return a ``SearchResult``.""" + limits = limits or {} + start = time.time() + + n_workers = max(1, multiprocessing.cpu_count() - 1) + deadline = deadline_from_limits(board, limits, start) or (start + DEFAULT_MOVETIME) + max_depth = min(int(limits.get("depth") or MAX_DEPTH), MAX_DEPTH) + + root_fen = board.root().fen() + moves = [m.uci() for m in board.move_stack] + + # Worker 0 searches every root move (authoritative PV); the rest split the + # root moves so the expensive top-level subtrees are divided while still + # sharing everything below the root through the TT. + legal = [m.uci() for m in board.legal_moves] + splitters = max(1, n_workers - 1) + slices: list[list[str] | None] = [None] + for i in range(1, n_workers): + slices.append(legal[(i - 1) % splitters :: splitters] or None) + + tt = SharedTT(slots=tt_slots, create=True) + stop = SharedFlag(create=True) + payloads: list[_Payload] = [ + (root_fen, moves, slices[i], max_depth, deadline, tt.name, tt.slots, i, stop.name) + for i in range(n_workers) + ] + try: + with Pool(n_workers) as pool: + async_res = pool.map_async(_worker, payloads) + while not async_res.ready() and time.time() < deadline: + time.sleep(0.02) + stop.set() + results = async_res.get() + finally: + stop.close() + stop.unlink() + tt.close() + tt.unlink() + + elapsed = time.time() - start + total_nodes = sum(r.nodes for r in results if r) + + usable = [r for r in results if r and r.pv] + if not usable: + # Every worker crashed or died before completing a single ply; fall + # back to any legal move so the engine still replies. + legal_moves = list(board.legal_moves) + return SearchResult(0, legal_moves[:1], 0, total_nodes, elapsed) + + best = max(usable, key=_result_rank) + pv = [chess.Move.from_uci(u) for u in best.pv] + return SearchResult(int(best.score), pv, best.depth, total_nodes, elapsed) diff --git a/move_ordering.py b/src/pychess/move_ordering.py similarity index 63% rename from move_ordering.py rename to src/pychess/move_ordering.py index a4e0099..e6929a8 100644 --- a/move_ordering.py +++ b/src/pychess/move_ordering.py @@ -1,10 +1,9 @@ import chess -from chess import Move -from evaluation import PIECE_VALUES +from .evaluation import PIECE_VALUES -class MoveOrderingMixin(object): +class MoveOrderer: """Orders moves to maximise alpha-beta cut-offs. Priority (high to low): @@ -14,39 +13,26 @@ class MoveOrderingMixin(object): 4. Killer moves for this ply 5. Quiet moves, sorted by the history heuristic - Killer and history state is kept per engine instance and is reset by - building a fresh engine on ``ucinewgame``. + Killer and history tables are per-instance; a fresh ``MoveOrderer`` (built + per search, or per Lazy SMP worker) starts empty. """ - # ---- lazily-created per-instance state ------------------------------- - - @property - def killers(self): - try: - return self._killers - except AttributeError: - self._killers = {} - return self._killers - - @property - def history(self): - try: - return self._history - except AttributeError: - self._history = {} - return self._history + def __init__(self, root_moves: set[chess.Move] | None = None) -> None: + self.killers: dict[int, list[chess.Move]] = {} + self.history: dict[tuple[chess.Color, chess.Square, chess.Square], int] = {} + # Restricts the moves considered at the root; Lazy SMP workers each own + # a slice of the root moves. ``None`` means "all". + self.root_moves = root_moves # ---- ordering ------------------------------------------------------- - # Restricts the moves considered at the root; set by Lazy SMP workers so - # each process owns a slice of the root moves. ``None`` means "all". - _root_moves = None - - def order_moves(self, board, tt_move=None, ply=0): + def order_moves( + self, board: chess.Board, tt_move: chess.Move | None = None, ply: int = 0 + ) -> list[chess.Move]: killers = self.killers.get(ply, ()) history = self.history color = board.turn - root_moves = self._root_moves if ply == 0 else None + root_moves = self.root_moves if ply == 0 else None scored = [] for move in board.legal_moves: @@ -67,7 +53,7 @@ def order_moves(self, board, tt_move=None, ply=0): scored.sort(key=lambda item: item[0], reverse=True) return [move for _, move in scored] - def mvvlva(self, board, move: Move) -> int: + def mvvlva(self, board: chess.Board, move: chess.Move) -> int: """Most Valuable Victim / Least Valuable Attacker score.""" if board.is_en_passant(move): return PIECE_VALUES[chess.PAWN] * 10 - PIECE_VALUES[chess.PAWN] // 100 @@ -76,21 +62,18 @@ def mvvlva(self, board, move: Move) -> int: if victim is None: return 0 attacker = board.piece_type_at(move.from_square) + assert attacker is not None # the mover always sits on from_square return PIECE_VALUES[victim] * 10 - PIECE_VALUES[attacker] // 100 # ---- cut-off bookkeeping ------------------------------------------ - def record_killer(self, ply, move): + def record_killer(self, ply: int, move: chess.Move) -> None: slot = self.killers.setdefault(ply, []) if move in slot: return slot.insert(0, move) del slot[2:] - def record_history(self, board, move, depth): + def record_history(self, board: chess.Board, move: chess.Move, depth: int) -> None: key = (board.turn, move.from_square, move.to_square) self.history[key] = self.history.get(key, 0) + depth * depth - - -# Backwards-compatible alias for the old name referenced elsewhere. -ChecksCapturesOrderMixin = MoveOrderingMixin diff --git a/src/pychess/negamax.py b/src/pychess/negamax.py new file mode 100644 index 0000000..982bb66 --- /dev/null +++ b/src/pychess/negamax.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import chess + +from .constants import INF, MATE, TT_EXACT, TT_LOWER, TT_UPPER + +if TYPE_CHECKING: + from .clock import Clock + from .evaluation import PestoEvaluator + from .move_ordering import MoveOrderer + from .shared_tt import SharedTT + from .transposition import TranspositionTable + +# Upper bound on quiescence extension (plies past the normal horizon). +Q_MAX_DEPTH = 8 +# Delta-pruning margin: a bit more than a queen. +Q_DELTA_MARGIN = 1100 + + +class SearchAbortError(Exception): + """Raised inside the search when the clock says stop; the caller discards + the partial iteration and keeps the previous one.""" + + +def is_drawn(board: chess.Board) -> bool: + return ( + board.is_fivefold_repetition() + or board.is_stalemate() + or board.is_seventyfive_moves() + or board.is_insufficient_material() + ) + + +class Negamax: + """Fail-soft negamax with a quiescence leaf, over injected collaborators. + + ``evaluator`` - ``.evaluate(board) -> int`` from the side-to-move's view + ``orderer`` - ``.order_moves`` / ``.mvvlva`` / ``.record_killer`` / ``.record_history`` + ``tt`` - ``.key`` / ``.probe`` / ``.store`` (in-process or shared) + ``clock`` - ``.should_stop(nodes) -> bool`` + + ``search`` and ``quiesce`` share ``self.nodes``; the clock is polled every + 4096 nodes and raises ``SearchAbortError`` once armed. + """ + + def __init__( + self, + evaluator: PestoEvaluator, + orderer: MoveOrderer, + tt: TranspositionTable | SharedTT, + clock: Clock, + ) -> None: + self.evaluator = evaluator + self.orderer = orderer + self.tt = tt + self.clock = clock + self.nodes = 0 + + def search( + self, board: chess.Board, alpha: int, beta: int, depth: int, ply: int = 0 + ) -> tuple[int, list[chess.Move]]: + self.nodes += 1 + if ply and not (self.nodes & 4095) and self.clock.should_stop(self.nodes): + raise SearchAbortError + + if depth <= 0 or board.is_game_over(): + if board.is_checkmate(): + return -MATE - depth, [] + if is_drawn(board): + return -depth, [] + return self.quiesce(board, alpha, beta, 0), [] + + alpha_orig = alpha + + key = self.tt.key(board) + tt_cutoff, tt_value, tt_move = self.tt.probe(key, depth, alpha, beta) + if tt_cutoff and ply > 0: + return tt_value, [tt_move] if tt_move else [] + + best_score = -INF + best_move = None + pv = [] + for move in self.orderer.order_moves(board, tt_move=tt_move, ply=ply): + board.push(move) + try: + child_score, child_pv = self.search(board, -beta, -alpha, depth - 1, ply + 1) + except SearchAbortError: + board.pop() + raise + child_score = -child_score + board.pop() + + if child_score > best_score: + best_score = child_score + best_move = move + pv = [move, *child_pv] + + if best_score > alpha: + alpha = best_score + + if alpha >= beta: + if not board.is_capture(move): + self.orderer.record_killer(ply, move) + self.orderer.record_history(board, move, depth) + break + + if best_score <= alpha_orig: + flag = TT_UPPER + elif best_score >= beta: + flag = TT_LOWER + else: + flag = TT_EXACT + self.tt.store(key, depth, best_score, flag, best_move) + + return best_score, pv + + def quiesce(self, board: chess.Board, alpha: int, beta: int, qply: int) -> int: + """Fail-soft quiescence search. + + - Depth-bounded: capture chains are cut off after ``Q_MAX_DEPTH`` plies. + - Check-aware: while in check every legal evasion is searched and there + is no stand-pat cut-off, so the side to move can never "pass" out of + check. + - Non-check nodes search captures and promotions only, MVV-LVA ordered, + with stand-pat and delta pruning. + """ + self.nodes += 1 + if not (self.nodes & 4095) and self.clock.should_stop(self.nodes): + raise SearchAbortError + + if board.is_checkmate(): + return qply - MATE + if is_drawn(board) or board.is_repetition(3): + return 0 + + if board.is_check(): + best = -INF + if qply >= Q_MAX_DEPTH: + return self.evaluator.evaluate(board) + moves = list(board.legal_moves) + else: + best = self.evaluator.evaluate(board) + if best >= beta or qply >= Q_MAX_DEPTH: + return best + if best > alpha: + alpha = best + if best < alpha - Q_DELTA_MARGIN: # delta pruning + return best + moves = [m for m in board.legal_moves if board.is_capture(m) or m.promotion] + moves.sort(key=lambda m: self.orderer.mvvlva(board, m), reverse=True) + + for move in moves: + board.push(move) + try: + score = -self.quiesce(board, -beta, -alpha, qply + 1) + except SearchAbortError: + board.pop() + raise + board.pop() + + if score > best: + best = score + if best > alpha: + alpha = best + if alpha >= beta: + break + + return best diff --git a/perft.py b/src/pychess/perft.py similarity index 75% rename from perft.py rename to src/pychess/perft.py index 79676df..aa63d9a 100644 --- a/perft.py +++ b/src/pychess/perft.py @@ -1,15 +1,16 @@ -import functools, multiprocessing, time +import functools +import multiprocessing +import time +from collections.abc import Iterator +from multiprocessing.pool import Pool from chess import Board -from multiprocessing.pool import Pool -from typing import Iterator, Tuple -def perft(board: Board, depth: int) -> Tuple[int, float]: +def perft(board: Board, depth: int) -> tuple[int, float]: start = time.time() nodes = count_nodes(depth, board) - end = time.time() - return nodes, end - start + return nodes, time.time() - start def count_nodes(depth: int, board: Board) -> int: @@ -40,7 +41,7 @@ def successors(board: Board) -> Iterator[Board]: return sum(pool.imap_unordered(perft_f, successors(board))) -def main(): +def main() -> None: # pragma: no cover - depth-6 benchmark, run manually depth = 6 cpu_count = multiprocessing.cpu_count() board = Board() @@ -48,13 +49,11 @@ def main(): start = time.time() with Pool(cpu_count) as pool: nodes = parallel_perft(pool, depth=depth, board=board) - end = time.time() - print("info CPUs {} nodes {} time {}".format(cpu_count, nodes, end - start)) + print(f"info CPUs {cpu_count} nodes {nodes} time {time.time() - start}") start = time.time() nodes = count_nodes(depth, board) - end = time.time() - print("info CPUs 1 nodes {} time {}".format(nodes, end - start)) + print(f"info CPUs 1 nodes {nodes} time {time.time() - start}") if __name__ == "__main__": diff --git a/archive/test/__init__.py b/src/pychess/py.typed similarity index 100% rename from archive/test/__init__.py rename to src/pychess/py.typed diff --git a/shared_tt.py b/src/pychess/shared_tt.py similarity index 68% rename from shared_tt.py rename to src/pychess/shared_tt.py index 8b25a4d..abc7a9c 100644 --- a/shared_tt.py +++ b/src/pychess/shared_tt.py @@ -10,25 +10,28 @@ processes) fails that check and is treated as a miss, so no lock is needed (Hyatt's XOR trick). ``data`` packs the move, score, depth and bound flag. """ + +import contextlib import struct from multiprocessing import shared_memory import chess +from chess.polyglot import zobrist_hash -from transposition import TT_EXACT, TT_LOWER, TT_UPPER, MATE_GUARD +from .constants import MATE_GUARD, TT_EXACT, TT_LOWER, TT_UPPER ENTRY_SIZE = 16 _ENTRY = struct.Struct(" int: if move is None: return 0 return move.from_square | (move.to_square << 6) | ((move.promotion or 0) << 12) -def _unpack_move(value): +def _unpack_move(value: int) -> chess.Move | None: value &= 0xFFFF if value == 0: return None @@ -36,15 +39,17 @@ def _unpack_move(value): return chess.Move(value & 63, (value >> 6) & 63, promo or None) -def _pack_data(move, score, depth, flag): +def _pack_data(move: chess.Move | None, score: int, depth: int, flag: int) -> int: depth = 0 if depth < 0 else (255 if depth > 255 else int(depth)) - return ((_pack_move(move) & 0xFFFF) - | ((score & 0xFFFF) << 16) - | (depth << 32) - | ((flag & 0xFF) << 40)) + return ( + (_pack_move(move) & 0xFFFF) + | ((score & 0xFFFF) << 16) + | (depth << 32) + | ((flag & 0xFF) << 40) + ) -def _unpack_data(data): +def _unpack_data(data: int) -> tuple[chess.Move | None, int, int, int]: move = _unpack_move(data) raw = (data >> 16) & 0xFFFF score = raw - 0x10000 if raw >= 0x8000 else raw @@ -52,7 +57,7 @@ def _unpack_data(data): class SharedTT: - def __init__(self, slots=1 << 20, name=None, create=True): + def __init__(self, slots: int = 1 << 20, name: str | None = None, create: bool = True) -> None: assert slots & (slots - 1) == 0, "slots must be a power of two" self.slots = slots self.mask = slots - 1 @@ -62,7 +67,12 @@ def __init__(self, slots=1 << 20, name=None, create=True): self.shm = shared_memory.SharedMemory(name=name) self.name = self.shm.name - def probe(self, key, depth, alpha, beta): + def key(self, board: chess.Board) -> int: + return zobrist_hash(board) + + def probe( + self, key: int, depth: int, alpha: int, beta: int + ) -> tuple[bool, int, chess.Move | None]: off = (key & self.mask) * ENTRY_SIZE word0, data = _ENTRY.unpack_from(self.shm.buf, off) if data == 0 or (word0 ^ data) != key: @@ -77,7 +87,7 @@ def probe(self, key, depth, alpha, beta): return True, score, move return False, 0, move - def store(self, key, depth, score, flag, move): + def store(self, key: int, depth: int, score: int, flag: int, move: chess.Move | None) -> None: off = (key & self.mask) * ENTRY_SIZE word0, old = _ENTRY.unpack_from(self.shm.buf, off) if old and (word0 ^ old) == key and _unpack_data(old)[2] > depth: @@ -85,23 +95,19 @@ def store(self, key, depth, score, flag, move): data = _pack_data(move, score, depth, flag) _ENTRY.pack_into(self.shm.buf, off, (key ^ data) & _U64, data) - def close(self): - try: + def close(self) -> None: + with contextlib.suppress(Exception): self.shm.close() - except Exception: - pass - def unlink(self): - try: + def unlink(self) -> None: + with contextlib.suppress(Exception): self.shm.unlink() - except Exception: - pass class SharedFlag: """One shared byte used as a cross-process stop signal.""" - def __init__(self, name=None, create=True): + def __init__(self, name: str | None = None, create: bool = True) -> None: if create: self.shm = shared_memory.SharedMemory(create=True, size=1) self.shm.buf[0] = 0 @@ -109,20 +115,16 @@ def __init__(self, name=None, create=True): self.shm = shared_memory.SharedMemory(name=name) self.name = self.shm.name - def set(self): + def set(self) -> None: self.shm.buf[0] = 1 - def is_set(self): + def is_set(self) -> bool: return self.shm.buf[0] != 0 - def close(self): - try: + def close(self) -> None: + with contextlib.suppress(Exception): self.shm.close() - except Exception: - pass - def unlink(self): - try: + def unlink(self) -> None: + with contextlib.suppress(Exception): self.shm.unlink() - except Exception: - pass diff --git a/src/pychess/transposition.py b/src/pychess/transposition.py new file mode 100644 index 0000000..3b8cf6c --- /dev/null +++ b/src/pychess/transposition.py @@ -0,0 +1,55 @@ +import chess +from chess.polyglot import zobrist_hash + +from .constants import MATE_GUARD, TT_EXACT, TT_LOWER, TT_UPPER + +# (depth, value, flag, move) +_Entry = tuple[int, int, int, "chess.Move | None"] + + +class TranspositionTable: + """An always-replace-if-deeper table keyed by Zobrist hash. + + Entries are ``(depth, value, flag, move)`` tuples. This is the in-process + table used for single-threaded search and tests; Lazy SMP uses + ``shared_tt.SharedTT``, which exposes the same + ``key`` / ``probe`` / ``store`` interface over shared memory. + """ + + def __init__(self) -> None: + self._table: dict[int, _Entry] = {} + + def clear(self) -> None: + self._table.clear() + + def key(self, board: chess.Board) -> int: + return zobrist_hash(board) + + def probe( + self, key: int, depth: int, alpha: int, beta: int + ) -> tuple[bool, int, chess.Move | None]: + """Return ``(cutoff, value, move)``. + + ``cutoff`` is True when the stored value can be returned directly. + ``move`` is the stored best move (possibly None) and is always returned + for move ordering even when no cut-off is possible. + """ + entry = self._table.get(key) + if entry is None: + return False, 0, None + + e_depth, e_value, e_flag, e_move = entry + if e_depth >= depth and abs(e_value) < MATE_GUARD: + if e_flag == TT_EXACT: + return True, e_value, e_move + if e_flag == TT_LOWER and e_value >= beta: + return True, e_value, e_move + if e_flag == TT_UPPER and e_value <= alpha: + return True, e_value, e_move + return False, 0, e_move + + def store(self, key: int, depth: int, value: int, flag: int, move: chess.Move | None) -> None: + existing = self._table.get(key) + if existing is not None and existing[0] > depth: + return # keep the deeper analysis + self._table[key] = (depth, value, flag, move) diff --git a/src/pychess/types.py b/src/pychess/types.py new file mode 100644 index 0000000..5799146 --- /dev/null +++ b/src/pychess/types.py @@ -0,0 +1,17 @@ +"""Shared type aliases.""" + +from typing import TypedDict + + +class GoLimits(TypedDict, total=False): + """Parsed ``go`` arguments. Every key is optional; missing means "no limit".""" + + depth: int + nodes: int + movetime: int # milliseconds + wtime: int + btime: int + winc: int + binc: int + movestogo: int + infinite: bool diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_clock.py b/tests/test_clock.py new file mode 100644 index 0000000..bdd4a0e --- /dev/null +++ b/tests/test_clock.py @@ -0,0 +1,51 @@ +"""Unit tests for ``clock`` - the stop predicate and time management.""" + +import chess +import pytest + +from pychess.clock import Clock, deadline_from_limits + + +def test_never_stops_until_armed(): + clock = Clock(deadline=0.0) # already in the past + assert clock.should_stop(10**9) is False + clock.arm() + assert clock.should_stop(0) is True + + +def test_node_limit(): + clock = Clock(node_limit=1000) + clock.arm() + assert clock.should_stop(999) is False + assert clock.should_stop(1000) is True + + +def test_deadline_from_limits_movetime(): + assert deadline_from_limits(chess.Board(), {"movetime": 2000}, 100.0) == 102.0 + + +def test_deadline_from_limits_depth_only_is_open_ended(): + assert deadline_from_limits(chess.Board(), {"depth": 8}, 0.0) is None + + +def test_deadline_from_limits_bare_go_uses_default(): + assert deadline_from_limits(chess.Board(), {}, 0.0) == pytest.approx(4.0) + + +def test_deadline_from_limits_infinite(): + assert deadline_from_limits(chess.Board(), {"infinite": True}, 0.0) == 60.0 + + +def test_deadline_from_limits_clock_budget(): + # 60s left, 2s increment, 30 moves to go: 60000/31 + 0.75*2000 ms, + # below the 0.4*wtime cap. + board = chess.Board() + got = deadline_from_limits(board, {"wtime": 60000, "winc": 2000, "movestogo": 30}, 0.0) + assert got == pytest.approx(60000 / 31 / 1000 + 1.5) + + +def test_deadline_from_limits_uses_side_to_move_clock(): + board = chess.Board() + board.push_uci("e2e4") # black to move -> btime applies, wtime ignored + got = deadline_from_limits(board, {"wtime": 1, "btime": 60000}, 0.0) + assert got == pytest.approx(60000 / 31 / 1000) diff --git a/tests/test_engine.py b/tests/test_engine.py new file mode 100644 index 0000000..509228a --- /dev/null +++ b/tests/test_engine.py @@ -0,0 +1,61 @@ +"""Tests for the assembled engines and the Lazy SMP coordinator.""" + +import time + +import chess + +from pychess import lazy_smp +from pychess.engine import Engine, RandomEngine +from pychess.lazy_smp import SearchResult, _Payload, _result_rank, _worker +from pychess.shared_tt import SharedFlag, SharedTT + + +def test_random_engine_returns_a_legal_move(): + board = chess.Board() + result = RandomEngine().search(board) + assert isinstance(result, SearchResult) + assert result.pv[0] in set(board.legal_moves) + assert result.score == 0 + + +def test_result_rank_orders_win_over_depth_over_loss(): + win = lazy_smp._WorkerResult(9999, ["a1a8"], 3, 10) + deep = lazy_smp._WorkerResult(20, ["e2e4"], 8, 10) + shallow = lazy_smp._WorkerResult(50, ["d2d4"], 4, 10) + loss = lazy_smp._WorkerResult(-9999, ["h2h3"], 5, 10) + assert max([deep, shallow, win, loss], key=_result_rank) is win + assert max([deep, shallow, loss], key=_result_rank) is deep + assert min([deep, shallow, loss], key=_result_rank) is loss + + +def test_worker_runs_a_search_in_process(): + tt = SharedTT(slots=1 << 12, create=True) + stop = SharedFlag(create=True) + try: + payload: _Payload = ( + chess.STARTING_FEN, + [], + None, + 3, + time.time() + 5.0, + tt.name, + tt.slots, + 0, + stop.name, + ) + result = _worker(payload) + assert result.depth >= 1 + assert result.pv and chess.Move.from_uci(result.pv[0]) in chess.Board().legal_moves + assert result.nodes > 0 + finally: + stop.close() + stop.unlink() + tt.close() + tt.unlink() + + +def test_engine_search_end_to_end(): + result = Engine().search(chess.Board(), {"movetime": 300}) + assert result.pv + assert result.pv[0] in set(chess.Board().legal_moves) + assert result.nodes > 0 diff --git a/tests/test_evaluation.py b/tests/test_evaluation.py new file mode 100644 index 0000000..35deee1 --- /dev/null +++ b/tests/test_evaluation.py @@ -0,0 +1,26 @@ +"""Unit tests for ``evaluation.PestoEvaluator``.""" + +import chess + +from pychess.eval_board import EvalBoard +from pychess.evaluation import PestoEvaluator + + +def test_startpos_is_roughly_balanced(): + assert abs(PestoEvaluator().evaluate(chess.Board())) <= 60 + + +def test_side_to_move_relative(): + ev = PestoEvaluator() + w = chess.Board("4k3/8/8/8/8/8/8/R3K3 w - - 0 1") + b = chess.Board("4k3/8/8/8/8/8/8/R3K3 b - - 0 1") + assert ev.evaluate(w) > 0 # white to move, white is up a rook + assert ev.evaluate(b) < 0 # black to move, still down a rook + + +def test_incremental_accumulator_matches_recompute(): + incremental = EvalBoard() + for uci in ("e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6"): + incremental.push_uci(uci) + plain = chess.Board(incremental.fen()) + assert PestoEvaluator().evaluate(incremental) == PestoEvaluator().evaluate(plain) diff --git a/tests/test_move_ordering.py b/tests/test_move_ordering.py new file mode 100644 index 0000000..1f7025f --- /dev/null +++ b/tests/test_move_ordering.py @@ -0,0 +1,47 @@ +"""Unit tests for ``move_ordering.MoveOrderer``.""" + +import chess + +from pychess.move_ordering import MoveOrderer + + +def test_tt_move_comes_first(): + board = chess.Board() + tt_move = chess.Move.from_uci("g1f3") + ordered = MoveOrderer().order_moves(board, tt_move=tt_move, ply=0) + assert ordered[0] == tt_move + + +def test_captures_precede_quiets(): + # White pawn on e4 can take on d5; lots of quiet moves available. + board = chess.Board("rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2") + ordered = MoveOrderer().order_moves(board) + assert board.is_capture(ordered[0]) + assert ordered[0] == chess.Move.from_uci("e4d5") + + +def test_root_moves_restricts_the_root_only(): + board = chess.Board() + keep = {chess.Move.from_uci("e2e4"), chess.Move.from_uci("d2d4")} + orderer = MoveOrderer(root_moves=keep) + assert set(orderer.order_moves(board, ply=0)) == keep + # deeper plies are unrestricted + assert len(orderer.order_moves(board, ply=1)) == 20 + + +def test_killer_move_beats_other_quiets(): + board = chess.Board() + orderer = MoveOrderer() + killer = chess.Move.from_uci("h2h3") + orderer.record_killer(0, killer) + ordered = list(orderer.order_moves(board, ply=0)) + quiets = [m for m in ordered if not board.is_capture(m)] + assert quiets[0] == killer + + +def test_mvvlva_prefers_taking_the_bigger_piece(): + # White pawn on d4 could take either rook on c5 / e5. + board = chess.Board("3qk3/8/8/2r1r3/3P4/8/8/3QK3 w - - 0 1") + pxr = chess.Move.from_uci("d4c5") + pxr2 = chess.Move.from_uci("d4e5") + assert MoveOrderer().mvvlva(board, pxr) == MoveOrderer().mvvlva(board, pxr2) > 0 diff --git a/tests/test_negamax.py b/tests/test_negamax.py new file mode 100644 index 0000000..bb6ebbc --- /dev/null +++ b/tests/test_negamax.py @@ -0,0 +1,69 @@ +"""Unit tests for ``negamax`` - a ``Negamax`` assembled from real collaborators +plus the ``is_drawn`` helper.""" + +import chess +import pytest + +from pychess.clock import Clock +from pychess.constants import INF, MATE +from pychess.evaluation import PestoEvaluator +from pychess.move_ordering import MoveOrderer +from pychess.negamax import Negamax, SearchAbortError, is_drawn +from pychess.transposition import TranspositionTable + +MATE_IN_1 = chess.Board("4k3/8/4K3/8/8/8/8/7R w - - 0 1") # Rh8# + + +def make_negamax(clock: Clock | None = None, tt: TranspositionTable | None = None) -> Negamax: + return Negamax(PestoEvaluator(), MoveOrderer(), tt or TranspositionTable(), clock or Clock()) + + +def test_finds_mate_in_one(): + score, pv = make_negamax().search(MATE_IN_1.copy(), -INF, INF, 3) + assert score >= MATE - 100 + assert pv[0] == chess.Move.from_uci("h1h8") + + +def test_avoids_getting_mated(): + board = chess.Board("6k1/5ppp/8/8/8/8/5PPP/R5K1 b - - 0 1") + score, _pv = make_negamax().search(board, -INF, INF, 4) + assert score > -(MATE - 100) # not getting mated + + +def test_wins_the_hanging_rook(): + # Rooks share the 4th rank; black's is undefended and the king is far. + board = chess.Board("4k3/8/8/8/r6R/8/8/4K3 w - - 0 1") + score, pv = make_negamax().search(board, -INF, INF, 4) + assert pv[0] == chess.Move.from_uci("h4a4") + assert score > 300 + + +def test_depth_one_still_returns_a_move(): + _score, pv = make_negamax().search(chess.Board(), -INF, INF, 1) + assert pv and pv[0] in set(chess.Board().legal_moves) + + +def test_shares_node_count_between_search_and_quiescence(): + engine = make_negamax() + engine.search(chess.Board(), -INF, INF, 3) + assert engine.nodes > 0 + + +def test_abort_is_raised_once_the_clock_is_armed(): + clock = Clock(deadline=0.0) + clock.arm() + engine = make_negamax(clock=clock) + with pytest.raises(SearchAbortError): + engine.search(chess.Board(), -INF, INF, 6, ply=1) + + +def test_is_drawn_stalemate(): + assert is_drawn(chess.Board("7k/5Q2/6K1/8/8/8/8/8 b - - 0 1")) + + +def test_is_drawn_insufficient_material(): + assert is_drawn(chess.Board("4k3/8/8/8/8/8/8/4K3 w - - 0 1")) + + +def test_is_drawn_normal_position_is_not_drawn(): + assert not is_drawn(chess.Board()) diff --git a/test/test_perft.py b/tests/test_perft.py similarity index 96% rename from test/test_perft.py rename to tests/test_perft.py index 0bcd007..3091740 100644 --- a/test/test_perft.py +++ b/tests/test_perft.py @@ -3,12 +3,13 @@ Reference node counts are the well-known published values from the Chess Programming Wiki (https://www.chessprogramming.org/Perft_Results). """ + import multiprocessing import chess import pytest -from perft import count_nodes, parallel_perft +from pychess.perft import count_nodes, parallel_perft STARTPOS = chess.STARTING_FEN KIWIPETE = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1" diff --git a/tests/test_transposition.py b/tests/test_transposition.py new file mode 100644 index 0000000..c6826d0 --- /dev/null +++ b/tests/test_transposition.py @@ -0,0 +1,62 @@ +"""Unit tests for ``transposition.TranspositionTable``.""" + +import chess + +from pychess.constants import INF, MATE_GUARD, TT_EXACT, TT_LOWER, TT_UPPER +from pychess.transposition import TranspositionTable + +STARTPOS = chess.Board() + + +def test_probe_miss_on_empty(): + tt = TranspositionTable() + assert tt.probe(tt.key(STARTPOS), 1, -INF, INF) == (False, 0, None) + + +def test_exact_roundtrips(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + move = chess.Move.from_uci("e2e4") + tt.store(key, 4, 25, TT_EXACT, move) + assert tt.probe(key, 4, -INF, INF) == (True, 25, move) + + +def test_shallower_entry_is_not_a_cutoff_but_still_gives_the_move(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + move = chess.Move.from_uci("e2e4") + tt.store(key, 2, 25, TT_EXACT, move) + assert tt.probe(key, 5, -INF, INF) == (False, 0, move) + + +def test_lower_bound_only_cuts_when_it_beats_beta(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + tt.store(key, 4, 50, TT_LOWER, None) + assert tt.probe(key, 4, -INF, 40) == (True, 50, None) + assert tt.probe(key, 4, -INF, 60) == (False, 0, None) + + +def test_upper_bound_only_cuts_when_it_is_below_alpha(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + tt.store(key, 4, 50, TT_UPPER, None) + assert tt.probe(key, 4, 60, INF) == (True, 50, None) + assert tt.probe(key, 4, 40, INF) == (False, 0, None) + + +def test_deeper_entry_is_kept_on_store(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + tt.store(key, 6, 10, TT_EXACT, None) + tt.store(key, 3, 999, TT_EXACT, None) + assert tt.probe(key, 3, -INF, INF) == (True, 10, None) + + +def test_mate_scores_are_never_returned_as_a_bound(): + tt = TranspositionTable() + key = tt.key(STARTPOS) + move = chess.Move.from_uci("e2e4") + tt.store(key, 5, MATE_GUARD + 1, TT_EXACT, move) + cutoff, value, got = tt.probe(key, 3, -INF, INF) + assert cutoff is False and value == 0 and got == move diff --git a/tests/test_uci.py b/tests/test_uci.py new file mode 100644 index 0000000..3c7e776 --- /dev/null +++ b/tests/test_uci.py @@ -0,0 +1,147 @@ +"""Tests for the UCI protocol layer (``pychess.__main__``).""" + +import builtins + +import chess +import pytest + +from pychess import __main__ as cli +from pychess.__main__ import UCI, main +from pychess.engine import RandomEngine +from pychess.lazy_smp import SearchResult +from pychess.types import GoLimits + + +class DeadEngine: + """Always returns an empty PV, to exercise the ``bestmove 0000`` path.""" + + def search(self, board: chess.Board, limits: GoLimits | None = None) -> SearchResult: + return SearchResult(0, [], 0, 0, 0.0) + + +@pytest.fixture +def uci(monkeypatch): + """A UCI session with the opening book disabled and a fast random engine.""" + monkeypatch.setattr(cli, "BOOK_PATH", "/nonexistent/book.bin") + session = UCI() + session.engine = RandomEngine() + return session + + +class TestParseGo: + def test_integer_params(self): + limits = UCI().parse_go(["go", "depth", "8", "movetime", "1500", "wtime", "60000"]) + assert limits == {"depth": 8, "movetime": 1500, "wtime": 60000} + + def test_infinite_flag(self): + assert UCI().parse_go(["go", "infinite"]) == {"infinite": True} + + def test_bad_value_is_ignored(self): + assert UCI().parse_go(["go", "depth", "xyz"]) == {} + + def test_bare_go(self): + assert UCI().parse_go(["go"]) == {} + + +class TestProcessCommand: + def test_uci_handshake(self, uci, capsys): + uci.process_command("uci") + out = capsys.readouterr().out + assert "id name pychess" in out + assert "uciok" in out + + def test_isready(self, uci, capsys): + uci.process_command("isready") + assert capsys.readouterr().out.strip() == "readyok" + + def test_unknown_command(self, uci, capsys): + uci.process_command("frobnicate") + assert "Unknown command" in capsys.readouterr().out + + def test_ignored_commands_do_not_raise(self, uci): + for cmd in ("debug on", "setoption name X", "register", "stop", "ponderhit"): + uci.process_command(cmd) + + def test_quit_exits(self, uci): + with pytest.raises(SystemExit): + uci.process_command("quit") + + def test_ucinewgame_resets_state(self, uci): + uci.board.push_uci("e2e4") + uci.process_command("ucinewgame") + assert uci.board.fen() == chess.STARTING_FEN + + def test_position_startpos_with_moves(self, uci): + uci.process_command("position startpos moves e2e4 e7e5") + assert [m.uci() for m in uci.board.move_stack] == ["e2e4", "e7e5"] + + def test_position_fen(self, uci): + fen = "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1" + uci.process_command(f"position fen {fen}") + assert uci.board.fen() == fen + + def test_print_commands(self, uci, capsys): + uci.process_command("position startpos moves d2d4") + uci.process_command("printBoard") + uci.process_command("printLegalMoves") + uci.process_command("printMoveStack") + out = capsys.readouterr().out + assert "d4" in out # move stack / legal moves rendered as SAN + + def test_perft(self, uci, capsys): + uci.process_command("position startpos") + uci.process_command("perft 2") + assert "nodes 400" in capsys.readouterr().out + + def test_go_uses_the_engine_when_off_book(self, uci, capsys): + uci.process_command("position startpos moves e2e4 e7e5") + uci.process_command("go depth 1") + out = capsys.readouterr().out + assert out.startswith("info starting search") + assert "bestmove " in out + + def test_go_falls_back_to_a_legal_move(self, uci, capsys): + uci.engine = DeadEngine() + uci.process_command("go depth 1") + assert "bestmove 0000" in capsys.readouterr().out + + def test_self_play_stops_on_a_finished_game(self, uci, capsys): + uci.board = chess.Board("7k/5Q2/6K1/8/8/8/8/8 b - - 0 1") # stalemate + uci.process_command("selfPlay") + assert capsys.readouterr().out.strip().endswith("1/2-1/2") + + def test_self_play_loops_then_stops_on_empty_pv(self, uci, capsys): + uci.engine = DeadEngine() + uci.process_command("selfPlay") + out = capsys.readouterr().out + assert "info depth" not in out # DeadEngine's empty PV breaks the loop + assert out.strip().endswith("*") # game still in progress + + def test_self_play_plays_book_moves(self, monkeypatch, capsys): + # Re-enable the book so the book branch of the loop runs, then stop it. + session = UCI() + session.engine = DeadEngine() + calls = iter([chess.Move.from_uci("e2e4"), None]) + monkeypatch.setattr(session, "book_move", lambda: next(calls)) + session.process_command("selfPlay") + assert session.board.move_stack[0].uci() == "e2e4" + + +class TestBookMove: + def test_missing_book_returns_none(self, uci): + assert uci.book_move() is None # fixture points BOOK_PATH at nothing + + def test_real_book_returns_a_legal_move(self): + session = UCI() # real BOOK_PATH + move = session.book_move() + if move is not None: # book file is present in a source checkout + assert move in session.board.legal_moves + + +def test_main_loop_processes_until_quit(monkeypatch, capsys): + commands = iter(["isready", "uci", "quit"]) + monkeypatch.setattr(builtins, "input", lambda: next(commands)) + main() + out = capsys.readouterr().out + assert "readyok" in out + assert "uciok" in out diff --git a/transposition.py b/transposition.py deleted file mode 100644 index 39a82de..0000000 --- a/transposition.py +++ /dev/null @@ -1,74 +0,0 @@ -from chess.polyglot import zobrist_hash - -# Entry flags -TT_EXACT = 0 # value is exact -TT_LOWER = 1 # value is a lower bound (fail-high / beta cut-off) -TT_UPPER = 2 # value is an upper bound (fail-low / all moves searched) - -# Scores at or beyond this magnitude are mate-related. The engine currently -# scores mate by remaining depth rather than distance-to-root, so those values -# are not safe to reuse for cut-offs across different depths - we still keep the -# stored move for ordering, but never return the score as a bound. -MATE_GUARD = 9000 - - -class TranspositionTableMixin(object): - """A simple always-replace-if-deeper transposition table. - - Keyed by Zobrist hash (``chess.polyglot.zobrist_hash``). Entries are - ``(depth, value, flag, move)`` tuples. The table lives on the engine - instance and persists between ``go`` commands; ``ucinewgame`` builds a - fresh engine which drops it. - - When ``self._shared_tt`` is set (Lazy SMP workers) probes and stores are - delegated to that cross-process table instead of the per-instance dict. - """ - - _shared_tt = None - - @property - def transposition_table(self): - try: - return self._transposition_table - except AttributeError: - self._transposition_table = {} - return self._transposition_table - - def tt_clear(self): - self.transposition_table.clear() - - def tt_key(self, board): - return zobrist_hash(board) - - def tt_probe(self, key, depth, alpha, beta): - """Return ``(cutoff, value, move)``. - - ``cutoff`` is True when the stored value can be returned directly. - ``move`` is the stored best move (possibly None) and is always - returned for move ordering even when no cut-off is possible. - """ - if self._shared_tt is not None: - return self._shared_tt.probe(key, depth, alpha, beta) - - entry = self.transposition_table.get(key) - if entry is None: - return False, 0, None - - e_depth, e_value, e_flag, e_move = entry - if e_depth >= depth and abs(e_value) < MATE_GUARD: - if e_flag == TT_EXACT: - return True, e_value, e_move - if e_flag == TT_LOWER and e_value >= beta: - return True, e_value, e_move - if e_flag == TT_UPPER and e_value <= alpha: - return True, e_value, e_move - return False, 0, e_move - - def tt_store(self, key, depth, value, flag, move): - if self._shared_tt is not None: - self._shared_tt.store(key, depth, value, flag, move) - return - existing = self.transposition_table.get(key) - if existing is not None and existing[0] > depth: - return # keep the deeper analysis - self.transposition_table[key] = (depth, value, flag, move) From 7ab15c627c65a83cd5216be477512594a485e5a5 Mon Sep 17 00:00:00 2001 From: Christopher Junius <41166228+cjunius@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:03:26 -0400 Subject: [PATCH 2/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/pychess/lazy_smp.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pychess/lazy_smp.py b/src/pychess/lazy_smp.py index 2b4da4d..9ddff2a 100644 --- a/src/pychess/lazy_smp.py +++ b/src/pychess/lazy_smp.py @@ -113,7 +113,8 @@ def search( start = time.time() n_workers = max(1, multiprocessing.cpu_count() - 1) - deadline = deadline_from_limits(board, limits, start) or (start + DEFAULT_MOVETIME) + deadline = deadline_from_limits(board, limits, start) + deadline = deadline if deadline is not None else float("inf") max_depth = min(int(limits.get("depth") or MAX_DEPTH), MAX_DEPTH) root_fen = board.root().fen() From ebc95b94f7a8e264367d016571c22c411c33a8ae Mon Sep 17 00:00:00 2001 From: Christopher Junius <41166228+cjunius@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:03:49 -0400 Subject: [PATCH 3/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/pychess/__main__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/pychess/__main__.py b/src/pychess/__main__.py index 6a26cf9..28a44c5 100644 --- a/src/pychess/__main__.py +++ b/src/pychess/__main__.py @@ -35,7 +35,9 @@ def __init__(self) -> None: self.depth = 4 def process_command(self, line: str) -> None: - args = line.split(" ") + args = line.strip().split() + if not args: + return match args[0]: case "uci": print(f"id name pychess {__version__}") From 6f9d2cedca77b600a77cca21a9a7a8c59458875b Mon Sep 17 00:00:00 2001 From: Christopher Junius <41166228+cjunius@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:04:06 -0400 Subject: [PATCH 4/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/pychess/negamax.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pychess/negamax.py b/src/pychess/negamax.py index 982bb66..602794c 100644 --- a/src/pychess/negamax.py +++ b/src/pychess/negamax.py @@ -69,7 +69,7 @@ def search( if board.is_checkmate(): return -MATE - depth, [] if is_drawn(board): - return -depth, [] + return 0, [] return self.quiesce(board, alpha, beta, 0), [] alpha_orig = alpha From a69d71f7055925134b7593dc5fd21c17553c6548 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 30 Aug 2026 13:06:33 +0000 Subject: [PATCH 5/8] Pass node_limit through to Clock in Lazy SMP workers Co-authored-by: cjunius <41166228+cjunius@users.noreply.github.com> --- CHANGELOG.md | 5 +++++ src/pychess/lazy_smp.py | 33 +++++++++++++++++++++++++++------ tests/test_engine.py | 1 + 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 323d527..a0b8d3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,11 @@ follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). `SearchResult` and `__main__` does all formatting. - License changed to Apache-2.0. +### Fixed + +- `go nodes N` now enforces the node limit in Lazy SMP workers; previously the + limit was parsed but never passed to `Clock`. + ### Removed - The single-process search path; `go` always runs Lazy SMP. diff --git a/src/pychess/lazy_smp.py b/src/pychess/lazy_smp.py index 9ddff2a..0f6c19e 100644 --- a/src/pychess/lazy_smp.py +++ b/src/pychess/lazy_smp.py @@ -26,7 +26,7 @@ SMP_TT_SLOTS = 1 << 20 # 1M entries * 16 bytes = 16 MB # The pickled payload each worker process receives. -_Payload = tuple[str, list[str], list[str] | None, int, float, str, int, int, str] +_Payload = tuple[str, list[str], list[str] | None, int, float, int | None, str, int, int, str] class _WorkerResult(NamedTuple): @@ -54,9 +54,18 @@ def _worker(payload: _Payload) -> _WorkerResult: they populate the shared table along slightly different paths; the shared entries then speed up every other worker. """ - (root_fen, moves, root_slice, max_depth, deadline, tt_name, tt_slots, worker_id, stop_name) = ( - payload - ) + ( + root_fen, + moves, + root_slice, + max_depth, + deadline, + node_limit, + tt_name, + tt_slots, + worker_id, + stop_name, + ) = payload tt = SharedTT(slots=tt_slots, name=tt_name, create=False) stop = SharedFlag(name=stop_name, create=False) @@ -69,7 +78,7 @@ def _worker(payload: _Payload) -> _WorkerResult: if root_slice is not None: root_moves = {chess.Move.from_uci(u) for u in root_slice} - clock = Clock(deadline=deadline, stop_flag=stop) + clock = Clock(deadline=deadline, node_limit=node_limit, stop_flag=stop) searcher = Negamax(PestoEvaluator(), MoveOrderer(root_moves=root_moves), tt, clock) best = _WorkerResult(0, [], 0, 0) @@ -131,8 +140,20 @@ def search( tt = SharedTT(slots=tt_slots, create=True) stop = SharedFlag(create=True) + node_limit = limits.get("nodes") payloads: list[_Payload] = [ - (root_fen, moves, slices[i], max_depth, deadline, tt.name, tt.slots, i, stop.name) + ( + root_fen, + moves, + slices[i], + max_depth, + deadline, + node_limit, + tt.name, + tt.slots, + i, + stop.name, + ) for i in range(n_workers) ] try: diff --git a/tests/test_engine.py b/tests/test_engine.py index 509228a..6b98d80 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -38,6 +38,7 @@ def test_worker_runs_a_search_in_process(): None, 3, time.time() + 5.0, + None, tt.name, tt.slots, 0, From fcbac36fd6259b2479a78985f146c3e828dc8051 Mon Sep 17 00:00:00 2001 From: Christopher Junius <41166228+cjunius@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:07:26 -0400 Subject: [PATCH 6/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/pychess/__main__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/pychess/__main__.py b/src/pychess/__main__.py index 28a44c5..3b24965 100644 --- a/src/pychess/__main__.py +++ b/src/pychess/__main__.py @@ -170,7 +170,10 @@ def main() -> None: signal.signal(signal.SIGINT, lambda *_: sys.exit(0)) uci = UCI() while True: - command = input() + try: + command = input() + except EOFError: + break if command == "quit": break uci.process_command(command) From 21153572acb53f52edb3aa8059c68ba3dab403f8 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 30 Aug 2026 13:09:11 +0000 Subject: [PATCH 7/8] Remove unused DEFAULT_MOVETIME import in lazy_smp Co-authored-by: cjunius <41166228+cjunius@users.noreply.github.com> --- src/pychess/lazy_smp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pychess/lazy_smp.py b/src/pychess/lazy_smp.py index 0f6c19e..de255df 100644 --- a/src/pychess/lazy_smp.py +++ b/src/pychess/lazy_smp.py @@ -14,7 +14,7 @@ import chess -from .clock import DEFAULT_MOVETIME, MAX_DEPTH, Clock, deadline_from_limits +from .clock import MAX_DEPTH, Clock, deadline_from_limits from .constants import INF, MATE_IN_MAX from .eval_board import EvalBoard from .evaluation import PestoEvaluator From 8fc77b1f0e8f12c0e90e27f130b683b2feb369ed Mon Sep 17 00:00:00 2001 From: Christopher Junius <41166228+cjunius@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:12:40 -0400 Subject: [PATCH 8/8] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/pychess/lazy_smp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pychess/lazy_smp.py b/src/pychess/lazy_smp.py index de255df..6661e55 100644 --- a/src/pychess/lazy_smp.py +++ b/src/pychess/lazy_smp.py @@ -79,6 +79,7 @@ def _worker(payload: _Payload) -> _WorkerResult: root_moves = {chess.Move.from_uci(u) for u in root_slice} clock = Clock(deadline=deadline, node_limit=node_limit, stop_flag=stop) + clock.arm() searcher = Negamax(PestoEvaluator(), MoveOrderer(root_moves=root_moves), tt, clock) best = _WorkerResult(0, [], 0, 0) @@ -88,7 +89,6 @@ def _worker(payload: _Payload) -> _WorkerResult: score, pv = searcher.search(board, -INF, INF, depth) except SearchAbortError: break - clock.arm() best = _WorkerResult(score, [m.uci() for m in pv], depth, searcher.nodes) if stop.is_set() or time.time() >= deadline: break