diff --git a/chess/chesstb.py b/chess/chesstb.py index aa9af00a8..2928d20ce 100644 --- a/chess/chesstb.py +++ b/chess/chesstb.py @@ -1,60 +1,49 @@ -"""Pure-Python prober for the *chesstb* endgame tablebase format -(WDL ``.lzw`` / DTZ ``.lzdtz`` / DTC ``.lzdtc`` / DTM ``.lzdtm`` -/ DTM50 ``.lzdtm50``). - -Upstream: https://github.com/noobpwnftw/chesstb - -Shaped like :mod:`chess.syzygy`: a :class:`Tablebase` opens a directory of -table files and answers WDL / DTZ / DTC / DTM / DTM50 queries. - -Every ``probe_*`` distance is signed from the side to move: ``+N`` toward a win, -``-N`` toward a loss, ``0`` for no decisive result -- a draw, a clock that has -taken the win, or a mate already on the board. :meth:`Tablebase.probe` keeps -every class field explicit for callers wanting the class outright. - -A :class:`Tablebase` is safe to share between threads and probe concurrently. -""" from __future__ import annotations import array import collections import contextlib -import importlib +import dataclasses import lzma import mmap import os import struct import sys import threading -from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Type, Union +from typing import Any, NamedTuple +from collections.abc import Iterator +from types import TracebackType +from typing import TypeAlias import chess try: - _lz4_block: Any = importlib.import_module("lz4.block") + import lz4.block as _lz4_block # type: ignore except ImportError: _lz4_block = None __all__ = ["Tablebase", "ProbeResult", "MissingTableError", "open_tablebase"] -#: :attr:`PieceConfig.cache_key`. A 'p' or 'r' material shares its plain +_StrPath: TypeAlias = str | os.PathLike[str] + +#: :attr:`_PieceConfig.cache_key`. A 'p' or 'r' material shares its plain #: twin's ``min_key``, so the marks join the key. -CacheKey = Tuple[int, bool, int] +_CacheKey = tuple[int, bool, int] -#: One material's key: see :func:`full_material_key`. -MaterialKey = Tuple[int, bool, int] +#: One material's key: see :func:`_full_material_key`. +_MaterialKey = tuple[int, bool, int] # The uint32 table header reserves its low two bits for the table number. _PACKED_MATERIAL_KEY_MASK = 0x3FFFFFFF -def side_index(color: chess.Color) -> int: +def _side_index(color: chess.Color) -> int: """0 for white, 1 for black, as the table format orders them.""" return 0 if color == chess.WHITE else 1 # --- Square transforms (src/probe/position_index.cpp) --- -def apply_transform(bb: int, t: int) -> int: +def _apply_transform(bb: int, t: int) -> int: """Symmetry transform mask on every square of a bitboard: 1 mirrors the files, 2 the ranks, 4 then the a1-h8 diagonal.""" if t & 1: @@ -66,9 +55,9 @@ def apply_transform(bb: int, t: int) -> int: return bb -SYM_NONE = 0 -SYM_FILE_MIRROR = 1 -SYM_DIHEDRAL_8 = 2 +_SYM_NONE = 0 +_SYM_FILE_MIRROR = 1 +_SYM_DIHEDRAL_8 = 2 # White king squares of the slices: files a-d under the file mirror, the # a1-d1-d4 triangle under all eight symmetries. @@ -85,7 +74,7 @@ def apply_transform(bb: int, t: int) -> int: _BINOM[_k][_n] = 0 if _n > _k else _BINOM[_k - 1][_n - 1] + _BINOM[_k - 1][_n] -def binom(n: int, k: int) -> int: +def _binom(n: int, k: int) -> int: if k < 0 or k > 7 or n < 0 or n > 64: return 0 return _BINOM[n][k] @@ -97,8 +86,8 @@ def binom(n: int, k: int) -> int: } -def full_material_key(pieces: List[Tuple[chess.Color, chess.PieceType]], has_pair: bool = False, - castling_rights: Tuple[int, int] = (0, 0)) -> MaterialKey: +def _full_material_key(pieces: list[tuple[chess.Color, chess.PieceType]], has_pair: bool = False, + castling_rights: tuple[int, int] = (0, 0)) -> _MaterialKey: """The base-9 count word, then the pair flag and rights code as tiebreaks. KRKr and KrKR differ only in the code, so compare these whole. Rooks holding a right count in the word, so KrK orders ahead of KKr; the @@ -115,8 +104,8 @@ def full_material_key(pieces: List[Tuple[chess.Color, chess.PieceType]], has_pai _TYPE_ORDER = {chess.KING: 0, chess.QUEEN: 1, chess.ROOK: 2, chess.BISHOP: 3, chess.KNIGHT: 4, chess.PAWN: 5} -def _composition_key(pieces: List[Tuple[chess.Color, chess.PieceType]], - color: chess.Color) -> List[int]: +def _composition_key(pieces: list[tuple[chess.Color, chess.PieceType]], + color: chess.Color) -> list[int]: """Piece counts for `color` by type: the side-ordering tiebreak when strengths are equal.""" counts = [0] * 7 @@ -126,7 +115,7 @@ def _composition_key(pieces: List[Tuple[chess.Color, chess.PieceType]], return counts -class PieceConfig: +class _PieceConfig: """Canonical material. `pieces` lists the (color, type) of the free men, white's first. `has_pair` marks an opposing pawn pair ('p'), indexed jointly and left out of `pieces`.""" @@ -135,8 +124,8 @@ class PieceConfig: "mirrored", "has_castling", "castling_code", "min_key", "cache_key", "num_pieces", "is_bare_kings") - def __init__(self, pieces: List[Tuple[chess.Color, chess.PieceType]], - has_pair: bool = False, castling_rights: Tuple[int, int] = (0, 0)): + def __init__(self, pieces: list[tuple[chess.Color, chess.PieceType]], + has_pair: bool = False, castling_rights: tuple[int, int] = (0, 0)): wr, br = castling_rights ws = sum(_STRENGTH[t] for c, t in pieces if c == chess.WHITE) bs = sum(_STRENGTH[t] for c, t in pieces if c == chess.BLACK) @@ -157,14 +146,14 @@ def __init__(self, pieces: List[Tuple[chess.Color, chess.PieceType]], if swap: pieces = [(not c, t) for c, t in pieces] wr, br = br, wr - pieces = sorted(pieces, key=lambda ct: (side_index(ct[0]), _TYPE_ORDER[ct[1]])) + pieces = sorted(pieces, key=lambda ct: (_side_index(ct[0]), _TYPE_ORDER[ct[1]])) # Exactly `literal != base_key`: a self-mirror material never swaps. self.mirrored = swap self.pieces = pieces self.has_pair = has_pair self.castling_rights = (wr, br) - self.base_key = full_material_key(pieces, has_pair, (wr, br)) - self.mirr_key = full_material_key( + self.base_key = _full_material_key(pieces, has_pair, (wr, br)) + self.mirr_key = _full_material_key( [(not c, t) for c, t in pieces], has_pair, (br, wr)) self.has_castling = wr + br > 0 # Tiebreak below `min_key`: KRKr and KrKR differ only here. Fewer white @@ -172,7 +161,7 @@ def __init__(self, pieces: List[Tuple[chess.Color, chess.PieceType]], self.castling_code = wr * 3 + br # The 30-bit count word alone, as the on-disk header carries it. self.min_key = min(self.base_key, self.mirr_key)[0] - self.cache_key: CacheKey = (self.min_key, has_pair, self.castling_code) + self.cache_key: _CacheKey = (self.min_key, has_pair, self.castling_code) self.num_pieces = len(pieces) # `num_pieces` counts free men only (KpKp has 2), so test bare kings here. self.is_bare_kings = (self.num_pieces <= 2 and not has_pair @@ -185,8 +174,8 @@ def name(self) -> str: # by (side index, type order). written = [0, 0] - def write_castling_before(order: Tuple[int, int]) -> None: - for i in (side_index(chess.WHITE), side_index(chess.BLACK)): + def write_castling_before(order: tuple[int, int]) -> None: + for i in (_side_index(chess.WHITE), _side_index(chess.BLACK)): if written[i] == self.castling_rights[i]: continue if (i, _TYPE_ORDER[chess.ROOK]) >= order: @@ -195,37 +184,37 @@ def write_castling_before(order: Tuple[int, int]) -> None: written[i] = self.castling_rights[i] for c, t in self.pieces: - write_castling_before((side_index(c), _TYPE_ORDER[t])) + write_castling_before((_side_index(c), _TYPE_ORDER[t])) if t == chess.KING: if seen_white_king and self.has_pair: s.append("p") seen_white_king = True s.append(chess.piece_symbol(t).upper()) - write_castling_before((side_index(chess.BLACK) + 1, 0)) + write_castling_before((_side_index(chess.BLACK) + 1, 0)) if self.has_pair: s.append("p") return "".join(s) -_PIECE_CONFIG_CACHE: Dict[Tuple[Tuple[Tuple[chess.Color, chess.PieceType], ...], bool, - Tuple[int, int]], - PieceConfig] = {} +_PIECE_CONFIG_CACHE: dict[tuple[tuple[tuple[chess.Color, chess.PieceType], ...], bool, + tuple[int, int]], + _PieceConfig] = {} -def piece_config(pieces: List[Tuple[chess.Color, chess.PieceType]], has_pair: bool = False, - castling_rights: Tuple[int, int] = (0, 0)) -> PieceConfig: - """A shared :class:`PieceConfig` for this material. Immutable and cheap, +def _piece_config(pieces: list[tuple[chess.Color, chess.PieceType]], has_pair: bool = False, + castling_rights: tuple[int, int] = (0, 0)) -> _PieceConfig: + """A shared :class:`_PieceConfig` for this material. Immutable and cheap, so a racing build needs no lock.""" key = (tuple(sorted(pieces)), has_pair, castling_rights) cfg = _PIECE_CONFIG_CACHE.get(key) if cfg is None: - cfg = PieceConfig(pieces, has_pair, castling_rights) + cfg = _PieceConfig(pieces, has_pair, castling_rights) _PIECE_CONFIG_CACHE[key] = cfg return cfg def _material_from_board(board: chess.Board, excluded: int = 0 - ) -> List[Tuple[chess.Color, chess.PieceType]]: + ) -> list[tuple[chess.Color, chess.PieceType]]: """The men on `board` as (color, piece type), squares in `excluded` left out.""" keep = ~excluded @@ -239,44 +228,44 @@ def _material_from_board(board: chess.Board, excluded: int = 0 def _piece_config_from_board(board: chess.Board, rooks: int, - pair: Optional[Tuple[int, int]]) -> Tuple["PieceConfig", bool]: - """(PieceConfig, mirrored?) of the table for the board's material, less the + pair: tuple[int, int] | None) -> tuple[_PieceConfig, bool]: + """(_PieceConfig, mirrored?) of the table for the board's material, less the `rooks` holding a right and the opposing `pair` squares, as marks; mirrored if colors had to swap to put the stronger side on white.""" excluded = rooks if pair is None else rooks | chess.BB_SQUARES[pair[0]] | chess.BB_SQUARES[pair[1]] rights = (chess.popcount(rooks & board.occupied_co[chess.WHITE]), chess.popcount(rooks & board.occupied_co[chess.BLACK])) - cfg = piece_config(_material_from_board(board, excluded), pair is not None, rights) + cfg = _piece_config(_material_from_board(board, excluded), pair is not None, rights) return cfg, cfg.mirrored # --- Piece_Class enum (src/chess/piece_config.h) --- -(BLACK_KINGS, BLACK_KNIGHTS, BLACK_BISHOPS, BLACK_ROOKS, BLACK_QUEENS, BLACK_PAWNS, - WHITE_KINGS, WHITE_KNIGHTS, WHITE_BISHOPS, WHITE_ROOKS, WHITE_QUEENS, WHITE_PAWNS) = range(12) -PIECE_CLASS_NB = 12 +(_BLACK_KINGS, _BLACK_KNIGHTS, _BLACK_BISHOPS, _BLACK_ROOKS, _BLACK_QUEENS, _BLACK_PAWNS, + _WHITE_KINGS, _WHITE_KNIGHTS, _WHITE_BISHOPS, _WHITE_ROOKS, _WHITE_QUEENS, _WHITE_PAWNS) = range(12) +_PIECE_CLASS_NB = 12 _PTCLASS = {chess.KING: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4, chess.PAWN: 5} -def make_piece_class(color: chess.Color, ptype: int) -> int: - base = WHITE_KINGS if color == chess.WHITE else BLACK_KINGS +def _make_piece_class(color: chess.Color, ptype: int) -> int: + base = _WHITE_KINGS if color == chess.WHITE else _BLACK_KINGS return base + _PTCLASS[ptype] -def class_to_piece(pcl: int) -> Tuple[chess.Color, int]: - color = chess.WHITE if pcl >= WHITE_KINGS else chess.BLACK - off = pcl - (WHITE_KINGS if color == chess.WHITE else BLACK_KINGS) +def _class_to_piece(pcl: int) -> tuple[chess.Color, int]: + color = chess.WHITE if pcl >= _WHITE_KINGS else chess.BLACK + off = pcl - (_WHITE_KINGS if color == chess.WHITE else _BLACK_KINGS) inv = {0: chess.KING, 1: chess.KNIGHT, 2: chess.BISHOP, 3: chess.ROOK, 4: chess.QUEEN, 5: chess.PAWN} return color, inv[off] -class PieceGroup: +class _PieceGroup: def __init__(self, ptype: int, count: int): self.count = count # The legal squares run on from the first: a2..h7 for pawns. self.first = chess.A2 if ptype == chess.PAWN else chess.A1 self.num_legal = chess.H7 - chess.A2 + 1 if ptype == chess.PAWN else 64 - self.table_size = binom(self.num_legal, count) + self.table_size = _binom(self.num_legal, count) def index_of(self, bb: int) -> int: """Colex rank of the pieces on bitboard ``bb``.""" @@ -292,10 +281,10 @@ def squares(self, idx: int) -> int: hi = self.num_legal for k in range(self.count, 0, -1): p = hi - 1 - while binom(p, k) > rank: + while _binom(p, k) > rank: p -= 1 pos[k - 1] = p - rank -= binom(p, k) + rank -= _binom(p, k) hi = p bb = 0 for p in pos: @@ -304,15 +293,15 @@ def squares(self, idx: int) -> int: # --- King_Slice_Manager (src/egtb/king_slice_manager.cpp) --- -class KingSliceManager: +class _KingSliceManager: def __init__(self, sym: int): self.sym = sym - n_trans = 8 if sym == SYM_DIHEDRAL_8 else 2 - anchors = _ANCHOR_TRIANGLE if sym == SYM_DIHEDRAL_8 else _ANCHOR_FILE_MIRROR + n_trans = 8 if sym == _SYM_DIHEDRAL_8 else 2 + anchors = _ANCHOR_TRIANGLE if sym == _SYM_DIHEDRAL_8 else _ANCHOR_FILE_MIRROR SLICE_NONE = -1 - # Per (wk, bk): slice id, the apply_transform bits to reach it (0: none), + # Per (wk, bk): slice id, the _apply_transform bits to reach it (0: none), # and whether the diagonal stabilizer decides. - self.pair: List[List[int]] = [[SLICE_NONE, 0, 0] for _ in range(64 * 64)] + self.pair: list[list[int]] = [[SLICE_NONE, 0, 0] for _ in range(64 * 64)] self.num_slices = 0 for wk in range(64): @@ -321,12 +310,12 @@ def __init__(self, sym: int): for bk in range(64): if bk == wk or chess.BB_KING_ATTACKS[wk] & chess.BB_SQUARES[bk]: continue - if (sym == SYM_DIHEDRAL_8 and _MAIN_DIAG & chess.BB_SQUARES[wk] + if (sym == _SYM_DIHEDRAL_8 and _MAIN_DIAG & chess.BB_SQUARES[wk] and _ABOVE_DIAG & chess.BB_SQUARES[bk]): continue sid = self.num_slices self.num_slices += 1 - stab = 1 if (sym == SYM_DIHEDRAL_8 and _MAIN_DIAG & chess.BB_SQUARES[wk] + stab = 1 if (sym == _SYM_DIHEDRAL_8 and _MAIN_DIAG & chess.BB_SQUARES[wk] and _MAIN_DIAG & chess.BB_SQUARES[bk]) else 0 self.pair[wk * 64 + bk] = [sid, 0, stab] @@ -338,8 +327,8 @@ def __init__(self, sym: int): if wk == bk or chess.BB_KING_ATTACKS[wk] & chess.BB_SQUARES[bk]: continue for t in range(n_trans): - wk_t = chess.lsb(apply_transform(chess.BB_SQUARES[wk], t)) - bk_t = chess.lsb(apply_transform(chess.BB_SQUARES[bk], t)) + wk_t = chess.lsb(_apply_transform(chess.BB_SQUARES[wk], t)) + bk_t = chess.lsb(_apply_transform(chess.BB_SQUARES[bk], t)) look = self.pair[wk_t * 64 + bk_t] if look[0] != -1 and look[1] == 0: e[0] = look[0] @@ -347,28 +336,28 @@ def __init__(self, sym: int): e[2] = look[2] break - def lookup(self, wk: int, bk: int) -> List[int]: + def lookup(self, wk: int, bk: int) -> list[int]: return self.pair[wk * 64 + bk] -class CastlingKingSliceManager: +class _CastlingKingSliceManager: """King slices for a castling material: (castling placement, free king square), or the placement alone when both sides hold rights. The order MUST match the C++: slice ids are on disk.""" def __init__(self, white_rights: int, black_rights: int): - self.sym = SYM_NONE + self.sym = _SYM_NONE self.rights = (white_rights, black_rights) - self.group = CastlingGroup(white_rights, black_rights) + self.group = _CastlingGroup(white_rights, black_rights) self.both_pinned = self.group.both_pinned self.num_slices = 0 - self._lookup: Dict[Tuple[int, int], int] = {} + self._lookup: dict[tuple[int, int], int] = {} for ci in range(self.group.table_size): pinned = 0 king_sq = [-1, -1] for color in (chess.WHITE, chess.BLACK): - i = side_index(color) + i = _side_index(color) if not self.rights[i]: continue kf, rook_mask = self.group.placement(ci, color) @@ -400,7 +389,7 @@ def slice_of(self, wk: int, bk: int, w_rooks: int, b_rooks: int) -> int: kfile = [-1, -1] masks = [0, 0] for color in (chess.WHITE, chess.BLACK): - i = side_index(color) + i = _side_index(color) if not self.rights[i]: if rooks[i]: return -1 @@ -422,7 +411,7 @@ def slice_of(self, wk: int, bk: int, w_rooks: int, b_rooks: int) -> int: # --- Castling_Group (src/chess/castling_group.h) --- -class CastlingGroup: +class _CastlingGroup: """Joint placement of each unmoved king and the rooks it can still castle with, on any files: 56 per side. The order MUST match the C++: stored king slice ids are built from it.""" @@ -431,14 +420,14 @@ class CastlingGroup: # A side's castling rooks as a mask over the files of its home rank. ROOK_MASKS = 1 << 8 # Per rights count: each placement as (king file, rook file mask), in order. - _SIDE_CACHE: Dict[int, List[Tuple[int, int]]] = {} + _SIDE_CACHE: dict[int, list[tuple[int, int]]] = {} @staticmethod - def _side_placements(num_rights: int) -> List[Tuple[int, int]]: - cached = CastlingGroup._SIDE_CACHE.get(num_rights) + def _side_placements(num_rights: int) -> list[tuple[int, int]]: + cached = _CastlingGroup._SIDE_CACHE.get(num_rights) if cached is not None: return cached - out: List[Tuple[int, int]] = [] + out: list[tuple[int, int]] = [] if num_rights: for k in range(8): if num_rights == 1: @@ -449,7 +438,7 @@ def _side_placements(num_rights: int) -> List[Tuple[int, int]]: for lo in range(k): for hi in range(k + 1, 8): out.append((k, 1 << lo | 1 << hi)) - CastlingGroup._SIDE_CACHE[num_rights] = out + _CastlingGroup._SIDE_CACHE[num_rights] = out return out def __init__(self, white_rights: int, black_rights: int): @@ -461,16 +450,16 @@ def __init__(self, white_rights: int, black_rights: int): self.table_size = max(len(w_side), 1) * self.b_span self.both_pinned = white_rights > 0 and black_rights > 0 # Per side: placement index by king file * ROOK_MASKS + rook mask, -1 if none. - self._inverse: List[List[int]] = [] + self._inverse: list[list[int]] = [] for placements in self.side: inv = [-1] * (8 * self.ROOK_MASKS) for i, (k, mask) in enumerate(placements): inv[k * self.ROOK_MASKS + mask] = i self._inverse.append(inv) - def placement(self, idx: int, color: chess.Color) -> Tuple[int, int]: + def placement(self, idx: int, color: chess.Color) -> tuple[int, int]: within = idx // self.b_span if color == chess.WHITE else idx % self.b_span - return self.side[side_index(color)][within] + return self.side[_side_index(color)][within] def index_of(self, w_king: int, w_rooks: int, b_king: int, b_rooks: int) -> int: """The placement of each side's king file and rook file mask, -1 if @@ -486,24 +475,24 @@ def index_of(self, w_king: int, w_rooks: int, b_king: int, b_rooks: int) -> int: # Geometry only, so all are built at import. -_KSM: Dict[int, KingSliceManager] = {sym: KingSliceManager(sym) for sym in (SYM_FILE_MIRROR, SYM_DIHEDRAL_8)} -_CASTLE_KSM: Dict[Tuple[int, int], CastlingKingSliceManager] = { - (w, b): CastlingKingSliceManager(w, b) - for w in range(CastlingGroup.MAX_RIGHTS + 1) - for b in range(CastlingGroup.MAX_RIGHTS + 1) +_KSM: dict[int, _KingSliceManager] = {sym: _KingSliceManager(sym) for sym in (_SYM_FILE_MIRROR, _SYM_DIHEDRAL_8)} +_CASTLE_KSM: dict[tuple[int, int], _CastlingKingSliceManager] = { + (w, b): _CastlingKingSliceManager(w, b) + for w in range(_CastlingGroup.MAX_RIGHTS + 1) + for b in range(_CastlingGroup.MAX_RIGHTS + 1) if w or b} # --- Pawn_Slice_Manager (src/egtb/pawn_slice_manager.cpp) --- -class PairGroup: +class _PairGroup: """Opposing pawn pair ('p'): white below black on one file, 15 rank pairs x 8 files = 120. The order and :meth:`canonical_pair` MUST match src/chess/pair_group.h: pawn slice ids are on disk.""" def __init__(self) -> None: - self.white: List[int] = [] - self.black: List[int] = [] - self._inv: Dict[Tuple[int, int], int] = {} + self.white: list[int] = [] + self.black: list[int] = [] + self._inv: dict[tuple[int, int], int] = {} for f in range(8): for wr in range(1, 6): # ranks 2..6 for br in range(wr + 1, 7): # ranks 3..7 @@ -525,7 +514,7 @@ def is_opposing_pair(w: int, b: int) -> bool: and chess.square_rank(w) < chess.square_rank(b)) @staticmethod - def canonical_pair(white: int, black: int) -> Optional[Tuple[int, int]]: + def canonical_pair(white: int, black: int) -> tuple[int, int] | None: """The opposing pair minimal by (file, white_rank, black_rank), or None: on the first file holding one, the lowest white pawn with a black one above it, and the lowest black pawn above that.""" @@ -538,13 +527,13 @@ def canonical_pair(white: int, black: int) -> Optional[Tuple[int, int]]: return None -class PawnSliceManager: - """Pawn slices for one pawn structure, shared via :func:`pawn_slice_mgr`.""" +class _PawnSliceManager: + """Pawn slices for one pawn structure, shared via :func:`_pawn_slice_mgr`.""" def __init__(self, has_pair: bool, white_pawns: int, black_pawns: int): - pair_group = PairGroup() if has_pair else None - white_group = PieceGroup(chess.PAWN, white_pawns) if white_pawns else None - black_group = PieceGroup(chess.PAWN, black_pawns) if black_pawns else None + pair_group = _PairGroup() if has_pair else None + white_group = _PieceGroup(chess.PAWN, white_pawns) if white_pawns else None + black_group = _PieceGroup(chess.PAWN, black_pawns) if black_pawns else None self.pair_group = pair_group self.white_group = white_group self.black_group = black_group @@ -556,12 +545,12 @@ def __init__(self, has_pair: bool, white_pawns: int, black_pawns: int): if pair_group is None: # Without a pair only overlaps are cut, so the slice is direct: # black's placement, then white's among the squares left free. - self.white_free_size = binom(chess.H7 - chess.A2 + 1 - black_pawns, white_pawns) + self.white_free_size = _binom(chess.H7 - chess.A2 + 1 - black_pawns, white_pawns) self.num_slices = self.black_table_size * self.white_free_size return n_cart = self.pair_table_size * self.white_table_size * self.black_table_size - def placements(g: Optional[PieceGroup]) -> List[int]: + def placements(g: _PieceGroup | None) -> list[int]: return [g.squares(i) for i in range(g.table_size)] if g else [0] white_placements = placements(white_group) @@ -584,12 +573,12 @@ def placements(g: Optional[PieceGroup]) -> List[int]: continue sq_bb = chess.BB_SQUARES[sq] bit = 1 << pair_idx - if PairGroup.canonical_pair(pw_bb | sq_bb, pb_bb) == (pw, pb): + if _PairGroup.canonical_pair(pw_bb | sq_bb, pb_bb) == (pw, pb): white_allowed[sq] |= bit - if PairGroup.canonical_pair(pw_bb, pb_bb | sq_bb) == (pw, pb): + if _PairGroup.canonical_pair(pw_bb, pb_bb | sq_bb) == (pw, pb): black_allowed[sq] |= bit - def allowed(boards: List[int], masks: List[int]) -> List[int]: + def allowed(boards: list[int], masks: list[int]) -> list[int]: out = [] for bb in boards: bits = all_pairs @@ -609,7 +598,7 @@ def allowed(boards: List[int], masks: List[int]) -> List[int]: for wsq in range(chess.A2, chess.H7 + 1): first = self.pair_table_size for bsq in chess.scan_forward(black): - if PairGroup.is_opposing_pair(wsq, bsq): + if _PairGroup.is_opposing_pair(wsq, bsq): first = min(first, pair_group.index_of(wsq, bsq)) before[wsq] = (1 << first) - 1 candidates = black_candidates[b_idx] @@ -656,11 +645,11 @@ def lookup(self, pair_w: int, pair_b: int, white: int, black: int) -> int: _FACT = [1, 1, 2, 6, 24, 120, 720, 5040, 40320] -def index_permutation_valid(n_classes: int, perm: int) -> bool: +def _index_permutation_valid(n_classes: int, perm: int) -> bool: return n_classes <= 8 and perm < _FACT[n_classes] -def storage_within_class_order(populated: List[int], perm: int) -> List[int]: +def _storage_within_class_order(populated: list[int], perm: int) -> list[int]: n = len(populated) available = list(populated) order = [] @@ -675,40 +664,40 @@ def storage_within_class_order(populated: List[int], perm: int) -> List[int]: # --- Position_Index_Config (src/probe/position_index.h) --- -class PositionIndexConfig: - def __init__(self, cfg: PieceConfig): +class _PositionIndexConfig: + def __init__(self, cfg: _PieceConfig): self.cfg = cfg - counts: Dict[Tuple[int, int], int] = {} + counts: dict[tuple[int, int], int] = {} for c, t in cfg.pieces: counts[(c, t)] = counts.get((c, t), 0) + 1 has_pawns = (counts.get((chess.WHITE, chess.PAWN), 0) > 0 or counts.get((chess.BLACK, chess.PAWN), 0) > 0 or cfg.has_pair) - self.ksm: Union[KingSliceManager, CastlingKingSliceManager] + self.ksm: _KingSliceManager | _CastlingKingSliceManager if cfg.has_castling: - self.sym = SYM_NONE + self.sym = _SYM_NONE w_rights, b_rights = cfg.castling_rights self.ksm = _CASTLE_KSM[(w_rights, b_rights)] else: - self.sym = SYM_FILE_MIRROR if has_pawns else SYM_DIHEDRAL_8 + self.sym = _SYM_FILE_MIRROR if has_pawns else _SYM_DIHEDRAL_8 self.ksm = _KSM[self.sym] - self.groups: Dict[int, PieceGroup] = {} + self.groups: dict[int, _PieceGroup] = {} for c in (chess.WHITE, chess.BLACK): for t in (chess.QUEEN, chess.ROOK, chess.BISHOP, chess.KNIGHT): # pawns: self.psm n = counts.get((c, t), 0) if n == 0: continue - pcl = make_piece_class(c, t) - self.groups[pcl] = PieceGroup(t, n) + pcl = _make_piece_class(c, t) + self.groups[pcl] = _PieceGroup(t, n) - self.psm = pawn_slice_mgr(cfg.has_pair, counts.get((chess.WHITE, chess.PAWN), 0), + self.psm = _pawn_slice_mgr(cfg.has_pair, counts.get((chess.WHITE, chess.PAWN), 0), counts.get((chess.BLACK, chess.PAWN), 0)) self.num_pawn_slices = self.psm.num_slices - self.populated: List[int] = [] - self.weights: Dict[int, int] = {} + self.populated: list[int] = [] + self.weights: dict[int, int] = {} w = 1 - for i in range(PIECE_CLASS_NB): + for i in range(_PIECE_CLASS_NB): if i not in self.groups: continue self.populated.append(i) @@ -719,23 +708,23 @@ def __init__(self, cfg: PieceConfig): self.pawn_slice_stride = self.num_king_slices * self.within_slice_size self.num_positions = self.num_pawn_slices * self.pawn_slice_stride - def make_layout(self, perm: int) -> Tuple[List[int], List[int]]: - order = storage_within_class_order(self.populated, perm) + def make_layout(self, perm: int) -> tuple[list[int], list[int]]: + order = _storage_within_class_order(self.populated, perm) radix = [self.groups[c].table_size for c in order] return order, radix - def board_index(self, board: chess.Board, order: List[int], radix: List[int]) -> Optional[int]: + def board_index(self, board: chess.Board, order: list[int], radix: list[int]) -> int | None: boards = {} for c in self.populated: - color, tt = class_to_piece(c) + color, tt = _class_to_piece(c) boards[c] = board.pieces_mask(tt, color) white_pawns = board.pieces_mask(chess.PAWN, chess.WHITE) black_pawns = board.pieces_mask(chess.PAWN, chess.BLACK) wk, bk = board.king(chess.WHITE), board.king(chess.BLACK) assert wk is not None and bk is not None # tablebase positions have both kings - if isinstance(self.ksm, CastlingKingSliceManager): - # Nothing folds under SYM_NONE: the right tells orientations apart. + if isinstance(self.ksm, _CastlingKingSliceManager): + # Nothing folds under _SYM_NONE: the right tells orientations apart. # A castling slice is keyed by the pinned rooks too, which ride in # it rather than in their rook class. castling_rooks = board.clean_castling_rights() @@ -753,9 +742,9 @@ def board_index(self, board: chess.Board, order: List[int], radix: List[int]) -> if ksid == -1: return None if t: - boards = {c: apply_transform(bb, t) for c, bb in boards.items()} - white_pawns = apply_transform(white_pawns, t) - black_pawns = apply_transform(black_pawns, t) + boards = {c: _apply_transform(bb, t) for c, bb in boards.items()} + white_pawns = _apply_transform(white_pawns, t) + black_pawns = _apply_transform(black_pawns, t) within_idx = {c: self.groups[c].index_of(boards[c]) for c in self.populated} if stabilizer: # Both kings on the diagonal: the a1-h8 mirror keeps their @@ -771,7 +760,7 @@ def board_index(self, board: chess.Board, order: List[int], radix: List[int]) -> if self.psm.has_pawns: pw = pb = -1 if self.cfg.has_pair: - pw, pb = PairGroup.canonical_pair(white_pawns, black_pawns) or (-1, -1) + pw, pb = _PairGroup.canonical_pair(white_pawns, black_pawns) or (-1, -1) white_pawns &= ~chess.BB_SQUARES[pw] black_pawns &= ~chess.BB_SQUARES[pb] pawn_slice = self.psm.lookup(pw, pb, white_pawns, black_pawns) @@ -784,12 +773,12 @@ def board_index(self, board: chess.Board, order: List[int], radix: List[int]) -> return outer + within -_PSM_CACHE: Dict[Tuple[bool, int, int], PawnSliceManager] = {} +_PSM_CACHE: dict[tuple[bool, int, int], _PawnSliceManager] = {} # Costly to build, so once per pawn structure, under the lock. _PSM_LOCK = threading.Lock() -def pawn_slice_mgr(has_pair: bool, white_pawns: int, black_pawns: int) -> PawnSliceManager: +def _pawn_slice_mgr(has_pair: bool, white_pawns: int, black_pawns: int) -> _PawnSliceManager: key = (has_pair, white_pawns, black_pawns) psm = _PSM_CACHE.get(key) if psm is not None: @@ -797,47 +786,47 @@ def pawn_slice_mgr(has_pair: bool, white_pawns: int, black_pawns: int) -> PawnSl with _PSM_LOCK: psm = _PSM_CACHE.get(key) if psm is None: - psm = PawnSliceManager(has_pair, white_pawns, black_pawns) + psm = _PawnSliceManager(has_pair, white_pawns, black_pawns) _PSM_CACHE[key] = psm return psm # --- On-disk framing (src/egtb/egtb_format.h, src/util/{memory,mono_uint_vec}.h) --- -WDL_MAGIC, DTZ_MAGIC, DTC_MAGIC, DTM_MAGIC, DTM50_MAGIC = ( +_WDL_MAGIC, _DTZ_MAGIC, _DTC_MAGIC, _DTM_MAGIC, _DTM50_MAGIC = ( 0x9bd1e3a6, 0x2ec8b161, 0x2ec8b17e, 0xab57c134, 0xab57c151) -SINGULAR_FLAG = 0x80 -DROPPED_FLAG = 0x40 -LOSS_ONLY_FLAG = 0x20 -RELAXED_FLAG = 0x10 -MAX_NON_CURSED_DTZ = 100 -DTM50_HMC_COUNT = 100 -DTM50_PACK_LAYERS = 101 +_SINGULAR_FLAG = 0x80 +_DROPPED_FLAG = 0x40 +_LOSS_ONLY_FLAG = 0x20 +_RELAXED_FLAG = 0x10 +_MAX_NON_CURSED_DTZ = 100 +_DTM50_HMC_COUNT = 100 +_DTM50_PACK_LAYERS = 101 # An 8-man winner has at most six pawns with five non-converting pushes each. # Budgets 0..29 are solved; the embedded DTZ row supplies budget 30 for clean W/L. -DTC_BUDGET_LAYERS = 30 -DTC_PACK_LAYERS = 31 -DRAWN_AT_LAYER = 0xFFFF +_DTC_BUDGET_LAYERS = 30 +_DTC_PACK_LAYERS = 31 +_DRAWN_AT_LAYER = 0xFFFF -def layered_bitmap_bytes(layers: int) -> int: +def _layered_bitmap_bytes(layers: int) -> int: """Bytes of a MULTI record's changepoint bitmap, in whole 32-bit words.""" return ((layers + 31) // 32) * 4 -DTM50_MULTI_BITMAP_BYTES = layered_bitmap_bytes(DTM50_PACK_LAYERS) -DTC_MULTI_BITMAP_BYTES = layered_bitmap_bytes(DTC_PACK_LAYERS) +_DTM50_MULTI_BITMAP_BYTES = _layered_bitmap_bytes(_DTM50_PACK_LAYERS) +_DTC_MULTI_BITMAP_BYTES = _layered_bitmap_bytes(_DTC_PACK_LAYERS) -IGNORE_50MR = -1 # sentinel (C++ uses ~0u) +_IGNORE_50MR = -1 # sentinel (C++ uses ~0u) -LOSE, BLESSED_LOSS, DRAW, CURSED_WIN, WIN, ILLEGAL = 0, 1, 2, 3, 4, 7 +_LOSE, _BLESSED_LOSS, _DRAW, _CURSED_WIN, _WIN, _ILLEGAL = 0, 1, 2, 3, 4, 7 -def wdl_from_storage(s: int) -> int: +def _wdl_from_storage(s: int) -> int: if s == 6: # BOUNDARY_WIN - return WIN + return _WIN if s == 5: # BOUNDARY_LOSS - return LOSE + return _LOSE return s @@ -906,7 +895,7 @@ def _compressed_block(chunk: Any) -> Any: return bytes(chunk) -class MonoUintVec: +class _MonoUintVec: """Block-sampled delta coder for a monotone uint64 sequence, addressed as `base` into the table's buffer rather than a slice of it.""" @@ -946,11 +935,11 @@ def get(self, i: int) -> int: delta = self._read_bits(self.delta_off, i * self.offset_width, self.offset_width) return base + delta - def get2(self, i: int) -> Tuple[int, int]: + def get2(self, i: int) -> tuple[int, int]: return (self.get(i), self.get(i + 1)) -class Min0UintVec: +class _Min0UintVec: def __init__(self, data: Any, base: int, size: int, width: int): self.data = data @@ -979,17 +968,17 @@ def get(self, i: int) -> int: # --- LZ4 block decompression --- -def lz4_decompress_block(src: memoryview, expected_size: int, dict_bytes: bytes = b"") -> bytes: +def _lz4_decompress_block(src: memoryview, expected_size: int, dict_bytes: bytes = b"") -> bytes: """Decompress an LZ4 *block* (not frame), `dict_bytes` logically preceding the output. Uses `python-lz4 `_ where - installed, else :func:`lz4_decompress_block_python`.""" + installed, else :func:`_lz4_decompress_block_python`.""" if _lz4_block is not None: return bytes(_lz4_block.decompress(src, uncompressed_size=expected_size, dict=dict_bytes or None)) - return lz4_decompress_block_python(src, expected_size, dict_bytes) + return _lz4_decompress_block_python(src, expected_size, dict_bytes) -def lz4_decompress_block_python(src: memoryview, expected_size: int, +def _lz4_decompress_block_python(src: memoryview, expected_size: int, dict_bytes: bytes = b"") -> bytes: out = bytearray(dict_bytes) base = len(dict_bytes) @@ -1033,7 +1022,7 @@ def lz4_decompress_block_python(src: memoryview, expected_size: int, #: Default soft budget in bytes for decoded blocks across all tables of a #: :class:`Tablebase`, beyond which least-recently-used blocks are evicted. -DEFAULT_BLOCK_CACHE_BYTES = 64 * 1024 * 1024 +_DEFAULT_BLOCK_CACHE_BYTES = 64 * 1024 * 1024 class _PerColor: @@ -1042,13 +1031,13 @@ class _PerColor: __slots__ = ("_blocks", "_block_locks", "_meta_lock") - _blocks: Dict[int, Any] + _blocks: dict[int, Any] def __init__(self) -> None: self._blocks = {} # Per block, not per color: lzma releases the GIL, so cold decodes of # different blocks run in parallel. - self._block_locks: Dict[int, threading.Lock] = {} + self._block_locks: dict[int, threading.Lock] = {} self._meta_lock = threading.Lock() def lock_for(self, block_id: int) -> threading.Lock: @@ -1070,7 +1059,7 @@ class _BlockCache: def __init__(self, max_bytes: int) -> None: self.max_bytes = max_bytes self.cur_bytes = 0 - self._lru: "collections.OrderedDict[Tuple[Any, int], int]" = collections.OrderedDict() + self._lru: collections.OrderedDict[tuple[Any, int], int] = collections.OrderedDict() self._lock = threading.Lock() def touch(self, pc: Any, block_id: int) -> None: @@ -1114,11 +1103,6 @@ def _drop(pc: _PerColor, block_id: int) -> None: pc._block_locks.pop(block_id, None) -#: A path, or whatever an overridden :meth:`_TableFile._open_source` accepts. -#: Interpolated into messages, so it wants a ``__str__``. -TableSource = Any - - class _TableFile: """Source lifecycle shared by the table kinds. Files are mapped, not read in: a probe touches a few blocks, and the page cache stays reclaimable.""" @@ -1126,19 +1110,19 @@ class _TableFile: EXT: str MAGIC: int KIND: str - PER_COLOR: Type[Any] + PER_COLOR: type[Any] cache: _BlockCache - per_color: List[Any] - path: TableSource + per_color: list[Any] + path: str - _data: Optional[Any] = None - _reader: Optional[_Serial] = None + _data: Any | None = None + _reader: _Serial | None = None - def __init__(self, cfg: PieceConfig, path: TableSource, - cache: Optional[_BlockCache] = None): + def __init__(self, cfg: _PieceConfig, path: str, + cache: _BlockCache | None = None): self.cfg = cfg - self.index_cfg = PositionIndexConfig(cfg) - self.cache = cache if cache is not None else _BlockCache(DEFAULT_BLOCK_CACHE_BYTES) + self.index_cfg = _PositionIndexConfig(cfg) + self.cache = cache if cache is not None else _BlockCache(_DEFAULT_BLOCK_CACHE_BYTES) self.is_singular = [False, False] self.is_dropped = [False, False] self.is_loss_only = [False, False] @@ -1146,7 +1130,7 @@ def __init__(self, cfg: PieceConfig, path: TableSource, self.per_color = [None, None] self._open(path) - def _open(self, path: TableSource) -> None: + def _open(self, path: str) -> None: self.path = path try: self._reader = _Serial(self._open_source(path)) @@ -1171,19 +1155,19 @@ def _parse(self, r: _Serial) -> None: flag = r.u8() pc = self.PER_COLOR() self.per_color[c] = pc - self.is_loss_only[c] = bool(flag & LOSS_ONLY_FLAG) - self.is_relaxed[c] = bool(flag & RELAXED_FLAG) - if flag & SINGULAR_FLAG: + self.is_loss_only[c] = bool(flag & _LOSS_ONLY_FLAG) + self.is_relaxed[c] = bool(flag & _RELAXED_FLAG) + if flag & _SINGULAR_FLAG: self.is_singular[c] = True if not self._on_singular(r, pc): raise ValueError(f"Invalid {self.KIND} singular value {self.path}") - elif flag & DROPPED_FLAG: + elif flag & _DROPPED_FLAG: self.is_dropped[c] = True else: self._parse_header(r, pc) if table_num == 1: # Symmetric material: BLACK is WHITE mirrored, flag byte and all. - w, b = side_index(chess.WHITE), side_index(chess.BLACK) + w, b = _side_index(chess.WHITE), _side_index(chess.BLACK) self.is_dropped[b] = True self.is_loss_only[b] = self.is_loss_only[w] self.is_relaxed[b] = self.is_relaxed[w] @@ -1216,7 +1200,7 @@ def _decode_block(self, pc: Any, block_id: int) -> Any: def _finalize(self, r: _Serial) -> None: raise NotImplementedError - def _open_source(self, path: TableSource) -> Any: + def _open_source(self, path: str) -> Any: """Open `path`, set ``self._data`` to what :meth:`close` releases, and return the buffer to read. Maps the file; an override for another transport may return anything with ``len()``, indexing and slicing. @@ -1256,37 +1240,37 @@ def close(self) -> None: class _WDLPerColor(_PerColor): __slots__ = ("order", "radix", "block_size", "tail_size", "block_cnt", - "data_size", "offsets", "buf", "data_off", "dict", "single_val") - order: List[int] - radix: List[int] + "data_size", "offsets", "buf", "data_off", "lz4_dict", "single_val") + order: list[int] + radix: list[int] block_size: int tail_size: int block_cnt: int data_size: int - offsets: MonoUintVec + offsets: _MonoUintVec buf: Any data_off: int - dict: bytes + lz4_dict: bytes single_val: int - _blocks: Dict[int, bytes] + _blocks: dict[int, bytes] def __init__(self) -> None: super().__init__() - self.single_val = DRAW - self.dict = b"" + self.single_val = _DRAW + self.lz4_dict = b"" -class WDLFile(_TableFile): +class _WDLFile(_TableFile): EXT = ".lzw" - MAGIC = WDL_MAGIC + MAGIC = _WDL_MAGIC KIND = "WDL" PER_COLOR = _WDLPerColor - per_color: List[Optional[_WDLPerColor]] + per_color: list[_WDLPerColor | None] def _parse_header(self, r: _Serial, pc: _WDLPerColor) -> None: perm = r.u32() n = len(self.index_cfg.populated) - if not index_permutation_valid(n, perm): + if not _index_permutation_valid(n, perm): raise ValueError("Invalid WDL index permutation") pc.order, pc.radix = self.index_cfg.make_layout(perm) pc.tail_size = r.u16() @@ -1302,7 +1286,7 @@ def _finalize(self, r: _Serial) -> None: assert pc is not None dict_size = r.u16() start = r.caret() - pc.dict = bytes(r.d[start:start + dict_size]) + pc.lz4_dict = bytes(r.d[start:start + dict_size]) r.advance(dict_size) for c in range(2): if self.is_singular[c] or self.is_dropped[c]: @@ -1314,10 +1298,10 @@ def _finalize(self, r: _Serial) -> None: offset_width = r.u8() r.advance(1) # usz_width mono_off = r.caret() - mono_bytes = MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, + mono_bytes = _MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, sample_width, offset_width) r.advance(mono_bytes) - pc.offsets = MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, + pc.offsets = _MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, sample_width, offset_width) for c in range(2): if self.is_singular[c] or self.is_dropped[c]: @@ -1334,9 +1318,9 @@ def _decode_block(self, pc: _WDLPerColor, block_id: int) -> bytes: dsz = dnext - doff out_sz = (pc.tail_size if (block_id == pc.block_cnt - 1 and pc.tail_size != 0) else pc.block_size) - blk = lz4_decompress_block( + blk = _lz4_decompress_block( _compressed_block(pc.buf[pc.data_off + doff:pc.data_off + doff + dsz]), - out_sz, pc.dict) + out_sz, pc.lz4_dict) pc._blocks[block_id] = blk self.cache.record(pc, block_id, len(blk)) return blk @@ -1382,36 +1366,32 @@ def _exists_case_exact(path: str) -> bool: # --- Probe helpers (src/probe/probe.cpp) --- -def mirror_for_canonical(board: chess.Board) -> chess.Board: +def _mirror_for_canonical(board: chess.Board) -> chess.Board: """Swap colors, rank-mirror the board and flip the side to move.""" out = board.copy(stack=False) out.apply_mirror() return out -_WDL_NAME = {LOSE: "LOSE", BLESSED_LOSS: "BLESSED_LOSS", DRAW: "DRAW", - CURSED_WIN: "CURSED_WIN", WIN: "WIN", ILLEGAL: "ILLEGAL"} - - # --- WDL helpers (src/egtb/egtb_entry.h) --- -def invert_wdl(w: int) -> int: - return {WIN: LOSE, CURSED_WIN: BLESSED_LOSS, DRAW: DRAW, - BLESSED_LOSS: CURSED_WIN, LOSE: WIN, ILLEGAL: ILLEGAL}[w] +def _invert_wdl(w: int) -> int: + return {_WIN: _LOSE, _CURSED_WIN: _BLESSED_LOSS, _DRAW: _DRAW, + _BLESSED_LOSS: _CURSED_WIN, _LOSE: _WIN, _ILLEGAL: _ILLEGAL}[w] -def invert_stored(s: int) -> int: - return {0: WIN, 1: CURSED_WIN, 2: DRAW, 3: BLESSED_LOSS, 4: LOSE, - 5: CURSED_WIN, # BOUNDARY_LOSS -> we win but only cursed - 6: BLESSED_LOSS, # BOUNDARY_WIN -> we lose but only blessed - 7: ILLEGAL}[s] +def _invert_stored(s: int) -> int: + return {0: _WIN, 1: _CURSED_WIN, 2: _DRAW, 3: _BLESSED_LOSS, 4: _LOSE, + 5: _CURSED_WIN, # BOUNDARY_LOSS -> we win but only cursed + 6: _BLESSED_LOSS, # BOUNDARY_WIN -> we lose but only blessed + 7: _ILLEGAL}[s] -def wdl_rank(w: int) -> int: - return {WIN: 4, CURSED_WIN: 3, DRAW: 2, BLESSED_LOSS: 1, LOSE: 0, ILLEGAL: -1}[w] +def _wdl_rank(w: int) -> int: + return {_WIN: 4, _CURSED_WIN: 3, _DRAW: 2, _BLESSED_LOSS: 1, _LOSE: 0, _ILLEGAL: -1}[w] -def stored_rank(s: int) -> int: +def _stored_rank(s: int) -> int: return {0: 0, # LOSE 5: 1, # BOUNDARY_LOSS 1: 2, # BLESSED_LOSS @@ -1422,36 +1402,36 @@ def stored_rank(s: int) -> int: 7: -1}[s] -def is_symmetric_material(cfg: PieceConfig) -> bool: +def _is_symmetric_material(cfg: _PieceConfig) -> bool: return cfg.base_key == cfg.mirr_key -def material_has_pawns(cfg: PieceConfig) -> bool: +def _material_has_pawns(cfg: _PieceConfig) -> bool: return cfg.has_pair or any(t == chess.PAWN for _c, t in cfg.pieces) -def is_win_class(w: int) -> bool: - return w == WIN or w == CURSED_WIN +def _is_win_class(w: int) -> bool: + return w == _WIN or w == _CURSED_WIN -def locate_frame(f: Any, cfg: PieceConfig, board: chess.Board, - wdl: int) -> Tuple[int, Optional[chess.Board], bool]: +def _locate_frame(f: Any, cfg: _PieceConfig, board: chess.Board, + wdl: int) -> tuple[int, chess.Board | None, bool]: """The frame holding a cell, the mirrored board to read it with (or None), and whether the cell is stored. A dropped frame is read through the mirror for self-mirror material; a loss-only frame stores no wins. Unstored cells are derived by one ply on the unmirrored board.""" - color = side_index(board.turn) + color = _side_index(board.turn) if not f.is_dropped[color]: - return color, None, not (f.is_loss_only[color] and is_win_class(wdl)) - if not is_symmetric_material(cfg): + return color, None, not (f.is_loss_only[color] and _is_win_class(wdl)) + if not _is_symmetric_material(cfg): return color, None, False - kept = side_index(not board.turn) - if f.is_loss_only[kept] and is_win_class(wdl): + kept = _side_index(not board.turn) + if f.is_loss_only[kept] and _is_win_class(wdl): return kept, None, False - return kept, mirror_for_canonical(board), True + return kept, _mirror_for_canonical(board), True -MAX_DERIVE_DEPTH = 64 +_MAX_DERIVE_DEPTH = 64 def _internal_board(board: chess.Board) -> chess.Board: @@ -1463,7 +1443,7 @@ def _internal_board(board: chess.Board) -> chess.Board: # --- LZMA blocks and stored values (src/egtb/egtb_entry.h) --- -def lzma_raw_decompress(block: memoryview, expected_size: int) -> bytes: +def _lzma_raw_decompress(block: memoryview, expected_size: int) -> bytes: if len(block) < 5: raise ValueError("LZMA block too small") props = bytes(block[-5:]) @@ -1490,26 +1470,26 @@ class _DTZValue(NamedTuple): rounded: bool -def dtz_value_from_storage(stored: int, w: int, entry_bytes: int) -> _DTZValue: - if w == DRAW: +def _dtz_value_from_storage(stored: int, w: int, entry_bytes: int) -> _DTZValue: + if w == _DRAW: return _DTZValue(0, False) - if entry_bytes == 1 and (w == CURSED_WIN or w == BLESSED_LOSS): + if entry_bytes == 1 and (w == _CURSED_WIN or w == _BLESSED_LOSS): return _DTZValue((stored << 1) - 1, True) return _DTZValue(stored, False) -def dtm_value_from_storage(stored: int, w: int) -> int: - if w in (WIN, CURSED_WIN): +def _dtm_value_from_storage(stored: int, w: int) -> int: + if w in (_WIN, _CURSED_WIN): return (stored << 1) | 1 - if w in (LOSE, BLESSED_LOSS): + if w in (_LOSE, _BLESSED_LOSS): return stored << 1 return 0 -def dtm50_value_from_storage(stored: int, w: int) -> int: - if w == WIN: +def _dtm50_value_from_storage(stored: int, w: int) -> int: + if w == _WIN: return (stored << 1) | 1 - if w == LOSE: + if w == _LOSE: return stored << 1 return 0 @@ -1520,19 +1500,19 @@ class _RankPerColor(_PerColor): __slots__ = ("order", "radix", "entry_bytes", "block_size", "tail_size", "block_cnt", "data_size", "offsets", "buf", "data_off", "rank_to_value", "single_val") - order: List[int] - radix: List[int] + order: list[int] + radix: list[int] entry_bytes: int block_size: int tail_size: int block_cnt: int data_size: int - offsets: MonoUintVec + offsets: _MonoUintVec buf: Any data_off: int - rank_to_value: List[int] + rank_to_value: list[int] single_val: int - _blocks: Dict[int, bytes] + _blocks: dict[int, bytes] def __init__(self) -> None: super().__init__() @@ -1544,7 +1524,7 @@ class _RankFile(_TableFile): in magic and value decode.""" PER_COLOR = _RankPerColor - per_color: List[Optional[_RankPerColor]] + per_color: list[_RankPerColor | None] def _parse_header(self, r: _Serial, pc: _RankPerColor) -> None: perm = r.u32() @@ -1568,9 +1548,9 @@ def _finalize(self, r: _Serial) -> None: offset_width = r.u8() r.advance(1) # usz_width mono_off = r.caret() - mb = MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, sample_width, offset_width) + mb = _MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, sample_width, offset_width) r.advance(mb) - pc.offsets = MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, + pc.offsets = _MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, sample_width, offset_width) for c in range(2): if self.is_singular[c] or self.is_dropped[c]: @@ -1587,14 +1567,14 @@ def _decode_block(self, pc: _RankPerColor, block_id: int) -> bytes: else pc.block_size) doff, dnext = pc.offsets.get2(block_id) dsz = dnext - doff - blk = b"" if dsz == 0 else lzma_raw_decompress( + blk = b"" if dsz == 0 else _lzma_raw_decompress( _compressed_block(pc.buf[pc.data_off + doff:pc.data_off + doff + dsz]), decode_sz) pc._blocks[block_id] = blk self.cache.record(pc, block_id, len(blk)) return blk - def _read_stored(self, color: int, board: chess.Board) -> Optional[Tuple[int, int]]: + def _read_stored(self, color: int, board: chess.Board) -> tuple[int, int] | None: """(stored, entry_bytes) of a cell, or None in a skip block.""" pc = self.per_color[color] assert pc is not None @@ -1616,25 +1596,25 @@ def _read_stored(self, color: int, board: chess.Board) -> Optional[Tuple[int, in return pc.rank_to_value[stored], pc.entry_bytes -class DTZFile(_RankFile): +class _DTZFile(_RankFile): EXT = ".lzdtz" - MAGIC = DTZ_MAGIC + MAGIC = _DTZ_MAGIC KIND = "DTZ" def read(self, color: int, board: chess.Board, wdl: int) -> _DTZValue: cell = self._read_stored(color, board) - return _DTZValue(0, False) if cell is None else dtz_value_from_storage(cell[0], wdl, cell[1]) + return _DTZValue(0, False) if cell is None else _dtz_value_from_storage(cell[0], wdl, cell[1]) -class DTMFile(_RankFile): +class _DTMFile(_RankFile): EXT = ".lzdtm" - MAGIC = DTM_MAGIC + MAGIC = _DTM_MAGIC KIND = "DTM" def read(self, color: int, board: chess.Board, wdl: int) -> int: cell = self._read_stored(color, board) # The class supplies the parity bit; unlike DTZ, no rounding. - return 0 if cell is None else dtm_value_from_storage(cell[0], wdl) + return 0 if cell is None else _dtm_value_from_storage(cell[0], wdl) # --- Changepoint packs (src/probe/layered_file.h, {dtm50,dtc}_file.cpp) --- @@ -1664,7 +1644,7 @@ def _bit(buf: bytes, i: int) -> int: for b in range(256)) -def _state_stride_index(state_bits: bytes, num_positions: int) -> Tuple[array.array[int], ...]: +def _state_stride_index(state_bits: bytes, num_positions: int) -> tuple[array.array[int], ...]: """``cum[s][k]``: positions in state `s` among the first ``k * _LAYERED_STRIDE``. The last entry may count padding; no read uses it.""" n_strides = _ceil_div(num_positions, _LAYERED_STRIDE) @@ -1683,8 +1663,8 @@ def _state_stride_index(state_bits: bytes, num_positions: int) -> Tuple[array.ar return tuple(out) -def _state_and_index(state_bits: bytes, cum: Tuple[array.array[int], ...], - pos: int) -> Tuple[int, int]: +def _state_and_index(state_bits: bytes, cum: tuple[array.array[int], ...], + pos: int) -> tuple[int, int]: sid, within = divmod(pos, _LAYERED_STRIDE) byte_in_stride, field = divmod(within, 4) base = sid * _STATE_STRIDE_BYTES @@ -1740,19 +1720,19 @@ class _LayeredPerColor(_PerColor): __slots__ = ("order", "radix", "entry_bytes", "block_positions", "tail_positions", "block_cnt", "data_size", "offsets", "usizes", "buf", "data_off", "rank_to_value") - order: List[int] - radix: List[int] + order: list[int] + radix: list[int] entry_bytes: int block_positions: int tail_positions: int block_cnt: int data_size: int - offsets: MonoUintVec - usizes: Min0UintVec + offsets: _MonoUintVec + usizes: _Min0UintVec buf: Any data_off: int - rank_to_value: List[int] - _blocks: Dict[int, Dict[str, Any]] + rank_to_value: list[int] + _blocks: dict[int, dict[str, Any]] def __init__(self) -> None: super().__init__() @@ -1766,7 +1746,7 @@ class _LayeredFile(_TableFile): """Changepoint container shared by DTM50 and DTC; ``read`` is per metric.""" PER_COLOR = _LayeredPerColor - per_color: List[Optional[_LayeredPerColor]] + per_color: list[_LayeredPerColor | None] def _on_singular(self, r: _Serial, pc: Any) -> bool: return r.u8() == 0 # the singular value must be DRAW @@ -1793,14 +1773,14 @@ def _finalize(self, r: _Serial) -> None: offset_width = r.u8() usz_width = r.u8() mono_off = r.caret() - mb = MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, sample_width, offset_width) + mb = _MonoUintVec.on_disk_bytes(pc.block_cnt + 1, log2_bu, sample_width, offset_width) r.advance(mb) usz_off = r.caret() - ub = Min0UintVec.on_disk_bytes(pc.block_cnt, usz_width) + ub = _Min0UintVec.on_disk_bytes(pc.block_cnt, usz_width) r.advance(ub) - pc.offsets = MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, + pc.offsets = _MonoUintVec(r.d, mono_off, pc.block_cnt + 1, log2_bu, sample_width, offset_width) - pc.usizes = Min0UintVec(r.d, usz_off, pc.block_cnt, usz_width) + pc.usizes = _Min0UintVec(r.d, usz_off, pc.block_cnt, usz_width) for c in range(2): if self.is_singular[c] or self.is_dropped[c]: continue @@ -1811,11 +1791,11 @@ def _finalize(self, r: _Serial) -> None: pc.buf, pc.data_off = r.d, start r.advance(pc.data_size) - def _decode_block(self, pc: _LayeredPerColor, block_id: int) -> Dict[str, Any]: + def _decode_block(self, pc: _LayeredPerColor, block_id: int) -> dict[str, Any]: doff, dnext = pc.offsets.get2(block_id) dsz = dnext - doff usz = pc.usizes.get(block_id) - payload = lzma_raw_decompress( + payload = _lzma_raw_decompress( _compressed_block(pc.buf[pc.data_off + doff:pc.data_off + doff + dsz]), usz) eb = pc.entry_bytes (num_positions, num_single, num_double, num_multi, @@ -1862,7 +1842,7 @@ def _read_rank(payload: bytes, off: int, eb: int) -> int: return payload[off] if eb == 1 else int(struct.unpack_from(" Optional[Tuple[Dict[str, Any], int, int]]: + ) -> tuple[dict[str, Any], int, int] | None: """A position's block, record state and index within that state, or ``None`` if nothing is stored (drawn at every layer).""" pc = self.per_color[color] @@ -1875,26 +1855,26 @@ def _locate(self, color: int, board: chess.Board lo, hi = pc.offsets.get2(block_id) if lo == hi: return None # skip block (uniform DRAW) - blk: Dict[str, Any] = self._get_block(pc, block_id) + blk: dict[str, Any] = self._get_block(pc, block_id) st, idx = _state_and_index(blk["state_bits"], blk["state_cum"], pos_in_block) return blk, st, idx -class DTM50File(_LayeredFile): +class _DTM50File(_LayeredFile): EXT = ".lzdtm50" - MAGIC = DTM50_MAGIC + MAGIC = _DTM50_MAGIC KIND = "DTM50" def read(self, color: int, board: chess.Board, wdl: int, - hmc: int) -> Tuple[int, int]: + hmc: int) -> tuple[int, int]: """The value at `hmc` and the layer where the cell turns DRAW. Only the draw-end hint means DRAW; a stored 0 is a mate.""" - flat = (hmc == IGNORE_50MR) - if not flat and (wdl == CURSED_WIN or wdl == BLESSED_LOSS): - return (DRAWN_AT_LAYER, 0) + flat = (hmc == _IGNORE_50MR) + if not flat and (wdl == _CURSED_WIN or wdl == _BLESSED_LOSS): + return (_DRAWN_AT_LAYER, 0) found = self._locate(color, board) if found is None: - return (DRAWN_AT_LAYER, 0) + return (_DRAWN_AT_LAYER, 0) blk, st, idx = found pc = self.per_color[color] assert pc is not None @@ -1917,7 +1897,7 @@ def read(self, color: int, board: chess.Board, wdl: int, if layer < h: stored = r2v[self._read_rank(payload, off + 1, eb)] elif draw_end: - return (DRAWN_AT_LAYER, draw_flip) + return (_DRAWN_AT_LAYER, draw_flip) else: stored = r2v[self._read_rank(payload, off + 1 + eb, eb)] elif st == 2: # DOUBLE: transitions at h1 < h2 @@ -1934,7 +1914,7 @@ def read(self, color: int, board: chess.Board, wdl: int, elif layer < h2: stored = r2v[self._read_rank(payload, off + 2 + eb, eb)] elif draw_end: - return (DRAWN_AT_LAYER, draw_flip) + return (_DRAWN_AT_LAYER, draw_flip) else: stored = r2v[self._read_rank(payload, off + 2 + 2 * eb, eb)] else: # MULTI: changepoint bitmap @@ -1943,26 +1923,26 @@ def read(self, color: int, board: chess.Board, wdl: int, kbyte = payload[entry] draw_end = (kbyte & 0x80) != 0 k = kbyte & 0x7F - bits = _multi_bitmap(payload, entry, DTM50_MULTI_BITMAP_BYTES) + bits = _multi_bitmap(payload, entry, _DTM50_MULTI_BITMAP_BYTES) rsel = bin(bits & ((1 << (layer + 1)) - 1)).count("1") - 1 if draw_end: draw_flip = max(bits.bit_length() - 1, 0) if rsel == k - 1 and draw_end: - return (DRAWN_AT_LAYER, draw_flip) + return (_DRAWN_AT_LAYER, draw_flip) stored = r2v[self._read_rank( - payload, entry + 1 + DTM50_MULTI_BITMAP_BYTES + rsel * eb, eb)] + payload, entry + 1 + _DTM50_MULTI_BITMAP_BYTES + rsel * eb, eb)] if flat: - return (dtm_value_from_storage(stored, wdl), draw_flip) - return (dtm50_value_from_storage(stored, wdl), draw_flip) + return (_dtm_value_from_storage(stored, wdl), draw_flip) + return (_dtm50_value_from_storage(stored, wdl), draw_flip) -def dtc_budget_plies(rule50: int) -> int: +def _dtc_budget_plies(rule50: int) -> int: """Plies a DTC answer may spend before a 50-move claim: 0 once the clock reaches it.""" - if rule50 == IGNORE_50MR: - return MAX_NON_CURSED_DTZ - return 0 if rule50 >= MAX_NON_CURSED_DTZ else MAX_NON_CURSED_DTZ - rule50 + if rule50 == _IGNORE_50MR: + return _MAX_NON_CURSED_DTZ + return 0 if rule50 >= _MAX_NON_CURSED_DTZ else _MAX_NON_CURSED_DTZ - rule50 class _DTCCell(NamedTuple): @@ -1971,13 +1951,13 @@ class _DTCCell(NamedTuple): one a cursed class has.""" order: int = 0 - value: int = DRAWN_AT_LAYER - dtz: int = DRAWN_AT_LAYER + value: int = _DRAWN_AT_LAYER + dtz: int = _DRAWN_AT_LAYER dtz_rounded: bool = False @property def priced(self) -> bool: - return self.value != DRAWN_AT_LAYER + return self.value != _DRAWN_AT_LAYER class _BudgetSegments(NamedTuple): @@ -1985,21 +1965,21 @@ class _BudgetSegments(NamedTuple): `segs` ascends in both row and value; `draw_start` is where a trailing DRAW segment begins.""" - segs: List[Tuple[int, int]] - draw_start: Optional[int] + segs: list[tuple[int, int]] + draw_start: int | None def end_of(self, i: int) -> int: if i + 1 < len(self.segs): return self.segs[i + 1][0] - return DTC_PACK_LAYERS if self.draw_start is None else self.draw_start + return _DTC_PACK_LAYERS if self.draw_start is None else self.draw_start -class DTCFile(_LayeredFile): +class _DTCFile(_LayeredFile): EXT = ".lzdtc" - MAGIC = DTC_MAGIC + MAGIC = _DTC_MAGIC KIND = "DTC" - def _segments(self, color: int, board: chess.Board) -> Optional[_BudgetSegments]: + def _segments(self, color: int, board: chess.Board) -> _BudgetSegments | None: found = self._locate(color, board) if found is None: return None @@ -2042,14 +2022,14 @@ def _segments(self, color: int, board: chess.Board) -> Optional[_BudgetSegments] kbyte = payload[entry] draw_end = (kbyte & 0x80) != 0 k = kbyte & 0x7F - bits = _multi_bitmap(payload, entry, DTC_MULTI_BITMAP_BYTES) + bits = _multi_bitmap(payload, entry, _DTC_MULTI_BITMAP_BYTES) rows = [] while bits: low = bits & -bits rows.append(low.bit_length() - 1) bits ^= low decisive = k - 1 if draw_end else k - ranks = entry + 1 + DTC_MULTI_BITMAP_BYTES + ranks = entry + 1 + _DTC_MULTI_BITMAP_BYTES segs = [(rows[n], r2v[rank(payload, ranks + n * eb, eb)]) for n in range(decisive)] return _BudgetSegments(segs, rows[k - 1] if draw_end else None) @@ -2063,139 +2043,139 @@ def read(self, color: int, board: chess.Board, wdl: int, return _DTCCell() dtz = seg.segs[0][1] - if wdl == CURSED_WIN or wdl == BLESSED_LOSS: + if wdl == _CURSED_WIN or wdl == _BLESSED_LOSS: return _DTCCell(dtz=dtz, dtz_rounded=bool(dtz & 1)) - budget_plies = dtc_budget_plies(rule50) + budget_plies = _dtc_budget_plies(rule50) for i in range(len(seg.segs) - 1, -1, -1): value = seg.segs[i][1] if value > budget_plies: continue - return _DTCCell(DTC_BUDGET_LAYERS - (seg.end_of(i) - 1), value, dtz) + return _DTCCell(_DTC_BUDGET_LAYERS - (seg.end_of(i) - 1), value, dtz) return _DTCCell(dtz=dtz) - def read_curve(self, color: int, board: chess.Board, wdl: int) -> List[int]: + def read_curve(self, color: int, board: chess.Board, wdl: int) -> list[int]: """The value at every budget rather than at one clock, with - ``DRAWN_AT_LAYER`` where a budget settles nothing (everywhere for a + ``_DRAWN_AT_LAYER`` where a budget settles nothing (everywhere for a cursed class). The last entry is the embedded DTZ endpoint.""" - curve = [DRAWN_AT_LAYER] * DTC_PACK_LAYERS - if wdl == CURSED_WIN or wdl == BLESSED_LOSS: + curve = [_DRAWN_AT_LAYER] * _DTC_PACK_LAYERS + if wdl == _CURSED_WIN or wdl == _BLESSED_LOSS: return curve seg = self._segments(color, board) if seg is None: return curve for i, (start, value) in enumerate(seg.segs): for row in range(start, seg.end_of(i)): - curve[DTC_BUDGET_LAYERS - row] = value + curve[_DTC_BUDGET_LAYERS - row] = value return curve # --- Probe orchestration (src/probe/probe.cpp) --- -def prefer_new(new_wdl: int, new_dtz: int, old_wdl: int, old_dtz: int) -> bool: - rn, ro = wdl_rank(new_wdl), wdl_rank(old_wdl) +def _prefer_new(new_wdl: int, new_dtz: int, old_wdl: int, old_dtz: int) -> bool: + rn, ro = _wdl_rank(new_wdl), _wdl_rank(old_wdl) if rn != ro: return rn > ro - if new_wdl in (WIN, CURSED_WIN): + if new_wdl in (_WIN, _CURSED_WIN): return new_dtz < old_dtz - if new_wdl in (LOSE, BLESSED_LOSS): + if new_wdl in (_LOSE, _BLESSED_LOSS): return new_dtz > old_dtz return False -def prefer_new_dtc(new_wdl: int, new_order: int, new_value: int, +def _prefer_new_dtc(new_wdl: int, new_order: int, new_value: int, old_wdl: int, old_order: int, old_value: int) -> bool: - rn, ro = wdl_rank(new_wdl), wdl_rank(old_wdl) + rn, ro = _wdl_rank(new_wdl), _wdl_rank(old_wdl) if rn != ro: return rn > ro - if new_wdl in (WIN, CURSED_WIN): + if new_wdl in (_WIN, _CURSED_WIN): return (new_order < old_order if new_order != old_order else new_value < old_value) - if new_wdl in (LOSE, BLESSED_LOSS): + if new_wdl in (_LOSE, _BLESSED_LOSS): return (new_order > old_order if new_order != old_order else new_value > old_value) return False -def offer_dtz(child_wdl: int, dtz: int, best_wdl: int, best_dtz: int) -> Tuple[int, int]: +def _offer_dtz(child_wdl: int, dtz: int, best_wdl: int, best_dtz: int) -> tuple[int, int]: """Offer a move to `child_wdl` at `dtz` to the mover's best; returns the new best. Past 100 plies a decisive class turns cursed.""" - my_wdl = invert_wdl(child_wdl) - if dtz > MAX_NON_CURSED_DTZ: - if my_wdl == WIN: - my_wdl = CURSED_WIN - elif my_wdl == LOSE: - my_wdl = BLESSED_LOSS - if prefer_new(my_wdl, dtz, best_wdl, best_dtz): + my_wdl = _invert_wdl(child_wdl) + if dtz > _MAX_NON_CURSED_DTZ: + if my_wdl == _WIN: + my_wdl = _CURSED_WIN + elif my_wdl == _LOSE: + my_wdl = _BLESSED_LOSS + if _prefer_new(my_wdl, dtz, best_wdl, best_dtz): return my_wdl, dtz return best_wdl, best_dtz -def below_pinned_class(pinned: int, offer: int) -> bool: +def _below_pinned_class(pinned: int, offer: int) -> bool: """Whether `offer` ranks below the class already known for the parent, so the child can't win the minimax and needn't be probed. ILLEGAL pins nothing.""" - return pinned != ILLEGAL and wdl_rank(offer) < wdl_rank(pinned) + return pinned != _ILLEGAL and _wdl_rank(offer) < _wdl_rank(pinned) -def child_class_is_forced(pinned: int) -> bool: +def _child_class_is_forced(pinned: int) -> bool: """Under a LOSE pin every child can be taken as WIN: exactly pinned, each is a clean WIN (else the parent would be BLESSED_LOSS); folded for DTM, WIN and CURSED_WIN minimax alike.""" - return pinned == LOSE + return pinned == _LOSE -def dtz_lift(my_wdl: int) -> int: +def _dtz_lift(my_wdl: int) -> int: """A DTZ minimax lifts a LOSE to BLESSED_LOSS past 100.""" - return BLESSED_LOSS if my_wdl == LOSE else my_wdl + return _BLESSED_LOSS if my_wdl == _LOSE else my_wdl -def fold_dtm_wdl(w: int) -> int: - if w == CURSED_WIN: - return WIN - if w == BLESSED_LOSS: - return LOSE +def _fold_dtm_wdl(w: int) -> int: + if w == _CURSED_WIN: + return _WIN + if w == _BLESSED_LOSS: + return _LOSE return w -def fold_50mr_wdl(w: int) -> int: +def _fold_50mr_wdl(w: int) -> int: """5-class WDL -> the three a clocked metric holds: cursed and blessed are draws under the 50-move rule.""" - if w == CURSED_WIN or w == BLESSED_LOSS: - return DRAW + if w == _CURSED_WIN or w == _BLESSED_LOSS: + return _DRAW return w -def dtz_from_draw_flip(h: int, wdl: int, board: chess.Board) -> Optional[int]: +def _dtz_from_draw_flip(h: int, wdl: int, board: chess.Board) -> int | None: """DTZ of a W/L cell from its DRAW flip layer `h` (layer = hmc + 1): still decisive at hmc = 100 - dtz, so h = 102 - dtz. h == 1 (drawn at a fresh clock) can't be determined; no flip means dtz <= 1, split by mate. DRAW and ILLEGAL give 0.""" - if wdl == DRAW or wdl == ILLEGAL: + if wdl == _DRAW or wdl == _ILLEGAL: return 0 - if wdl not in (WIN, LOSE): + if wdl not in (_WIN, _LOSE): return None if h == 0: - return 0 if (wdl == LOSE and board.is_checkmate()) else 1 + return 0 if (wdl == _LOSE and board.is_checkmate()) else 1 if h == 1: return None - return MAX_NON_CURSED_DTZ + 2 - h + return _MAX_NON_CURSED_DTZ + 2 - h # Layer bounds at `rule50`, W/L only (cursed and blessed are DRAW in every layer). # Pinned: rule50 + dtm <= 100, so the layer is the flat DTM (a mate on the 100th # ply beats the claim). Busted: rule50 + dtz > 100, so the layer is DRAW. # An unknown distance reads as 0: check has_dtm before trusting a pin. -def dtm50_layer_pinned_by_dtm(wdl: int, dtm: int, rule50: int) -> bool: - if wdl not in (WIN, LOSE): +def _dtm50_layer_pinned_by_dtm(wdl: int, dtm: int, rule50: int) -> bool: + if wdl not in (_WIN, _LOSE): return False - return rule50 + dtm <= MAX_NON_CURSED_DTZ + return rule50 + dtm <= _MAX_NON_CURSED_DTZ -def layer_busted_by_dtz(wdl: int, dtz: int, rule50: int) -> bool: - if wdl not in (WIN, LOSE): +def _layer_busted_by_dtz(wdl: int, dtz: int, rule50: int) -> bool: + if wdl not in (_WIN, _LOSE): return False - return rule50 + dtz > MAX_NON_CURSED_DTZ + return rule50 + dtz > _MAX_NON_CURSED_DTZ class _DTM50Result(NamedTuple): @@ -2218,20 +2198,20 @@ def __init__(self) -> None: self._any_unknown = False def of_class(self, my_wdl: int) -> None: - self._best_rank = max(self._best_rank, wdl_rank(my_wdl)) + self._best_rank = max(self._best_rank, _wdl_rank(my_wdl)) def of_dtz_class(self, my_wdl: int) -> None: - self.of_class(dtz_lift(my_wdl)) + self.of_class(_dtz_lift(my_wdl)) def unknown(self) -> None: self._any_unknown = True def unpin(self, best_wdl: int) -> bool: - return self._any_unknown or self._best_rank >= wdl_rank(best_wdl) + return self._any_unknown or self._best_rank >= _wdl_rank(best_wdl) def _is_cursed_exit(parent: chess.Board, child: chess.Board, child_wdl: int) -> bool: - return (child_wdl in (CURSED_WIN, BLESSED_LOSS) + return (child_wdl in (_CURSED_WIN, _BLESSED_LOSS) and chess.popcount(child.clean_castling_rights()) < chess.popcount(parent.clean_castling_rights())) @@ -2250,21 +2230,21 @@ class _DTZMinimax: __slots__ = ("_best_wdl", "_best_dtz", "_skipped") def __init__(self) -> None: - self._best_wdl = LOSE + self._best_wdl = _LOSE self._best_dtz = 0 self._skipped = _SkippedChildren() def zeroing_child(self, child_wdl: int) -> None: - self._best_wdl, self._best_dtz = offer_dtz( + self._best_wdl, self._best_dtz = _offer_dtz( child_wdl, 1, self._best_wdl, self._best_dtz) def quiet_child(self, child_wdl: int, child: _DTM50Result, cursed_exit: bool) -> None: if child.has_dtz: - self._best_wdl, self._best_dtz = offer_dtz( + self._best_wdl, self._best_dtz = _offer_dtz( child_wdl, _quiet_move_dtz(child.dtz, cursed_exit, False), self._best_wdl, self._best_dtz) else: - self._skipped.of_dtz_class(invert_wdl(child_wdl)) + self._skipped.of_dtz_class(_invert_wdl(child_wdl)) def unwalked(self) -> None: self._skipped.unknown() @@ -2275,7 +2255,7 @@ def finish(self, wdl: int, dtm: int, any_legal: bool) -> _DTM50Result: if self._skipped.unpin(self._best_wdl): return _DTM50Result(wdl, dtm) return _DTM50Result(wdl, dtm, True, - 0 if self._best_wdl == DRAW else self._best_dtz) + 0 if self._best_wdl == _DRAW else self._best_dtz) class _UnboundedFold: @@ -2285,7 +2265,7 @@ class _UnboundedFold: __slots__ = ("_winning", "_have", "_drawn", "_any_rounded", "_best") def __init__(self, mover_class: int) -> None: - self._winning = mover_class in (WIN, CURSED_WIN) + self._winning = mover_class in (_WIN, _CURSED_WIN) self._have = False self._drawn = False self._any_rounded = False @@ -2295,14 +2275,14 @@ def zeroing_child(self) -> None: self._offer(1) def quiet_child(self, child_dtz: int, cursed_exit: bool, child_rounded: bool) -> None: - if child_dtz == DRAWN_AT_LAYER: + if child_dtz == _DRAWN_AT_LAYER: self._drawn = True else: self._offer(_quiet_move_dtz(child_dtz, cursed_exit, child_rounded)) self._any_rounded |= child_rounded def value(self) -> int: - return self._best if (self._have and not self._drawn) else DRAWN_AT_LAYER + return self._best if (self._have and not self._drawn) else _DRAWN_AT_LAYER def rounded(self) -> bool: return self._any_rounded @@ -2315,23 +2295,22 @@ def _offer(self, v: int) -> None: def _ep_capture_moves( board: chess.Board, ep_square: int -) -> Tuple[chess.Board, List[chess.Move]]: +) -> tuple[chess.Board, list[chess.Move]]: bcopy = board.copy(stack=False) bcopy.ep_square = ep_square return bcopy, list(bcopy.generate_legal_ep()) -class ProbeResult: - """Outcome of :meth:`Tablebase.probe`. - - ``wdl`` is :data:`ILLEGAL` where the tables can't answer. ``wdl``, - ``wdl50``, ``dtc_wdl`` and ``dtm50_wdl`` are :data:`WIN`..:data:`LOSE` - codes; ``wdl`` ignores the clock, ``wdl50`` is the result at the probed - halfmove clock. ``dtz``/``dtc``/``dtm``/``dtm50`` are unsigned plies, - signed by the matching WDL class. ``dtc_order`` is the pushes the winner - still owes; ``dtc_wdl`` is the DTC result, a 50-move draw included. - ``dtz_rounded`` says ``dtz`` may be a ply off. Each ``has_*`` flag says - whether its field could be determined. +class _Result: + """A probe's outcome as the probing code works with it: ``wdl`` is + :data:`_ILLEGAL` where the tables can't answer. ``wdl``, ``wdl50``, + ``dtc_wdl`` and ``dtm50_wdl`` are :data:`_WIN`..:data:`_LOSE` codes; + ``wdl`` ignores the clock, ``wdl50`` is the result at the probed halfmove + clock. ``dtz``/``dtc``/``dtm``/``dtm50`` are unsigned plies, signed by the + matching WDL class. ``dtc_order`` is the pushes the winner still owes; + ``dtc_wdl`` is the DTC result, a 50-move draw included. ``dtz_rounded`` + says ``dtz`` may be a ply off. Each ``has_*`` flag says whether its field + could be determined. """ __slots__ = ("wdl", "has_dtz", "dtz", "dtz_rounded", "has_wdl50", "wdl50", @@ -2355,48 +2334,83 @@ class ProbeResult: dtm50: int def __init__(self) -> None: - self.wdl = ILLEGAL + self.wdl = _ILLEGAL self.has_dtz = False self.dtz = 0 self.dtz_rounded = False self.has_wdl50 = False - self.wdl50 = ILLEGAL + self.wdl50 = _ILLEGAL self.has_dtc = False - self.dtc_wdl = ILLEGAL + self.dtc_wdl = _ILLEGAL self.dtc_order = 0 self.dtc = 0 self.has_dtm = False self.dtm = 0 self.has_dtm50 = False - self.dtm50_wdl = ILLEGAL + self.dtm50_wdl = _ILLEGAL self.dtm50 = 0 - def __repr__(self) -> str: - s = f"" - - -def _fill_dtm50_from_bounds(r: ProbeResult, rule50: int) -> None: - if rule50 == IGNORE_50MR: + +@dataclasses.dataclass(frozen=True, slots=True) +class ProbeResult: + """ + Everything :meth:`Tablebase.probe` found out about a position, from the + point of view of the side to move. + + Values follow the ``probe_*`` methods. A field is ``None`` where it can't + be determined; if the tables can't answer at all, every field is. + """ + + wdl: int | None = None + """ + Win/draw/loss ignoring the 50-move rule, as :meth:`Tablebase.probe_wdl`: + ``2`` win, ``1`` win drawn by the 50-move rule (cursed win), ``0`` draw, + ``-1`` loss saved by the 50-move rule (blessed loss), ``-2`` loss. + """ + + wdl50: int | None = None + """The result at the probed halfmove clock: ``2``, ``0`` or ``-2``.""" + + dtz: int | None = None + """Distance to zeroing, as :meth:`Tablebase.probe_dtz`.""" + + dtz_rounded: bool = False + """Whether :attr:`dtz` may be one ply off.""" + + dtc: tuple[int, int] | None = None + """Distance to conversion at the probed clock, as :meth:`Tablebase.probe_dtc`.""" + + dtm: int | None = None + """Distance to mate ignoring the 50-move rule, as :meth:`Tablebase.probe_dtm`.""" + + dtm50: int | None = None + """Distance to mate at the probed clock, as :meth:`Tablebase.probe_dtm50`.""" + + +def _to_public(r: _Result) -> ProbeResult: + if r.wdl == _ILLEGAL: + return ProbeResult() + return ProbeResult( + wdl=_WDL_SIGNED[r.wdl], + wdl50=_WDL_SIGNED[r.wdl50] if r.has_wdl50 else None, + dtz=_signed(r.dtz, r.wdl) if r.has_dtz else None, + dtz_rounded=r.has_dtz and r.dtz_rounded, + dtc=(r.dtc_order, _signed(r.dtc, r.dtc_wdl)) if r.has_dtc else None, + dtm=_signed(r.dtm, r.wdl) if r.has_dtm else None, + dtm50=_signed(r.dtm50, r.dtm50_wdl) if r.has_dtm50 else None) + + +def _fill_dtm50_from_bounds(r: _Result, rule50: int) -> None: + if rule50 == _IGNORE_50MR: return - if rule50 >= DTM50_HMC_COUNT: - if r.wdl == LOSE and not r.has_dtm: + if rule50 >= _DTM50_HMC_COUNT: + if r.wdl == _LOSE and not r.has_dtm: return - r.dtm50_wdl = LOSE if (r.wdl == LOSE and r.dtm == 0) else DRAW - elif (fold_50mr_wdl(r.wdl) == DRAW - or (r.has_dtz and layer_busted_by_dtz(r.wdl, r.dtz, rule50))): - r.dtm50_wdl = DRAW - elif r.has_dtm and dtm50_layer_pinned_by_dtm(r.wdl, r.dtm, rule50): + r.dtm50_wdl = _LOSE if (r.wdl == _LOSE and r.dtm == 0) else _DRAW + elif (_fold_50mr_wdl(r.wdl) == _DRAW + or (r.has_dtz and _layer_busted_by_dtz(r.wdl, r.dtz, rule50))): + r.dtm50_wdl = _DRAW + elif r.has_dtm and _dtm50_layer_pinned_by_dtm(r.wdl, r.dtm, rule50): r.dtm50_wdl = r.wdl r.dtm50 = r.dtm else: @@ -2404,31 +2418,31 @@ def _fill_dtm50_from_bounds(r: ProbeResult, rule50: int) -> None: r.has_dtm50 = True -def _fill_dtc_from_bounds(r: ProbeResult, has_pawns: bool, rule50: int) -> None: - if rule50 == IGNORE_50MR: +def _fill_dtc_from_bounds(r: _Result, has_pawns: bool, rule50: int) -> None: + if rule50 == _IGNORE_50MR: return - if r.wdl not in (WIN, LOSE): + if r.wdl not in (_WIN, _LOSE): r.has_dtc = True - r.dtc_wdl = DRAW + r.dtc_wdl = _DRAW return if not r.has_dtz: return - busted = r.dtz > dtc_budget_plies(rule50) + busted = r.dtz > _dtc_budget_plies(rule50) if has_pawns and not busted: return r.has_dtc = True - r.dtc_wdl = DRAW if busted else r.wdl + r.dtc_wdl = _DRAW if busted else r.wdl r.dtc = 0 if busted else r.dtz -def _fill_wdl50(r: ProbeResult, rule50: int) -> None: - if rule50 == IGNORE_50MR or r.wdl == ILLEGAL: +def _fill_wdl50(r: _Result, rule50: int) -> None: + if rule50 == _IGNORE_50MR or r.wdl == _ILLEGAL: return - if fold_50mr_wdl(r.wdl) == DRAW: - r.wdl50 = DRAW + if _fold_50mr_wdl(r.wdl) == _DRAW: + r.wdl50 = _DRAW elif r.has_dtz: - r.wdl50 = DRAW if layer_busted_by_dtz(r.wdl, r.dtz, rule50) else r.wdl + r.wdl50 = _DRAW if _layer_busted_by_dtz(r.wdl, r.dtz, rule50) else r.wdl else: return r.has_wdl50 = True @@ -2438,13 +2452,13 @@ class MissingTableError(KeyError): """Raised when the tables a probe needs are not available.""" -_WDL_SIGNED = {WIN: 2, CURSED_WIN: 1, DRAW: 0, BLESSED_LOSS: -1, LOSE: -2} +_WDL_SIGNED = {_WIN: 2, _CURSED_WIN: 1, _DRAW: 0, _BLESSED_LOSS: -1, _LOSE: -2} def _signed(magnitude: int, wdl: int) -> int: - if wdl in (WIN, CURSED_WIN): + if wdl in (_WIN, _CURSED_WIN): return magnitude - if wdl in (LOSE, BLESSED_LOSS): + if wdl in (_LOSE, _BLESSED_LOSS): return -magnitude return 0 @@ -2452,85 +2466,89 @@ def _signed(magnitude: int, wdl: int) -> int: # --- Tablebase --- class Tablebase: - """Probes a directory tree of chesstb tables. Use :func:`open_tablebase`. + """ + Manages a collection of tablebase files for probing. - *directory* may hold ``wdl/``, ``dtz/``, ``dtc/``, ``dtm/`` and ``dtm50/`` - subdirectories or the table files directly. Share one instance between - all probing threads. + Probing is thread-safe: share one instance between all threads. + + :param block_cache_bytes: Bound of the cache of decompressed blocks + shared by all tables. """ - #: Table classes opened per kind. A transport sets its own subclasses - #: here and overrides :meth:`_find`. - WDL_FILE: Type[WDLFile] = WDLFile - DTZ_FILE: Type[DTZFile] = DTZFile - DTC_FILE: Type[DTCFile] = DTCFile - DTM_FILE: Type[DTMFile] = DTMFile - DTM50_FILE: Type[DTM50File] = DTM50File + # Table classes opened per kind; a subclass may replace them, together + # with _find(), to read tables from elsewhere. + _WDL_FILE: type[_WDLFile] = _WDLFile + _DTZ_FILE: type[_DTZFile] = _DTZFile + _DTC_FILE: type[_DTCFile] = _DTCFile + _DTM_FILE: type[_DTMFile] = _DTMFile + _DTM50_FILE: type[_DTM50File] = _DTM50File - KINDS = ("wdl", "dtz", "dtc", "dtm", "dtm50") + _KINDS = ("wdl", "dtz", "dtc", "dtm", "dtm50") - def __init__(self, directory: str, *, block_cache_bytes: int = DEFAULT_BLOCK_CACHE_BYTES): - self.dirs: Dict[str, List[str]] = {kind: [] for kind in self.KINDS} + def __init__(self, *, block_cache_bytes: int = _DEFAULT_BLOCK_CACHE_BYTES) -> None: + self._dirs: dict[str, list[str]] = {kind: [] for kind in self._KINDS} # Per kind: the open tables, ``None`` for "looked, no such table". - self._caches: Dict[str, Dict[CacheKey, Any]] = {kind: {} for kind in self.KINDS} - # Per kind, guarding its cache and ``dirs`` entry. Held only across a - # first open, never a probe; taken in KINDS order. - self._open_locks: Dict[str, threading.Lock] = { - kind: threading.Lock() for kind in self.KINDS} + self._caches: dict[str, dict[_CacheKey, Any]] = {kind: {} for kind in self._KINDS} + # Per kind, guarding its cache and ``_dirs`` entry. Held only across a + # first open, never a probe; taken in _KINDS order. + self._open_locks: dict[str, threading.Lock] = { + kind: threading.Lock() for kind in self._KINDS} self._read_condition = threading.Condition() self._read_count = 0 # (men, rights, pair) -> (config, mirrored): see :meth:`_canonical_root`. - self._roots: Dict[Tuple[Tuple[int, ...], int, int, bool], Tuple[PieceConfig, bool]] = {} + self._roots: dict[tuple[tuple[int, ...], int, int, bool], tuple[_PieceConfig, bool]] = {} self._block_cache = _BlockCache(block_cache_bytes) - self.add_directory(directory) - def add_directory(self, directory: str) -> None: - """Adds a search directory. Each kind searches its subdirectory - (``wdl/``, ``dtz/``, …) if present, else *directory* itself. - Duplicates are ignored. + def add_directory(self, directory: _StrPath) -> None: + """ + Adds tables from a directory: from its ``wdl``, ``dtz``, ``dtc``, + ``dtm`` and ``dtm50`` subdirectories where present, otherwise from + *directory* itself. Adding a directory twice has no effect. - Safe to call while other threads probe, but materials already looked - up are not looked up again. + May be called while other threads probe, but a material already + probed keeps the tables it was found with. """ - for kind in self.KINDS: + directory = os.fspath(directory) + for kind in self._KINDS: sub = os.path.join(directory, kind) d = sub if os.path.isdir(sub) else directory with self._open_locks[kind]: key = os.path.normpath(d) - if all(os.path.normpath(e) != key for e in self.dirs[kind]): - self.dirs[kind].append(d) + if all(os.path.normpath(e) != key for e in self._dirs[kind]): + self._dirs[kind].append(d) def close(self) -> None: - """Closes all tables and drops cached blocks, after waiting for - probes in progress on other threads. Later probes reopen what they - need, so a continuous stream of probes can keep this waiting. + """ + Closes all tables and frees the block cache, after waiting for + probes in progress on other threads. Probes after closing reopen + the tables they need. """ with self._read_condition: while self._read_count > 0: self._read_condition.wait() self._block_cache.clear() self._roots.clear() - for kind in self.KINDS: + for kind in self._KINDS: with self._open_locks[kind]: self._close_all(self._caches[kind]) @staticmethod - def _close_all(cache: Dict[CacheKey, Optional[_TableFile]]) -> None: + def _close_all(cache: dict[_CacheKey, _TableFile | None]) -> None: while cache: _, table = cache.popitem() if table is not None: table.close() - def __enter__(self) -> "Tablebase": + def __enter__(self) -> Tablebase: return self - def __exit__(self, *exc: Any) -> None: + def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None: self.close() # --- table file resolution / caching --- - def _find(self, kind: str, name: str, ext: str) -> Optional[TableSource]: + def _find(self, kind: str, name: str, ext: str) -> str | None: """A source :meth:`_TableFile._open_source` opens, or ``None``.""" - for d in self.dirs[kind]: + for d in self._dirs[kind]: p = os.path.join(d, name + ext) if _exists_case_exact(p): return p @@ -2538,7 +2556,7 @@ def _find(self, kind: str, name: str, ext: str) -> Optional[TableSource]: # A cached None means "no such table", hence subscripting, not .get(). # Only a first open takes the lock, re-checking inside. - def _open(self, kind: str, cfg: PieceConfig) -> Any: + def _open(self, kind: str, cfg: _PieceConfig) -> Any: cache = self._caches[kind] k = cfg.cache_key try: @@ -2550,35 +2568,35 @@ def _open(self, kind: str, cfg: PieceConfig) -> Any: return cache[k] except KeyError: pass - cls = getattr(self, kind.upper() + "_FILE") + cls = getattr(self, "_" + kind.upper() + "_FILE") p = self._find(kind, cfg.name(), cls.EXT) table = cls(cfg, p, self._block_cache) if p is not None else None cache[k] = table return table - def _table_open_lock(self, kind: str, cache_key: CacheKey) -> Any: - """Lock for a table's first open; per kind, also guarding ``dirs``. + def _table_open_lock(self, kind: str, cache_key: _CacheKey) -> Any: + """Lock for a table's first open; per kind, also guarding ``_dirs``. A transport may narrow it per table.""" return self._open_locks[kind] - def _open_wdl(self, cfg: PieceConfig) -> Optional[WDLFile]: + def _open_wdl(self, cfg: _PieceConfig) -> _WDLFile | None: return self._open("wdl", cfg) # type: ignore[no-any-return] - def _open_dtz(self, cfg: PieceConfig) -> Optional[DTZFile]: + def _open_dtz(self, cfg: _PieceConfig) -> _DTZFile | None: return self._open("dtz", cfg) # type: ignore[no-any-return] - def _open_dtm(self, cfg: PieceConfig) -> Optional[DTMFile]: + def _open_dtm(self, cfg: _PieceConfig) -> _DTMFile | None: return self._open("dtm", cfg) # type: ignore[no-any-return] - def _open_dtc(self, cfg: PieceConfig) -> Optional[DTCFile]: + def _open_dtc(self, cfg: _PieceConfig) -> _DTCFile | None: return self._open("dtc", cfg) # type: ignore[no-any-return] - def _open_dtm50(self, cfg: PieceConfig) -> Optional[DTM50File]: + def _open_dtm50(self, cfg: _PieceConfig) -> _DTM50File | None: return self._open("dtm50", cfg) # type: ignore[no-any-return] # --- child construction for the derive / overlay paths --- def _make_child(self, parent: chess.Board, move: chess.Move - ) -> Tuple[PieceConfig, chess.Board, Optional[int], bool]: + ) -> tuple[_PieceConfig, chess.Board, int | None, bool]: zeroing = parent.is_zeroing(move) child = parent.copy(stack=False) child.push(move) # also sets child.ep_square on a double push @@ -2590,104 +2608,104 @@ def _make_child(self, parent: chess.Board, move: chess.Move def _relax_bound_wdl(self, board: chess.Board, depth: int) -> int: """Best class a capture or promotion reaches. Those children are in sub-tables, so this never re-enters the frame being resolved.""" - if depth >= MAX_DERIVE_DEPTH: - return ILLEGAL + if depth >= _MAX_DERIVE_DEPTH: + return _ILLEGAL b = _internal_board(board) - best = LOSE + best = _LOSE promo_rank = chess.BB_RANK_8 if b.turn == chess.WHITE else chess.BB_RANK_1 for m in b.generate_legal_moves(to_mask=b.occupied_co[not b.turn] | promo_rank): if m.promotion is None and not b.is_capture(m): continue cfg_c, cboard, cep, _zeroing = self._make_child(b, m) - cw = DRAW if cfg_c.is_bare_kings else self._probe_wdl_impl( + cw = _DRAW if cfg_c.is_bare_kings else self._probe_wdl_impl( cfg_c, cboard, cep, depth + 1) - if cw == ILLEGAL: - best = ILLEGAL + if cw == _ILLEGAL: + best = _ILLEGAL continue - mine = invert_wdl(cw) - if mine == WIN: - return WIN - if best != ILLEGAL and wdl_rank(mine) > wdl_rank(best): + mine = _invert_wdl(cw) + if mine == _WIN: + return _WIN + if best != _ILLEGAL and _wdl_rank(mine) > _wdl_rank(best): best = mine return best - def _raise_by_bound(self, w: WDLFile, frame: int, stored: int, + def _raise_by_bound(self, w: _WDLFile, frame: int, stored: int, board: chess.Board, depth: int) -> int: """A relaxed frame stores no better than the truth, and worse only where :meth:`_relax_bound_wdl` reaches it.""" - if not w.is_relaxed[frame] or stored == ILLEGAL or stored == WIN: + if not w.is_relaxed[frame] or stored == _ILLEGAL or stored == _WIN: return stored bound = self._relax_bound_wdl(board, depth) - if bound == ILLEGAL: - return ILLEGAL - return bound if wdl_rank(bound) > wdl_rank(stored) else stored + if bound == _ILLEGAL: + return _ILLEGAL + return bound if _wdl_rank(bound) > _wdl_rank(stored) else stored - def _read_wdl_stored(self, w: Optional[WDLFile], board: chess.Board, + def _read_wdl_stored(self, w: _WDLFile | None, board: chess.Board, depth: int) -> int: if w is None: return 7 # WDL_Stored::ILLEGAL - color = side_index(board.turn) + color = _side_index(board.turn) s = w.read(color, board) - if not w.is_relaxed[color] or s == 7 or s == WIN: + if not w.is_relaxed[color] or s == 7 or s == _WIN: return s bound = self._relax_bound_wdl(board, depth) - if bound == ILLEGAL: + if bound == _ILLEGAL: return 7 # WDL_Stored::ILLEGAL - return bound if stored_rank(bound) > stored_rank(s) else s + return bound if _stored_rank(bound) > _stored_rank(s) else s - def _probe_wdl_internal(self, w: Optional[WDLFile], cfg: PieceConfig, + def _probe_wdl_internal(self, w: _WDLFile | None, cfg: _PieceConfig, board: chess.Board, depth: int) -> int: if w is None: - return ILLEGAL - color = side_index(board.turn) + return _ILLEGAL + color = _side_index(board.turn) if w.is_dropped[color]: - if not is_symmetric_material(cfg): + if not _is_symmetric_material(cfg): return self._derive_wdl(board, depth) - mp = mirror_for_canonical(board) - mc = side_index(mp.turn) - return self._raise_by_bound(w, mc, wdl_from_storage(w.read(mc, mp)), + mp = _mirror_for_canonical(board) + mc = _side_index(mp.turn) + return self._raise_by_bound(w, mc, _wdl_from_storage(w.read(mc, mp)), board, depth) - return self._raise_by_bound(w, color, wdl_from_storage(w.read(color, board)), + return self._raise_by_bound(w, color, _wdl_from_storage(w.read(color, board)), board, depth) def _derive_wdl(self, board: chess.Board, depth: int) -> int: - if depth >= MAX_DERIVE_DEPTH: - return ILLEGAL + if depth >= _MAX_DERIVE_DEPTH: + return _ILLEGAL b = _internal_board(board) any_legal = False - best = LOSE + best = _LOSE skipped = _SkippedChildren() for m in b.legal_moves: any_legal = True cfg_c, cboard, cep, zeroing = self._make_child(b, m) if cfg_c.is_bare_kings: - mw = DRAW + mw = _DRAW elif zeroing: cw = self._probe_wdl_impl(cfg_c, cboard, cep, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - mw = invert_wdl(cw) + mw = _invert_wdl(cw) else: cs = self._read_wdl_stored(self._open_wdl(cfg_c), cboard, depth + 1) if cs == 7: skipped.unknown() continue - mw = invert_stored(cs) - if wdl_rank(mw) > wdl_rank(best): + mw = _invert_stored(cs) + if _wdl_rank(mw) > _wdl_rank(best): best = mw - if best == WIN: + if best == _WIN: return best if not any_legal: - return LOSE if b.is_check() else DRAW + return _LOSE if b.is_check() else _DRAW if skipped.unpin(best): - return ILLEGAL + return _ILLEGAL return best - def _probe_wdl_impl(self, cfg: PieceConfig, board: chess.Board, - ep_square: Optional[int], depth: int) -> int: + def _probe_wdl_impl(self, cfg: _PieceConfig, board: chess.Board, + ep_square: int | None, depth: int) -> int: best = self._probe_wdl_internal(self._open_wdl(cfg), cfg, board, depth) - if best == ILLEGAL or best == WIN or ep_square is None: + if best == _ILLEGAL or best == _WIN or ep_square is None: return best bcopy, eps = _ep_capture_moves(board, ep_square) if not eps: @@ -2697,122 +2715,122 @@ def _probe_wdl_impl(self, cfg: PieceConfig, board: chess.Board, unresolved_ep = False for m in eps: cfg_c, cboard, _cep, _ = self._make_child(bcopy, m) - cw = DRAW if cfg_c.is_bare_kings else self._probe_wdl_internal( + cw = _DRAW if cfg_c.is_bare_kings else self._probe_wdl_internal( self._open_wdl(cfg_c), cfg_c, cboard, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: unresolved_ep = True continue - mine = invert_wdl(cw) + mine = _invert_wdl(cw) if ((not has_non_ep_move and not any_ep) - or wdl_rank(mine) > wdl_rank(best)): + or _wdl_rank(mine) > _wdl_rank(best)): best = mine any_ep = True - if best == WIN: + if best == _WIN: break - if unresolved_ep and best != WIN: - return ILLEGAL + if unresolved_ep and best != _WIN: + return _ILLEGAL return best # --- DTZ --- - def _probe_dtz_internal(self, d: Optional[DTZFile], cfg: PieceConfig, - board: chess.Board, wdl: int, depth: int) -> Optional[_DTZValue]: + def _probe_dtz_internal(self, d: _DTZFile | None, cfg: _PieceConfig, + board: chess.Board, wdl: int, depth: int) -> _DTZValue | None: if d is None: return None - color, mp, readable = locate_frame(d, cfg, board, wdl) + color, mp, readable = _locate_frame(d, cfg, board, wdl) if not readable: return self._derive_dtz(board, wdl, depth) - if d.is_relaxed[color] and is_win_class(wdl): + if d.is_relaxed[color] and _is_win_class(wdl): derived = self._derive_dtz(board, wdl, depth, True) if derived is None or derived.dtz == 1: return derived return d.read(color, board if mp is None else mp, wdl) def _derive_dtz(self, board: chess.Board, wdl: int, depth: int, - zeroing_only: bool = False) -> Optional[_DTZValue]: - if depth >= MAX_DERIVE_DEPTH: + zeroing_only: bool = False) -> _DTZValue | None: + if depth >= _MAX_DERIVE_DEPTH: return None b = _internal_board(board) any_legal = False - best_wdl, best_dtz = LOSE, 0 + best_wdl, best_dtz = _LOSE, 0 rounded = False skipped = _SkippedChildren() for m in b.legal_moves: any_legal = True cfg_c, cboard, cep, zeroing = self._make_child(b, m) if cfg_c.is_bare_kings: - cw, my_dtz = DRAW, 1 + cw, my_dtz = _DRAW, 1 elif zeroing: - if child_class_is_forced(wdl): - cw = WIN + if _child_class_is_forced(wdl): + cw = _WIN else: cw = self._probe_wdl_impl(cfg_c, cboard, cep, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue my_dtz = 1 else: if zeroing_only: continue - if child_class_is_forced(wdl): - cw = WIN + if _child_class_is_forced(wdl): + cw = _WIN else: cw = self._probe_wdl_internal(self._open_wdl(cfg_c), cfg_c, cboard, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - if below_pinned_class(wdl, dtz_lift(invert_wdl(cw))): + if _below_pinned_class(wdl, _dtz_lift(_invert_wdl(cw))): continue child_dtz = self._probe_dtz_internal(self._open_dtz(cfg_c), cfg_c, cboard, cw, depth + 1) if child_dtz is None: - skipped.of_dtz_class(invert_wdl(cw)) + skipped.of_dtz_class(_invert_wdl(cw)) continue my_dtz = _quiet_move_dtz(child_dtz.dtz, _is_cursed_exit(b, cboard, cw), child_dtz.rounded) rounded |= child_dtz.rounded - best_wdl, best_dtz = offer_dtz(cw, my_dtz, best_wdl, best_dtz) - if wdl in (WIN, CURSED_WIN) and best_wdl == wdl and best_dtz == 1: + best_wdl, best_dtz = _offer_dtz(cw, my_dtz, best_wdl, best_dtz) + if wdl in (_WIN, _CURSED_WIN) and best_wdl == wdl and best_dtz == 1: return _DTZValue(best_dtz, False) if not any_legal: return _DTZValue(0, False) if skipped.unpin(best_wdl): return None - if zeroing_only or best_wdl == DRAW: + if zeroing_only or best_wdl == _DRAW: return _DTZValue(0, False) return _DTZValue(best_dtz, rounded) # --- DTC (whose unbounded row answers DTZ too) --- - def _probe_dtc_internal(self, c: Optional[DTCFile], cfg: PieceConfig, + def _probe_dtc_internal(self, c: _DTCFile | None, cfg: _PieceConfig, board: chess.Board, wdl: int, rule50: int, - depth: int) -> Optional[_DTCCell]: + depth: int) -> _DTCCell | None: if c is None: return None - color, mp, readable = locate_frame(c, cfg, board, wdl) + color, mp, readable = _locate_frame(c, cfg, board, wdl) if not readable: return self._derive_dtc(board, wdl, rule50, depth) return c.read(color, board if mp is None else mp, wdl, rule50) - def _read_dtc_curve(self, c: Optional[DTCFile], cfg: PieceConfig, - board: chess.Board, wdl: int) -> Optional[List[int]]: + def _read_dtc_curve(self, c: _DTCFile | None, cfg: _PieceConfig, + board: chess.Board, wdl: int) -> list[int] | None: """The whole stored record of *board*, for a derive to minimax over, or ``None`` if its frame is not stored.""" if c is None: return None - color, mp, readable = locate_frame(c, cfg, board, wdl) + color, mp, readable = _locate_frame(c, cfg, board, wdl) if not readable: return None return c.read_curve(color, board if mp is None else mp, wdl) @staticmethod - def _dtc_move_kind(board: chess.Board, move: chess.Move) -> Tuple[bool, bool]: + def _dtc_move_kind(board: chess.Board, move: chess.Move) -> tuple[bool, bool]: """(conversion, push): a capture or promotion converts; any other pawn move is a push.""" conversion = move.promotion is not None or board.is_capture(move) push = not conversion and board.piece_type_at(move.from_square) == chess.PAWN return conversion, push - def _child_dtc_cell(self, cfg_c: PieceConfig, cboard: chess.Board, - cep: Optional[int], cw: int, child_rule50: int, - depth: int) -> Optional[_DTCCell]: + def _child_dtc_cell(self, cfg_c: _PieceConfig, cboard: chess.Board, + cep: int | None, cw: int, child_rule50: int, + depth: int) -> _DTCCell | None: """The child's DTC answer. A child with ep rights goes through the ep overlay, since its own record can't express the ep capture.""" if cep is None: @@ -2821,12 +2839,12 @@ def _child_dtc_cell(self, cfg_c: PieceConfig, cboard: chess.Board, cr = self._probe_impl(cfg_c, cboard, child_rule50, cep, depth) if not cr.has_dtc or not cr.has_dtz: return None - if cr.dtc_wdl == DRAW: + if cr.dtc_wdl == _DRAW: return _DTCCell(dtz=cr.dtz, dtz_rounded=cr.dtz_rounded) return _DTCCell(cr.dtc_order, cr.dtc, cr.dtz, cr.dtz_rounded) def _ep_conversion_wins(self, cboard: chess.Board, cep: int, - depth: int) -> Optional[bool]: + depth: int) -> bool | None: """Whether an ep capture out of the child wins for the capturer; ``None`` if none is known to win and some can't be resolved. *depth* is the child's.""" @@ -2834,36 +2852,36 @@ def _ep_conversion_wins(self, cboard: chess.Board, cep: int, unknown = False for mv in eps: cfg_g, gboard, gep, _zeroing = self._make_child(bcopy, mv) - gw = DRAW if cfg_g.is_bare_kings else self._probe_wdl_impl( + gw = _DRAW if cfg_g.is_bare_kings else self._probe_wdl_impl( cfg_g, gboard, gep, depth + 1) - if gw == ILLEGAL: + if gw == _ILLEGAL: unknown = True continue - if fold_50mr_wdl(invert_wdl(gw)) == WIN: + if _fold_50mr_wdl(_invert_wdl(gw)) == _WIN: return True return None if unknown else False def _derive_dtc(self, board: chess.Board, wdl: int, rule50: int, - depth: int) -> Optional[_DTCCell]: + depth: int) -> _DTCCell | None: """DTC by one-ply minimax for a frame the file doesn't hold. A conversion is terminal at value 1; a winner's push reads one budget lower. A win takes the cheapest budget any move offers, a loss the budget the most stubborn defense forces.""" - if depth >= MAX_DERIVE_DEPTH: + if depth >= _MAX_DERIVE_DEPTH: return None - if wdl == WIN: + if wdl == _WIN: return self._derive_dtc_win(board, rule50, depth) - if wdl == LOSE: + if wdl == _LOSE: return self._derive_dtc_loss(board, rule50, depth) return self._derive_dtc_cursed(board, wdl, depth) def _derive_dtc_win(self, board: chess.Board, rule50: int, - depth: int) -> Optional[_DTCCell]: + depth: int) -> _DTCCell | None: b = _internal_board(board) have = False best_order = best_value = 0 - budget_plies = dtc_budget_plies(rule50) - unbounded = _UnboundedFold(WIN) + budget_plies = _dtc_budget_plies(rule50) + unbounded = _UnboundedFold(_WIN) skipped = _SkippedChildren() for m in b.legal_moves: conversion, push = self._dtc_move_kind(b, m) @@ -2871,17 +2889,17 @@ def _derive_dtc_win(self, board: chess.Board, rule50: int, if cfg_c.is_bare_kings: continue cw = self._probe_wdl_impl(cfg_c, cboard, cep, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - if cw != LOSE: + if cw != _LOSE: continue order, value = 0, 1 if conversion: unbounded.zeroing_child() else: child_rule50 = 0 if push else ( - 1 if rule50 == IGNORE_50MR else rule50 + 1) + 1 if rule50 == _IGNORE_50MR else rule50 + 1) cell = self._child_dtc_cell(cfg_c, cboard, cep, cw, child_rule50, depth + 1) if cell is None: @@ -2902,24 +2920,24 @@ def _derive_dtc_win(self, board: chess.Board, rule50: int, best_order, best_value, have = order, value, True if best_order == 0 and best_value == 1: return _DTCCell(best_order, best_value, 1) - if skipped.unpin(WIN): + if skipped.unpin(_WIN): return None dtz = unbounded.value() return _DTCCell(best_order, best_value, dtz) if have else _DTCCell(dtz=dtz) def _derive_dtc_loss(self, board: chess.Board, rule50: int, - depth: int) -> Optional[_DTCCell]: + depth: int) -> _DTCCell | None: """Walks each child's whole record: the longest wait at the highest budget any defense needs isn't what a child's cheapest budget reports. Every child wins for the opponent, so no class is read.""" b = _internal_board(board) - worst = [0] * DTC_PACK_LAYERS - drawn = [False] * DTC_PACK_LAYERS + worst = [0] * _DTC_PACK_LAYERS + drawn = [False] * _DTC_PACK_LAYERS any_legal = False - unbounded = _UnboundedFold(LOSE) + unbounded = _UnboundedFold(_LOSE) def raise_at(k: int, val: int) -> None: - if val > MAX_NON_CURSED_DTZ: + if val > _MAX_NON_CURSED_DTZ: drawn[k] = True elif val > worst[k]: worst[k] = val @@ -2929,7 +2947,7 @@ def raise_at(k: int, val: int) -> None: # Only a capture can bare the kings, so `conversion` already covers that. conversion, push = self._dtc_move_kind(b, m) if conversion: - for k in range(DTC_PACK_LAYERS): + for k in range(_DTC_PACK_LAYERS): raise_at(k, 1) unbounded.zeroing_child() continue @@ -2939,21 +2957,21 @@ def raise_at(k: int, val: int) -> None: if ep_wins is None: return None if ep_wins: - for k in range(DTC_PACK_LAYERS): + for k in range(_DTC_PACK_LAYERS): raise_at(k, 1) unbounded.zeroing_child() continue - curve = self._read_dtc_curve(self._open_dtc(cfg_c), cfg_c, cboard, WIN) + curve = self._read_dtc_curve(self._open_dtc(cfg_c), cfg_c, cboard, _WIN) if curve is None: return None if push: unbounded.zeroing_child() else: - unbounded.quiet_child(curve[DTC_BUDGET_LAYERS], False, False) - for k in range(DTC_PACK_LAYERS): + unbounded.quiet_child(curve[_DTC_BUDGET_LAYERS], False, False) + for k in range(_DTC_PACK_LAYERS): v = curve[k] - if v == DRAWN_AT_LAYER: + if v == _DRAWN_AT_LAYER: drawn[k] = True else: raise_at(k, 1 if push else v + 1) @@ -2961,17 +2979,17 @@ def raise_at(k: int, val: int) -> None: if not any_legal: return _DTCCell(0, 0, 0) # mate: converted, nothing owed dtz = unbounded.value() - budget_plies = dtc_budget_plies(rule50) - for k in range(DTC_PACK_LAYERS): + budget_plies = _dtc_budget_plies(rule50) + for k in range(_DTC_PACK_LAYERS): if not drawn[k] and worst[k] <= budget_plies: return _DTCCell(k, worst[k], dtz) return _DTCCell(dtz=dtz) def _derive_dtc_cursed(self, board: chess.Board, wdl: int, - depth: int) -> Optional[_DTCCell]: + depth: int) -> _DTCCell | None: """A cursed class has no budget, so only the unbounded row is derived.""" b = _internal_board(board) - winning = (wdl == CURSED_WIN) + winning = (wdl == _CURSED_WIN) unbounded = _UnboundedFold(wdl) any_legal = False skipped = _SkippedChildren() @@ -2983,26 +3001,26 @@ def _derive_dtc_cursed(self, board: chess.Board, wdl: int, # Bare kings is an outright draw, a move neither class counts. continue cw = self._probe_wdl_impl(cfg_c, cboard, cep, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - if winning and cw not in (LOSE, BLESSED_LOSS): + if winning and cw not in (_LOSE, _BLESSED_LOSS): continue # A blessed loss counts only moves that keep it blessed: into a # cursed win, or quietly into a win already at the horizon. - if not winning and cw != CURSED_WIN and (conversion or push): + if not winning and cw != _CURSED_WIN and (conversion or push): continue if conversion or push: unbounded.zeroing_child() - if winning and invert_wdl(cw) == wdl: + if winning and _invert_wdl(cw) == wdl: return _DTCCell(dtz=1) continue cell = self._probe_dtc_internal(self._open_dtc(cfg_c), cfg_c, cboard, - cw, IGNORE_50MR, depth + 1) + cw, _IGNORE_50MR, depth + 1) if cell is None: skipped.unknown() continue - if not winning and cw == WIN and cell.dtz < MAX_NON_CURSED_DTZ: + if not winning and cw == _WIN and cell.dtz < _MAX_NON_CURSED_DTZ: continue unbounded.quiet_child(cell.dtz, _is_cursed_exit(b, cboard, cw), cell.dtz_rounded) if skipped.unpin(wdl): @@ -3011,94 +3029,94 @@ def _derive_dtc_cursed(self, board: chess.Board, wdl: int, else _DTCCell()) # --- DTM (the standalone `dtm/` table) --- - def _probe_dtm_internal(self, d: Optional[DTMFile], cfg: PieceConfig, - board: chess.Board, wdl: int, depth: int) -> Optional[int]: + def _probe_dtm_internal(self, d: _DTMFile | None, cfg: _PieceConfig, + board: chess.Board, wdl: int, depth: int) -> int | None: if d is None: return None - color, mp, readable = locate_frame(d, cfg, board, wdl) + color, mp, readable = _locate_frame(d, cfg, board, wdl) if not readable: return self._derive_dtm(board, wdl, depth) return d.read(color, board if mp is None else mp, wdl) - def _derive_dtm(self, board: chess.Board, wdl: int, depth: int) -> Optional[int]: + def _derive_dtm(self, board: chess.Board, wdl: int, depth: int) -> int | None: """DTM by one-ply minimax for a dropped frame. DTM ignores the 50-move rule, so cursed classes fold to decisive ones and no clock is tracked.""" - if depth >= MAX_DERIVE_DEPTH: + if depth >= _MAX_DERIVE_DEPTH: return None - pinned = fold_dtm_wdl(wdl) + pinned = _fold_dtm_wdl(wdl) b = _internal_board(board) any_legal = False - best_wdl, best_dtm = LOSE, 0 + best_wdl, best_dtm = _LOSE, 0 skipped = _SkippedChildren() for mv in b.legal_moves: any_legal = True cfg_c, cboard, cep, _zeroing = self._make_child(b, mv) if cfg_c.is_bare_kings: - cw, cd = DRAW, 0 + cw, cd = _DRAW, 0 elif cep is not None: - cr = self._probe_impl(cfg_c, cboard, IGNORE_50MR, cep, depth + 1) - if cr.wdl == ILLEGAL: + cr = self._probe_impl(cfg_c, cboard, _IGNORE_50MR, cep, depth + 1) + if cr.wdl == _ILLEGAL: skipped.unknown() continue if not cr.has_dtm: - skipped.of_class(invert_wdl(fold_dtm_wdl(cr.wdl))) + skipped.of_class(_invert_wdl(_fold_dtm_wdl(cr.wdl))) continue cw, cd = cr.wdl, cr.dtm else: - if child_class_is_forced(pinned): - cw = WIN + if _child_class_is_forced(pinned): + cw = _WIN else: cw = self._probe_wdl_internal(self._open_wdl(cfg_c), cfg_c, cboard, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - if below_pinned_class(pinned, invert_wdl(fold_dtm_wdl(cw))): + if _below_pinned_class(pinned, _invert_wdl(_fold_dtm_wdl(cw))): continue child_dtm = self._probe_dtm_internal(self._open_dtm(cfg_c), cfg_c, cboard, cw, depth + 1) if child_dtm is None: - skipped.of_class(invert_wdl(fold_dtm_wdl(cw))) + skipped.of_class(_invert_wdl(_fold_dtm_wdl(cw))) continue cd = child_dtm - my_wdl = invert_wdl(fold_dtm_wdl(cw)) + my_wdl = _invert_wdl(_fold_dtm_wdl(cw)) my_dtm = 1 + cd - if prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): + if _prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): best_wdl, best_dtm = my_wdl, my_dtm - if pinned == WIN and best_wdl == pinned and best_dtm == 1: + if pinned == _WIN and best_wdl == pinned and best_dtm == 1: return best_dtm if not any_legal: return 0 if skipped.unpin(best_wdl): return None - if best_wdl in (WIN, LOSE): + if best_wdl in (_WIN, _LOSE): return best_dtm return 0 # --- DTM50 (whose flat layer answers DTM too) --- - def _probe_dtm50_internal(self, m: Optional[DTM50File], cfg: PieceConfig, + def _probe_dtm50_internal(self, m: _DTM50File | None, cfg: _PieceConfig, board: chess.Board, wdl: int, rule50: int, depth: int) -> _DTM50Result: - flat = (rule50 == IGNORE_50MR) - if not flat and rule50 >= DTM50_HMC_COUNT: - return _DTM50Result(DRAW, 0) + flat = (rule50 == _IGNORE_50MR) + if not flat and rule50 >= _DTM50_HMC_COUNT: + return _DTM50Result(_DRAW, 0) if m is None: - return _DTM50Result(ILLEGAL, 0) + return _DTM50Result(_ILLEGAL, 0) - def from_cell(cell: Tuple[int, int]) -> _DTM50Result: + def from_cell(cell: tuple[int, int]) -> _DTM50Result: value, flip = cell - if value == DRAWN_AT_LAYER: - cls, value = DRAW, 0 + if value == _DRAWN_AT_LAYER: + cls, value = _DRAW, 0 else: - cls = wdl if flat else fold_50mr_wdl(wdl) + cls = wdl if flat else _fold_50mr_wdl(wdl) if not flat: return _DTM50Result(cls, value) - dtz = dtz_from_draw_flip(flip, wdl, board) + dtz = _dtz_from_draw_flip(flip, wdl, board) if dtz is None: return _DTM50Result(cls, value) return _DTM50Result(cls, value, True, dtz) - color, mp, readable = locate_frame(m, cfg, board, wdl) + color, mp, readable = _locate_frame(m, cfg, board, wdl) if not readable: return (self._derive_dtm50_flat(board, wdl, depth) if flat else self._derive_dtm50(board, wdl, rule50, depth)) @@ -3108,156 +3126,156 @@ def _derive_dtm50_flat(self, board: chess.Board, wdl: int, depth: int) -> _DTM50Result: """Unbounded DTM by one-ply minimax for a dropped layer-0 frame, carrying DTZ as a cell read does.""" - if depth >= MAX_DERIVE_DEPTH: - return _DTM50Result(ILLEGAL, 0) - pinned = fold_dtm_wdl(wdl) + if depth >= _MAX_DERIVE_DEPTH: + return _DTM50Result(_ILLEGAL, 0) + pinned = _fold_dtm_wdl(wdl) b = _internal_board(board) any_legal = False - best_wdl, best_dtm = LOSE, 0 + best_wdl, best_dtm = _LOSE, 0 dtz = _DTZMinimax() skipped = _SkippedChildren() for mv in b.legal_moves: any_legal = True cfg_c, cboard, cep, zeroing = self._make_child(b, mv) if cfg_c.is_bare_kings: - cw, cd = DRAW, 0 - dtz.zeroing_child(DRAW) + cw, cd = _DRAW, 0 + dtz.zeroing_child(_DRAW) elif cep is not None: - cr = self._probe_impl(cfg_c, cboard, IGNORE_50MR, cep, depth + 1) - if cr.wdl == ILLEGAL: + cr = self._probe_impl(cfg_c, cboard, _IGNORE_50MR, cep, depth + 1) + if cr.wdl == _ILLEGAL: skipped.unknown() dtz.unwalked() continue dtz.zeroing_child(cr.wdl) # a double push zeroes the clock if not cr.has_dtm: - skipped.of_class(invert_wdl(fold_dtm_wdl(cr.wdl))) + skipped.of_class(_invert_wdl(_fold_dtm_wdl(cr.wdl))) continue cw, cd = cr.wdl, cr.dtm else: - if child_class_is_forced(wdl): - raw_wdl = WIN + if _child_class_is_forced(wdl): + raw_wdl = _WIN else: raw_wdl = self._probe_wdl_internal(self._open_wdl(cfg_c), cfg_c, cboard, depth + 1) - if raw_wdl == ILLEGAL: + if raw_wdl == _ILLEGAL: skipped.unknown() dtz.unwalked() continue - if below_pinned_class(pinned, invert_wdl(fold_dtm_wdl(raw_wdl))): + if _below_pinned_class(pinned, _invert_wdl(_fold_dtm_wdl(raw_wdl))): continue child = self._probe_dtm50_internal(self._open_dtm50(cfg_c), cfg_c, - cboard, raw_wdl, IGNORE_50MR, depth + 1) + cboard, raw_wdl, _IGNORE_50MR, depth + 1) if zeroing: dtz.zeroing_child(raw_wdl) else: dtz.quiet_child(raw_wdl, child, _is_cursed_exit(b, cboard, raw_wdl)) - if child.wdl == ILLEGAL: - skipped.of_class(invert_wdl(fold_dtm_wdl(raw_wdl))) + if child.wdl == _ILLEGAL: + skipped.of_class(_invert_wdl(_fold_dtm_wdl(raw_wdl))) continue cw, cd = child.wdl, child.dtm - my_wdl = invert_wdl(fold_dtm_wdl(cw)) + my_wdl = _invert_wdl(_fold_dtm_wdl(cw)) my_dtm = 1 + cd - if prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): + if _prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): best_wdl, best_dtm = my_wdl, my_dtm if not any_legal: - return dtz.finish(LOSE if b.is_check() else DRAW, 0, False) + return dtz.finish(_LOSE if b.is_check() else _DRAW, 0, False) if skipped.unpin(best_wdl): - return dtz.finish(ILLEGAL, 0, True) - if best_wdl in (WIN, LOSE): + return dtz.finish(_ILLEGAL, 0, True) + if best_wdl in (_WIN, _LOSE): return dtz.finish(best_wdl, best_dtm, True) - return dtz.finish(DRAW, 0, True) + return dtz.finish(_DRAW, 0, True) def _derive_dtm50(self, board: chess.Board, wdl: int, rule50: int, depth: int) -> _DTM50Result: """Clock-aware DTM50 derive: a child at 100 plies or more is a draw unless mated. No DTZ: :meth:`_probe_impl` takes it from layer 0.""" - if depth >= MAX_DERIVE_DEPTH: - return _DTM50Result(ILLEGAL, 0) - pinned = fold_50mr_wdl(wdl) + if depth >= _MAX_DERIVE_DEPTH: + return _DTM50Result(_ILLEGAL, 0) + pinned = _fold_50mr_wdl(wdl) b = _internal_board(board) any_legal = False - best_wdl, best_dtm = LOSE, 0 + best_wdl, best_dtm = _LOSE, 0 skipped = _SkippedChildren() for mv in b.legal_moves: any_legal = True cfg_c, cboard, cep, zeroing = self._make_child(b, mv) child_rule50 = 0 if zeroing else rule50 + 1 if cfg_c.is_bare_kings: - cd_wdl, cd_dtm = DRAW, 0 - elif child_rule50 >= DTM50_HMC_COUNT: - cd_wdl, cd_dtm = (LOSE, 0) if cboard.is_checkmate() else (DRAW, 0) + cd_wdl, cd_dtm = _DRAW, 0 + elif child_rule50 >= _DTM50_HMC_COUNT: + cd_wdl, cd_dtm = (_LOSE, 0) if cboard.is_checkmate() else (_DRAW, 0) elif cep is not None: cr = self._probe_impl(cfg_c, cboard, child_rule50, cep, depth + 1) - if cr.wdl == ILLEGAL: + if cr.wdl == _ILLEGAL: skipped.unknown() continue if not cr.has_dtm50: - skipped.of_class(invert_wdl(fold_50mr_wdl(cr.wdl))) + skipped.of_class(_invert_wdl(_fold_50mr_wdl(cr.wdl))) continue cd_wdl, cd_dtm = cr.dtm50_wdl, cr.dtm50 else: - if child_class_is_forced(wdl): - cw = WIN + if _child_class_is_forced(wdl): + cw = _WIN else: cw = self._probe_wdl_internal(self._open_wdl(cfg_c), cfg_c, cboard, depth + 1) - if cw == ILLEGAL: + if cw == _ILLEGAL: skipped.unknown() continue - if below_pinned_class(wdl, invert_wdl(cw)): + if _below_pinned_class(wdl, _invert_wdl(cw)): continue child = self._probe_dtm50_internal(self._open_dtm50(cfg_c), cfg_c, cboard, cw, child_rule50, depth + 1) - if child.wdl == ILLEGAL: - skipped.of_class(invert_wdl(fold_50mr_wdl(cw))) + if child.wdl == _ILLEGAL: + skipped.of_class(_invert_wdl(_fold_50mr_wdl(cw))) continue cd_wdl, cd_dtm = child.wdl, child.dtm - my_wdl = invert_wdl(fold_50mr_wdl(cd_wdl)) + my_wdl = _invert_wdl(_fold_50mr_wdl(cd_wdl)) my_dtm = 1 + cd_dtm - if prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): + if _prefer_new(my_wdl, my_dtm, best_wdl, best_dtm): best_wdl, best_dtm = my_wdl, my_dtm - if pinned == WIN and best_wdl == pinned and best_dtm == 1: + if pinned == _WIN and best_wdl == pinned and best_dtm == 1: return _DTM50Result(best_wdl, best_dtm) if not any_legal: - return _DTM50Result(LOSE if b.is_check() else DRAW, 0) + return _DTM50Result(_LOSE if b.is_check() else _DRAW, 0) if skipped.unpin(best_wdl): - return _DTM50Result(ILLEGAL, 0) - if best_wdl in (WIN, LOSE): + return _DTM50Result(_ILLEGAL, 0) + if best_wdl in (_WIN, _LOSE): return _DTM50Result(best_wdl, best_dtm) - return _DTM50Result(DRAW, 0) + return _DTM50Result(_DRAW, 0) # --- combined probe with ep overlay (src/probe/probe.cpp) --- - def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, - ep_square: Optional[int], depth: int) -> ProbeResult: - r = ProbeResult() + def _probe_impl(self, cfg: _PieceConfig, board: chess.Board, rule50: int, + ep_square: int | None, depth: int) -> _Result: + r = _Result() w = self._open_wdl(cfg) if w is None: return r - rule50_drawn = (rule50 != IGNORE_50MR and rule50 >= DTM50_HMC_COUNT) + rule50_drawn = (rule50 != _IGNORE_50MR and rule50 >= _DTM50_HMC_COUNT) r.wdl = self._probe_wdl_internal(w, cfg, board, depth) - if r.wdl == ILLEGAL: + if r.wdl == _ILLEGAL: return r - m50 = self._open_dtm50(cfg) if r.wdl != DRAW else None - if r.wdl == DRAW: + m50 = self._open_dtm50(cfg) if r.wdl != _DRAW else None + if r.wdl == _DRAW: r.has_dtm = True r.has_dtz = True - if rule50 != IGNORE_50MR: - r.dtc_wdl = DRAW + if rule50 != _IGNORE_50MR: + r.dtc_wdl = _DRAW r.has_dtc = True - r.dtm50_wdl = DRAW + r.dtm50_wdl = _DRAW r.has_dtm50 = True elif m50 is not None: - d50 = self._probe_dtm50_internal(m50, cfg, board, r.wdl, IGNORE_50MR, depth) + d50 = self._probe_dtm50_internal(m50, cfg, board, r.wdl, _IGNORE_50MR, depth) r.dtm = d50.dtm - r.has_dtm = (d50.wdl != ILLEGAL) + r.has_dtm = (d50.wdl != _ILLEGAL) r.dtz = d50.dtz r.has_dtz = d50.has_dtz - _fill_dtc_from_bounds(r, material_has_pawns(cfg), rule50) + _fill_dtc_from_bounds(r, _material_has_pawns(cfg), rule50) _fill_dtm50_from_bounds(r, rule50) - if not r.has_dtm50 and rule50 != IGNORE_50MR and rule50 < DTM50_HMC_COUNT: + if not r.has_dtm50 and rule50 != _IGNORE_50MR and rule50 < _DTM50_HMC_COUNT: d50 = self._probe_dtm50_internal(m50, cfg, board, r.wdl, rule50, depth) r.dtm50_wdl = d50.wdl r.dtm50 = d50.dtm - r.has_dtm50 = (d50.wdl != ILLEGAL) + r.has_dtm50 = (d50.wdl != _ILLEGAL) else: m = self._open_dtm(cfg) @@ -3268,14 +3286,14 @@ def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, r.has_dtm = True # The DTC pack gives DTC at this clock and DTZ from its unbounded row; # cursed or out of clock, it prices nothing. - if r.wdl != DRAW and (not r.has_dtc or not r.has_dtz) and material_has_pawns(cfg): + if r.wdl != _DRAW and (not r.has_dtc or not r.has_dtz) and _material_has_pawns(cfg): c = self._open_dtc(cfg) if c is not None: cell = self._probe_dtc_internal(c, cfg, board, r.wdl, rule50, depth) if cell is not None: # Unclocked, the cell serves only its DTZ row. - if rule50 != IGNORE_50MR: - r.dtc_wdl = r.wdl if cell.priced else DRAW + if rule50 != _IGNORE_50MR: + r.dtc_wdl = r.wdl if cell.priced else _DRAW r.dtc_order = cell.order if cell.priced else 0 r.dtc = cell.value if cell.priced else 0 r.has_dtc = True @@ -3294,14 +3312,14 @@ def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, r.has_dtz = True # Only pawnless material gets a decisive DTC from DTZ alone. if not r.has_dtc: - _fill_dtc_from_bounds(r, material_has_pawns(cfg), rule50) + _fill_dtc_from_bounds(r, _material_has_pawns(cfg), rule50) if not r.has_dtm50: _fill_dtm50_from_bounds(r, rule50) _fill_wdl50(r, rule50) - if ep_square is None or r.wdl == ILLEGAL: + if ep_square is None or r.wdl == _ILLEGAL: return r bcopy, eps = _ep_capture_moves(board, ep_square) if not eps: @@ -3311,9 +3329,9 @@ def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, best = r best_dtz_wdl = r.wdl best_dtz = r.dtz if r.has_dtz else 0 - best_dtm_wdl = fold_dtm_wdl(r.wdl) + best_dtm_wdl = _fold_dtm_wdl(r.wdl) best_dtm = r.dtm if r.has_dtm else 0 - best_dtm50_wdl = r.dtm50_wdl if r.has_dtm50 else fold_50mr_wdl(r.wdl) + best_dtm50_wdl = r.dtm50_wdl if r.has_dtm50 else _fold_50mr_wdl(r.wdl) best_dtm50 = r.dtm50 if r.has_dtm50 else 0 # DTC compares on its own class: a base this clock has drawn must lose # to an ep conversion that still wins. @@ -3322,69 +3340,69 @@ def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, best_dtc = r.dtc if r.has_dtc else 0 any_ep = False # Unclocked, DTC and DTM50 don't exist; a drawn clock has the claim. - live_clock = rule50 != IGNORE_50MR and not rule50_drawn + live_clock = rule50 != _IGNORE_50MR and not rule50_drawn if rule50_drawn: # Even an ep capture costs a ply; the claim is already there. - best.dtc_wdl = DRAW + best.dtc_wdl = _DRAW best.has_dtc = True - best.dtm50_wdl = DRAW + best.dtm50_wdl = _DRAW best.has_dtm50 = True for mv in eps: cfg_c, cboard, _cep, _ = self._make_child(bcopy, mv) if cfg_c.is_bare_kings: - cr = ProbeResult() - cr.wdl = DRAW + cr = _Result() + cr.wdl = _DRAW cr.has_dtz = best.has_dtz cr.has_dtm = best.has_dtm - cr.dtm50_wdl = DRAW + cr.dtm50_wdl = _DRAW cr.has_dtm50 = best.has_dtm50 else: - cr = self._probe_impl(cfg_c, cboard, 0 if live_clock else IGNORE_50MR, + cr = self._probe_impl(cfg_c, cboard, 0 if live_clock else _IGNORE_50MR, None, depth + 1) # ep is zeroing - if cr.wdl == ILLEGAL: - return ProbeResult() - my_wdl = invert_wdl(cr.wdl) + if cr.wdl == _ILLEGAL: + return _Result() + my_wdl = _invert_wdl(cr.wdl) if not has_non_ep_move and not any_ep: best.wdl = my_wdl best_dtz_wdl, best_dtz = my_wdl, 1 - best.dtz = 0 if my_wdl == DRAW else 1 + best.dtz = 0 if my_wdl == _DRAW else 1 best.dtz_rounded = False best.has_dtz = True - best_dtm_wdl = fold_dtm_wdl(my_wdl) + best_dtm_wdl = _fold_dtm_wdl(my_wdl) best_dtm = 1 + cr.dtm if cr.has_dtm else 0 best.dtm = (best_dtm if cr.has_dtm - and best_dtm_wdl in (WIN, LOSE) else 0) + and best_dtm_wdl in (_WIN, _LOSE) else 0) best.has_dtm = cr.has_dtm if live_clock: best_dtc_wdl, best_dtc_order, best_dtc = ( - fold_50mr_wdl(my_wdl), 0, 1) + _fold_50mr_wdl(my_wdl), 0, 1) best.dtc_wdl = best_dtc_wdl best.dtc_order = 0 - best.dtc = 0 if best_dtc_wdl == DRAW else 1 + best.dtc = 0 if best_dtc_wdl == _DRAW else 1 best.has_dtc = True - best_dtm50_wdl = invert_wdl(cr.dtm50_wdl) if cr.has_dtm50 else ILLEGAL + best_dtm50_wdl = _invert_wdl(cr.dtm50_wdl) if cr.has_dtm50 else _ILLEGAL best_dtm50 = 1 + cr.dtm50 if cr.has_dtm50 else 0 best.dtm50_wdl = best_dtm50_wdl best.dtm50 = (best_dtm50 if cr.has_dtm50 - and best_dtm50_wdl in (WIN, LOSE) else 0) + and best_dtm50_wdl in (_WIN, _LOSE) else 0) best.has_dtm50 = cr.has_dtm50 any_ep = True continue any_ep = True - if wdl_rank(my_wdl) > wdl_rank(best.wdl): + if _wdl_rank(my_wdl) > _wdl_rank(best.wdl): best.wdl = my_wdl # An ep capture zeroes, so its DTZ is 1. The base DTZ is needed # only to break a class tie, so an unknown one doesn't block it. - ep_outranks_dtz = wdl_rank(my_wdl) > wdl_rank(best_dtz_wdl) + ep_outranks_dtz = _wdl_rank(my_wdl) > _wdl_rank(best_dtz_wdl) if ep_outranks_dtz or (best.has_dtz - and prefer_new(my_wdl, 1, best_dtz_wdl, best_dtz)): + and _prefer_new(my_wdl, 1, best_dtz_wdl, best_dtz)): best_dtz_wdl, best_dtz = my_wdl, 1 - best.dtz = 0 if my_wdl == DRAW else 1 + best.dtz = 0 if my_wdl == _DRAW else 1 best.dtz_rounded = False best.has_dtz = True # A DTM ignoring a legal ep capture would be wrong, so a child @@ -3392,50 +3410,52 @@ def _probe_impl(self, cfg: PieceConfig, board: chess.Board, rule50: int, if not cr.has_dtm: best.has_dtm = False elif best.has_dtm: - my_dtm_wdl = fold_dtm_wdl(my_wdl) + my_dtm_wdl = _fold_dtm_wdl(my_wdl) my_dtm = 1 + cr.dtm - if prefer_new(my_dtm_wdl, my_dtm, best_dtm_wdl, best_dtm): + if _prefer_new(my_dtm_wdl, my_dtm, best_dtm_wdl, best_dtm): best_dtm_wdl, best_dtm = my_dtm_wdl, my_dtm - best.dtm = my_dtm if my_dtm_wdl in (WIN, LOSE) else 0 + best.dtm = my_dtm if my_dtm_wdl in (_WIN, _LOSE) else 0 if live_clock: # An ep capture is a conversion one ply out: (0, 1), classed by # the child's 50MR-folded WDL. The base only breaks a class tie. - my_dtc_wdl = fold_50mr_wdl(invert_wdl(cr.wdl)) - if (wdl_rank(my_dtc_wdl) > wdl_rank(best_dtc_wdl) - or (best.has_dtc and prefer_new_dtc(my_dtc_wdl, 0, 1, + my_dtc_wdl = _fold_50mr_wdl(_invert_wdl(cr.wdl)) + if (_wdl_rank(my_dtc_wdl) > _wdl_rank(best_dtc_wdl) + or (best.has_dtc and _prefer_new_dtc(my_dtc_wdl, 0, 1, best_dtc_wdl, best_dtc_order, best_dtc))): best_dtc_wdl, best_dtc_order, best_dtc = my_dtc_wdl, 0, 1 best.dtc_wdl = my_dtc_wdl best.dtc_order = 0 - best.dtc = 1 if my_dtc_wdl != DRAW else 0 + best.dtc = 1 if my_dtc_wdl != _DRAW else 0 best.has_dtc = True if not cr.has_dtm50: best.has_dtm50 = False elif best.has_dtm50: - my_dtm50_wdl = invert_wdl(cr.dtm50_wdl) + my_dtm50_wdl = _invert_wdl(cr.dtm50_wdl) my_dtm50 = 1 + cr.dtm50 - if prefer_new(my_dtm50_wdl, my_dtm50, best_dtm50_wdl, best_dtm50): + if _prefer_new(my_dtm50_wdl, my_dtm50, best_dtm50_wdl, best_dtm50): best_dtm50_wdl, best_dtm50 = my_dtm50_wdl, my_dtm50 best.dtm50_wdl = my_dtm50_wdl - best.dtm50 = my_dtm50 if my_dtm50_wdl in (WIN, LOSE) else 0 + best.dtm50 = my_dtm50 if my_dtm50_wdl in (_WIN, _LOSE) else 0 # An ep capture may have changed the class and DTZ; decide again. best.has_wdl50 = False _fill_wdl50(best, rule50) return best # --- public API --- - def probe(self, board: chess.Board, rule50: Optional[int] = None) -> ProbeResult: - """Probes all metrics of *board* at once. + def probe(self, board: chess.Board, rule50: int | None = None) -> ProbeResult: + """ + Probes every metric of a position at once. - *rule50*, the halfmove clock (by default the board's own), selects - the DTM50 and DTC values and decides ``wdl50`` where possible. + :param rule50: The halfmove clock to probe at, instead of the board's + own. It decides :attr:`~ProbeResult.wdl50`, + :attr:`~ProbeResult.dtc` and :attr:`~ProbeResult.dtm50`. - Returns a :class:`ProbeResult` whose ``wdl`` is :data:`ILLEGAL` if - the tables can't answer. A board with castling rights is answered only - by tables carrying those rights. + Fields the tables can't answer are ``None``; nothing is raised. + """ + return _to_public(self._probe(board, rule50)) - Thread-safe. A concurrent :meth:`close` waits for probes to finish.""" + def _probe(self, board: chess.Board, rule50: int | None) -> _Result: hmc = board.halfmove_clock if rule50 is None else rule50 with self._reading(): cfg, cboard, ep = self._canonical_root(board) @@ -3453,7 +3473,7 @@ def _reading(self) -> Iterator[None]: self._read_condition.notify_all() def _canonical_root(self, board: chess.Board - ) -> Tuple[PieceConfig, chess.Board, Optional[int]]: + ) -> tuple[_PieceConfig, chess.Board, int | None]: """Config, canonical board and split-off ep square to probe *board*, which is left as it is. Rooks holding a right are marks; so is the opposing pair, where its table is on disk (it duplicates its full @@ -3462,7 +3482,7 @@ def _canonical_root(self, board: chess.Board white, black = board.occupied_co[chess.WHITE], board.occupied_co[chess.BLACK] men = (board.pawns, board.knights, board.bishops, board.rooks, board.queens) rights = board.clean_castling_rights() - pair = PairGroup.canonical_pair(board.pawns & white, board.pawns & black) + pair = _PairGroup.canonical_pair(board.pawns & white, board.pawns & black) key = (tuple([chess.popcount(m & white) for m in men] + [chess.popcount(m & black) for m in men]), chess.popcount(rights & white), chess.popcount(rights & black), pair is not None) @@ -3477,7 +3497,7 @@ def _canonical_root(self, board: chess.Board self._roots[key] = root cfg, mirrored = root if mirrored: - board = mirror_for_canonical(board) + board = _mirror_for_canonical(board) elif board.ep_square is not None: board = board.copy(stack=False) ep = board.ep_square @@ -3485,113 +3505,141 @@ def _canonical_root(self, board: chess.Board return cfg, board, ep def _require(self, board: chess.Board, - rule50: Optional[int] = IGNORE_50MR) -> ProbeResult: + rule50: int | None = _IGNORE_50MR) -> _Result: # Unclocked by default for DTZ and DTM; DTC and DTM50 pass a clock. - r = self.probe(board, rule50) - if r.wdl == ILLEGAL: + r = self._probe(board, rule50) + if r.wdl == _ILLEGAL: with self._reading(): # naming the material may open a table raise MissingTableError( f"no chesstb table for {self._canonical_root(board)[0].name()}") return r def probe_wdl(self, board: chess.Board) -> int: - """Probes the win/draw/loss value of *board*. + """ + Probes for win/draw/loss information. - Returns ``2`` if the side to move is winning, ``0`` for a draw and - ``-2`` if the side to move is losing; ``1`` for a cursed win and - ``-1`` for a blessed loss (drawn by the 50-move rule). + Returns ``2`` if the side to move is winning, ``0`` if the position is + a draw and ``-2`` if the side to move is losing. Returns ``1`` for a + win that the 50-move rule turns into a draw (cursed win) and ``-1`` + for a loss it saves (blessed loss). + + A position with castling rights is answered from the tables for + those rights. :raises: :exc:`MissingTableError` if the tables can't answer. Use - :meth:`get_wdl` to get ``None`` instead.""" + :meth:`get_wdl` to get ``None`` instead. + """ with self._reading(): cfg, cboard, ep = self._canonical_root(board) # No distance table is read; a WIN stands despite unresolved ep. w = self._probe_wdl_impl(cfg, cboard, ep, 0) - if w == ILLEGAL: + if w == _ILLEGAL: raise MissingTableError( f"no chesstb table for {self._canonical_root(board)[0].name()}") return _WDL_SIGNED[w] - def get_wdl(self, board: chess.Board, default: Any = None) -> Any: + def get_wdl(self, board: chess.Board, default: int | None = None) -> int | None: + """Like :meth:`probe_wdl`, but returns *default* instead of raising.""" try: return self.probe_wdl(board) except MissingTableError: return default def probe_dtz(self, board: chess.Board) -> int: - """Probes the distance to zeroing (capture, promotion or pawn move) - of *board*: ``n`` if the side to move zeroes toward a win in ``n`` - plies, ``-n`` toward a loss, ``0`` for a draw. + """ + Probes the distance to zeroing: the plies to the next capture, pawn + move or promotion, with the 50-move rule ignored. - Not interchangeable with :meth:`chess.syzygy.Tablebase.probe_dtz`: - this doesn't encode the base shift for cursed and blessed results, - whose class only :meth:`probe_wdl` gives. + Returns ``n`` if the side to move is winning, ``-n`` if it is losing + and ``0`` for a draw. Unlike :meth:`chess.syzygy.Tablebase.probe_dtz`, + cursed wins and blessed losses are plain distances too: use + :meth:`probe_wdl` to tell them apart. The distance can be one ply off, + which :attr:`ProbeResult.dtz_rounded` reports. - :raises: :exc:`MissingTableError` if the DTZ can't be determined. Use - :meth:`get_dtz` to get ``None`` instead. + :raises: :exc:`MissingTableError` if the distance can't be determined. + Use :meth:`get_dtz` to get ``None`` instead. """ r = self._require(board) if not r.has_dtz: raise MissingTableError("DTZ table unavailable") return _signed(r.dtz, r.wdl) - def get_dtz(self, board: chess.Board, default: Any = None) -> Any: + def get_dtz(self, board: chess.Board, default: int | None = None) -> int | None: + """Like :meth:`probe_dtz`, but returns *default* instead of raising.""" try: return self.probe_dtz(board) except MissingTableError: return default def probe_dtc(self, board: chess.Board, - rule50: Optional[int] = None) -> Tuple[int, int]: - """Probes the distance to conversion of *board* at its halfmove clock - (or *rule50*), counting pawn pushes separately from other moves. - - Returns ``(pushes_owed, signed_plies)``: the pushes the winning side - still owes before a capture or promotion, and the signed plies to the - next zeroing move on that line. Fewest pushes comes first, but a - tight clock can force a line owing more. ``(0, 0)`` if the clock - leaves no win (a 50-move-rule draw). Pawnless positions owe nothing: - ``(0, dtz)``. - - :raises: :exc:`MissingTableError` if the DTC can't be determined.""" + rule50: int | None = None) -> tuple[int, int]: + """ + Probes the distance to conversion at the board's halfmove clock (or + *rule50*), counting pawn pushes separately from other moves. + + Returns ``(pushes, plies)``: the pawn pushes the winning side still + owes before a capture or promotion, and the plies to the next capture, + pawn move or promotion on that line, negative if the side to move is + losing. The line owing the fewest pushes is preferred, but a tight + clock can force one owing more. ``(0, 0)`` if the clock leaves no win. + Without pawns nothing is owed: ``(0, dtz)``. + + :raises: :exc:`MissingTableError` if the distance can't be determined. + """ r = self._require(board, rule50) if not r.has_dtc: raise MissingTableError("DTC unavailable") return (r.dtc_order, _signed(r.dtc, r.dtc_wdl)) def probe_dtm(self, board: chess.Board) -> int: - """Probes the signed distance to mate, ignoring the 50-move rule. + """ + Probes the distance to mate, with the 50-move rule ignored. + + Returns ``n`` if the side to move mates in ``n`` plies, ``-n`` if it + is mated in ``n`` plies, and ``0`` for a draw or when it is already + checkmated. - :raises: :exc:`MissingTableError` if the DTM can't be determined. Use - :meth:`get_dtm` to get ``None`` instead.""" + :raises: :exc:`MissingTableError` if the distance can't be determined. + Use :meth:`get_dtm` to get ``None`` instead. + """ r = self._require(board) if not r.has_dtm: raise MissingTableError("DTM unavailable") return _signed(r.dtm, r.wdl) - def get_dtm(self, board: chess.Board, default: Any = None) -> Any: + def get_dtm(self, board: chess.Board, default: int | None = None) -> int | None: + """Like :meth:`probe_dtm`, but returns *default* instead of raising.""" try: return self.probe_dtm(board) except MissingTableError: return default - def probe_dtm50(self, board: chess.Board, rule50: Optional[int] = None) -> int: - """Probes the signed distance to mate under the 50-move rule, at the - board's halfmove clock (or *rule50*). ``0`` if the 50-move rule draws, - including cursed wins and blessed losses. + def probe_dtm50(self, board: chess.Board, rule50: int | None = None) -> int: + """ + Probes the distance to mate under the 50-move rule, at the board's + halfmove clock (or *rule50*). + + Like :meth:`probe_dtm`, but ``0`` also where the 50-move rule draws + before the mate. - :raises: :exc:`MissingTableError` if the DTM50 can't be determined.""" + :raises: :exc:`MissingTableError` if the distance can't be determined. + """ r = self._require(board, rule50) if not r.has_dtm50: raise MissingTableError("DTM50 unavailable") return _signed(r.dtm50, r.dtm50_wdl) -def open_tablebase(directory: str, *, - block_cache_bytes: int = DEFAULT_BLOCK_CACHE_BYTES) -> Tablebase: - """Opens a directory tree of chesstb tables: ``wdl/``, ``dtz/``, - ``dtc/``, ``dtm/`` and ``dtm50/`` subdirectories, or the table files - directly in *directory*. See :class:`~chess.chesstb.Tablebase`. +def open_tablebase(directory: _StrPath, *, block_cache_bytes: int = _DEFAULT_BLOCK_CACHE_BYTES) -> Tablebase: + """ + Opens a collection of tables for probing. See + :class:`~chess.chesstb.Tablebase`. - :param block_cache_bytes: Bound of the LRU cache of decoded blocks.""" - return Tablebase(directory, block_cache_bytes=block_cache_bytes) + :param directory: Directory with tables, directly or in ``wdl``, + ``dtz``, ``dtc``, ``dtm`` and ``dtm50`` subdirectories. Use + :meth:`Tablebase.add_directory` for more. + :param block_cache_bytes: Bound of the cache of decompressed blocks. + """ + tables = Tablebase(block_cache_bytes=block_cache_bytes) + tables.add_directory(directory) + return tables diff --git a/docs/chesstb.rst b/docs/chesstb.rst index df20e8524..480f72236 100644 --- a/docs/chesstb.rst +++ b/docs/chesstb.rst @@ -2,21 +2,20 @@ chesstb endgame tablebase probing ================================== `chesstb `_ tablebases provide WDL -(win/draw/loss, with cursed and blessed results under the 50-move rule), DTZ -(distance to zeroing), DTC (pawn pushes still owed before a conversion, then -plies to the next zeroing move), DTM (distance to mate) and DTM50 (distance to -mate under the 50-move rule). Positions with castling rights have their own -tables, named with a lowercase ``r`` for each rook holding a right, as in -``KrK``. - -A chesstb DTZ is a plain distance in every WDL class; unlike Syzygy's, it -doesn't encode the base shift for cursed and blessed results. - -Tables are looked up in the ``wdl``, ``dtz``, ``dtc``, ``dtm`` and ``dtm50`` -subdirectories of each directory, or in the directory itself. Probes expect a -legal position and don't validate it: check untrusted input with -:func:`chess.Board.is_valid` first. `python-lz4 `_ -is used if installed, but isn't required. +(win/draw/loss), DTZ (distance to zeroing), DTC (distance to conversion, +counting pawn pushes separately), DTM (distance to mate) and DTM50 (distance +to mate under the 50-move rule) information for endgame positions, including +positions with castling rights. + +Distances are in plies, from the point of view of the side to move: positive +if it is winning, negative if it is losing, and ``0`` for a draw or a +checkmate on the board. DTC and DTM50 are probed at a halfmove clock, and are +``0`` where the 50-move rule draws. + +Probes expect a legal position: check untrusted input with +:func:`chess.Board.is_valid` first. +`python-lz4 `_ is used if installed, but isn't +required. .. warning:: Maliciously crafted tablebase files may cause denial of service. @@ -24,7 +23,7 @@ is used if installed, but isn't required. .. autofunction:: chess.chesstb.open_tablebase .. autoclass:: chess.chesstb.Tablebase - :members: probe_wdl, get_wdl, probe_dtz, get_dtz, probe_dtc, probe_dtm, get_dtm, probe_dtm50, probe, add_directory, close + :members: .. autoclass:: chess.chesstb.ProbeResult :members: diff --git a/test.py b/test.py index 400bc2bda..d8db3f762 100755 --- a/test.py +++ b/test.py @@ -9,6 +9,7 @@ import pathlib import platform import random +import shutil import sys import tempfile import textwrap @@ -6028,167 +6029,123 @@ def test_antichess_pgn(self): class ChesstbTestCase(unittest.TestCase): - def open_without_pack(self): - # A tablebase with the DTM50 pack out of the search path, which is how - # material shipping no pack is probed: the mate distance has to come - # from the standalone dtm/ table instead of the pack's flat layer. - tables = chess.chesstb.open_tablebase("data/chesstb") - tables.dirs["dtm50"].clear() - return tables - - # --- Table kinds and directory lookup. --- - - def test_table_kinds(self): - # One file class and one search subdirectory per kind. DTZ and DTM share - # one on-disk layout and so one reader (_RankFile); the value decode is - # the whole of what separates them, so it is asserted directly rather - # than through a probe that could pass for other reasons. DTC and DTM50 - # likewise share the changepoint container (_LayeredFile) and differ in - # what a record means, which the DTC tests below cover. - classes = [chess.chesstb.WDLFile, chess.chesstb.DTZFile, - chess.chesstb.DTCFile, chess.chesstb.DTMFile, - chess.chesstb.DTM50File] - self.assertEqual([c.KIND.lower() for c in classes], - list(chess.chesstb.Tablebase.KINDS)) - self.assertEqual(len({c.MAGIC for c in classes}), len(classes)) - self.assertEqual([c.EXT for c in classes], - [".lzw", ".lzdtz", ".lzdtc", ".lzdtm", ".lzdtm50"]) - # A stored 9 under a WIN: DTZ keeps the count, DTM doubles it and adds - # the ply the class implies. - self.assertEqual(chess.chesstb.dtz_value_from_storage(9, chess.chesstb.WIN, 1), (9, False)) - self.assertEqual(chess.chesstb.dtm_value_from_storage(9, chess.chesstb.WIN), 19) - self.assertEqual(chess.chesstb.dtm_value_from_storage(9, chess.chesstb.LOSE), 18) - # Cell width changes the DTZ decode and never the DTM one, which is why - # only one of the two reads it. A one-byte cursed cell reads back - # rounded. - self.assertEqual(chess.chesstb.dtz_value_from_storage(9, chess.chesstb.CURSED_WIN, 1), (17, True)) - self.assertEqual(chess.chesstb.dtz_value_from_storage(9, chess.chesstb.CURSED_WIN, 2), (9, False)) - - def test_search_directories(self): - with chess.chesstb.open_tablebase("data/chesstb") as tables: - # Every kind looks in its own subdirectory when there is one, else - # in the directory itself, so a flat dump of table files is also - # probeable. A directory already searched is not added again. - for kind in chess.chesstb.Tablebase.KINDS: - self.assertEqual(tables.dirs[kind], [os.path.join("data/chesstb", kind)]) - tables.add_directory("data") - tables.add_directory("data/") - tables.add_directory("data/chesstb") - for kind in chess.chesstb.Tablebase.KINDS: - self.assertEqual(tables.dirs[kind], [os.path.join("data/chesstb", kind), "data"]) - - # A directory holding no tables at all is not an error, just an absence. - with tempfile.TemporaryDirectory() as empty: - with chess.chesstb.open_tablebase(empty) as tables: - board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") - self.assertIsNone(tables.get_wdl(board)) - self.assertEqual(tables.probe(board).wdl, chess.chesstb.ILLEGAL) - - # --- What a probe answers, and in what convention. --- + def copy_tables(self, *kinds, flat=False): + # The test tables of the given kinds, in their subdirectories or all + # in one directory. + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + for kind in kinds: + target = directory.name if flat else os.path.join(directory.name, kind) + shutil.copytree(os.path.join("data", "chesstb", kind), target, dirs_exist_ok=True) + return pathlib.Path(directory.name) def test_probe(self): with chess.chesstb.open_tablebase("data/chesstb") as tables: - # KQK: mate distances and the signed WDL convention. board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") self.assertEqual(tables.probe_wdl(board), 2) self.assertEqual(tables.probe_dtz(board), 19) self.assertEqual(tables.probe_dtm(board), 19) self.assertEqual(tables.probe_dtm50(board), 19) + self.assertEqual(tables.probe_dtc(board), (0, 19)) board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 b - - 0 1") self.assertEqual(tables.probe_wdl(board), -2) self.assertEqual(tables.probe_dtz(board), -20) - self.assertEqual(tables.probe_dtm(board), -20) # signed: losing side + self.assertEqual(tables.probe_dtm(board), -20) self.assertEqual(tables.probe_dtm50(board), -20) - def test_case_insensitive_filesystem_does_not_swap_tables(self): - real_exists, real_open = os.path.exists, os.open + board = chess.Board("8/8/8/8/8/2k5/2N5/KB6 w - - 0 1") + self.assertEqual(tables.probe_wdl(board), 2) + self.assertEqual(tables.probe_dtm(board), 61) - def resolve(path): - directory, name = os.path.split(path) - try: - for entry in os.listdir(directory or "."): - if entry.lower() == name.lower(): - return os.path.join(directory, entry) - except OSError: - pass - return path + board = chess.Board("8/8/8/k7/8/8/K4P2/8 w - - 0 1") + self.assertEqual(tables.probe_dtc(board), (4, 23)) + self.assertEqual(tables.probe_dtm(board), 51) - os.path.exists = lambda p: real_exists(resolve(p)) - os.open = lambda p, *args, **kwargs: real_open(resolve(p), *args, **kwargs) - try: - with chess.chesstb.open_tablebase("data/chesstb") as tables: - board = chess.Board("4k3/8/8/8/8/8/8/R3K3 w Q - 0 1") - self.assertEqual(tables.probe(board).wdl, chess.chesstb.ILLEGAL) - board.set_castling_fen("-") - self.assertEqual(tables.probe_wdl(board), 2) - finally: - os.path.exists, os.open = real_exists, real_open + def test_probe_result(self): + with chess.chesstb.open_tablebase("data/chesstb") as tables: + board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") + self.assertEqual(tables.probe(board), chess.chesstb.ProbeResult( + wdl=2, wdl50=2, dtz=19, dtc=(0, 19), dtm=19, dtm50=19)) + + # The clock decides wdl50, dtc and dtm50. + board.halfmove_clock = 90 + result = chess.chesstb.ProbeResult(wdl=2, wdl50=0, dtz=19, dtc=(0, 0), dtm=19, dtm50=0) + self.assertEqual(tables.probe(board), result) + board.halfmove_clock = 0 + self.assertEqual(tables.probe(board, rule50=90), result) + self.assertEqual(tables.probe_dtm50(board, rule50=90), 0) + self.assertEqual(tables.probe_dtc(board, rule50=90), (0, 0)) - # --- The DTM50 pack, and the standalone DTM table it stands in for. --- + def test_missing_table(self): + with chess.chesstb.open_tablebase("data/chesstb") as tables: + board = chess.Board("7k/8/8/8/8/8/3QQQQ1/K7 w - - 0 1") + self.assertEqual(tables.probe(board), chess.chesstb.ProbeResult()) + with self.assertRaises(chess.chesstb.MissingTableError): + tables.probe_wdl(board) + with self.assertRaises(chess.chesstb.MissingTableError): + tables.probe_dtc(board) + self.assertIsNone(tables.get_wdl(board)) + self.assertIsNone(tables.get_dtz(board)) + self.assertEqual(tables.get_dtm(board, 0), 0) - def test_dtm_table_without_pack(self): - # Without the DTM50 pack the mate distance comes from the standalone - # dtm/ table, which must answer exactly what the pack does. - with self.open_without_pack() as tables: - board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") - self.assertEqual(tables.probe_dtm(board), 19) - # The whole mate fits the clock, so the pack is not needed. - self.assertEqual(tables.probe_dtm50(board), 19) - # DTZ still comes from its own table. + def test_directories(self): + board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") + + # Table files directly in the directory. + with chess.chesstb.open_tablebase(self.copy_tables("wdl", "dtz", flat=True)) as tables: + self.assertEqual(tables.probe_wdl(board), 2) self.assertEqual(tables.probe_dtz(board), 19) - # A DRAW is priced without opening the table at all. - self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/8/4k3/8/4P3/4K3 w - - 0 1")), 0) - # Each shipped dtm/ table drops one frame (KQK black, KBNK white), - # so the other side comes back the same way the pack's frames do. + + # No tables is not an error. + with chess.chesstb.open_tablebase(self.copy_tables()) as tables: + self.assertIsNone(tables.get_wdl(board)) + tables.add_directory("data/chesstb") + tables.add_directory("data/chesstb") + self.assertEqual(tables.probe_wdl(chess.Board("8/8/8/4k3/8/8/2R5/K7 w - - 0 1")), 2) + + def test_dtm_without_dtm50(self): + with chess.chesstb.open_tablebase(self.copy_tables("wdl", "dtz", "dtm")) as tables: + self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1")), 19) self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/5k2/8/8/1Q6/K7 b - - 0 1")), -20) self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/8/8/2k5/2N5/KB6 w - - 0 1")), 61) + # The whole mate fits the clock. + self.assertEqual(tables.probe_dtm50(chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1")), 19) - def test_dtm50_pack_preferred_over_dtm(self): - # The pack carries the flat DTM, which is what makes the dtm/ table - # redundant: with a pack on disk it must never be opened. - with chess.chesstb.open_tablebase("data/chesstb") as tables: - def fail(cfg): - self.fail("dtm/ opened while the DTM50 pack is available") - tables._open_dtm = fail - board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") - self.assertEqual(tables.probe_dtm(board), 19) - self.assertEqual(tables.probe_dtm50(board), 19) - - # --- The DTC pack: pushes owed, and the DTZ table it embeds. --- + def test_dtm_from_dtm50(self): + with chess.chesstb.open_tablebase(self.copy_tables("wdl", "dtm50")) as tables: + self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1")), 19) + self.assertEqual(tables.probe_dtm(chess.Board("8/8/8/5k2/8/8/1Q6/K7 b - - 0 1")), -20) - def test_dtc_missing_pack(self): - # A pawnful material with no pack has no DTC answer, and says so rather - # than standing in DTZ's number: the two are not the same metric. - with chess.chesstb.open_tablebase("data/chesstb") as tables: - tables.dirs["dtc"].clear() + def test_dtc_without_dtc(self): + with chess.chesstb.open_tablebase(self.copy_tables("wdl", "dtz", "dtm", "dtm50")) as tables: board = chess.Board("8/8/8/k7/8/8/K4P2/8 w - - 0 1") with self.assertRaises(chess.chesstb.MissingTableError): tables.probe_dtc(board) self.assertEqual(tables.probe_dtz(board), 19) - # --- Input the tables do not cover. --- - - def test_missing_table(self): - with chess.chesstb.open_tablebase("data/chesstb") as tables: - # Legal position whose material (KQQQQK) has no table on disk: the - # probes raise, and the get_* methods answer with a default. - board = chess.Board("7k/8/8/8/8/8/3QQQQ1/K7 w - - 0 1") - with self.assertRaises(chess.chesstb.MissingTableError): - tables.probe_wdl(board) + def test_case_insensitive_filesystem(self): + # The table for a castling right (KrK) must not be found as KRK. + directory = self.copy_tables("wdl") + if not os.path.exists(directory / "wdl" / "krk.lzw"): + self.skipTest("case-sensitive filesystem") + with chess.chesstb.open_tablebase(directory) as tables: + board = chess.Board("4k3/8/8/8/8/8/8/R3K3 w Q - 0 1") self.assertIsNone(tables.get_wdl(board)) - self.assertIsNone(tables.get_dtz(board)) - self.assertEqual(tables.get_dtm(board, "none"), "none") + board.castling_rights = chess.BB_EMPTY + self.assertEqual(tables.probe_wdl(board), 2) - # --- Sharing one Tablebase between threads. --- + def test_close(self): + board = chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1") + tables = chess.chesstb.open_tablebase("data/chesstb") + result = tables.probe(board) + tables.close() + self.assertEqual(tables.probe(board), result) + tables.close() def test_concurrent_probe(self): - # Threads sharing one Tablebase must agree with a single-threaded - # reference. The barrier puts them all on the *first* open of these - # five materials at once (the lazy-open race), and the 1-byte block - # budget makes eviction race decoding on essentially every probe. - # KRKR is left out on purpose: under that budget its blocks re-decode - # per probe at ~100 ms a go, and test_dropped_frame_symmetric covers it. + # The barrier puts all threads on the first open of these tables at + # once, and the 1-byte cache makes eviction race decoding. queries = [ ("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1", 0), ("8/8/8/5k2/8/8/1Q6/K7 b - - 0 1", 0), @@ -6200,8 +6157,7 @@ def test_concurrent_probe(self): ] def answers(tables): - return [tables.probe(chess.Board(fen), rule50).__repr__() - for fen, rule50 in queries] + return [tables.probe(chess.Board(fen), rule50) for fen, rule50 in queries] with chess.chesstb.open_tablebase("data/chesstb") as tables: expected = answers(tables) @@ -6229,40 +6185,6 @@ def worker(i): for got in results: self.assertEqual(got, expected) - def test_close_waits_for_probes(self): - # close() unmaps files and releases the views into them, so it must - # block until in-flight probes are done. Asserted on the read-count - # registration directly -- a thread standing in for a probe that is - # mid-read -- so the ordering is checked rather than raced for. - tables = chess.chesstb.open_tablebase("data/chesstb") - tables.probe(chess.Board("8/8/8/5k2/8/8/1Q6/K7 w - - 0 1")) # warm and mapped - - registered = threading.Event() - may_finish = threading.Event() - closed = threading.Event() - - def in_flight_probe(): - with tables._read_condition: - tables._read_count += 1 - registered.set() - may_finish.wait(timeout=30) - with tables._read_condition: - tables._read_count -= 1 - tables._read_condition.notify_all() - - reader = threading.Thread(target=in_flight_probe) - reader.start() - self.assertTrue(registered.wait(timeout=30)) - - closer = threading.Thread(target=lambda: (tables.close(), closed.set())) - closer.start() - self.assertFalse(closed.wait(timeout=0.05), "close() did not wait for the probe") - may_finish.set() - self.assertTrue(closed.wait(timeout=30), "close() did not resume") - - reader.join(timeout=30) - closer.join(timeout=30) - self.assertEqual([t.name for t in (reader, closer) if t.is_alive()], []) if __name__ == "__main__": verbosity = sum(arg.count("v") for arg in sys.argv if all(c == "v" for c in arg.lstrip("-")))