### Define Schema Manifest Structure Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/features.md Example of the schema manifest structure defining groups with names, versions, widths, and offsets. ```toml schema_semver = "0.1.0" groups = [ { name = "state", version = 1, width = 29, offset = 0 }, { name = "material", version = 1, width = 26, offset = 29 }, ... ] schema_id = "a40a02ef18e4219b754d0f32410d803f" # 128-bit, hex ``` -------------------------------- ### Install esca Python package Source: https://github.com/anglerfishchess/anglerfish/blob/main/rs_anglerfish/esca/README.md Install the esca package using pip. ```sh pip install esca ``` -------------------------------- ### Run production training session Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/training.md Executes a full-scale training run with specified checkpoint output. ```bash uv run python -m pyanglerfish.train \ --dump data-external/lichess_db_eval.jsonl.zst \ --min-depth 20 --steps 200000 --batch-size 1024 \ --eval-every 2000 --checkpoint runs/v0.pt ``` -------------------------------- ### Python Development Commands Source: https://github.com/anglerfishchess/anglerfish/blob/main/README.md Commands for setting up the Python environment and running quality checks. ```sh uv sync --all-groups uv run pytest uvx ruff check . uvx ruff format --check . uvx pyrefly check ``` -------------------------------- ### Initialize and Interact with Esca Games Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Demonstrates basic game initialization, move execution, and state inspection using the Python API. ```python import esca import numpy as np esca.CLASSIC # Variant esca.CHESS960 esca.US, esca.THEM # 0 and 1, the index of a side-paired fact # Game — variant defaults to classic everywhere it is optional g = esca.Game() g = esca.Game(variant=esca.CHESS960, seed=518) g = esca.Game.from_fen(fen, variant=esca.CHESS960) g.castling_output = esca.KING_TO_ROOK # or esca.KING_TWO_SQUARES g.play("e2e4") # UCI or a Move g.play_san("Nf3") g.move_to_uci(mv) g.undo() g.position # Position, immutable and hashable g.moves # list[Move] played g.legal_moves() # list[Move] g.annotated_moves() # list[AnnotatedMove] g.outcome() # "checkmate", "stalemate", … or None g.claims() # ["threefold_repetition", …] print(g.position.summary()) # Position on its own; rules come from the variant argument p = esca.Position.from_fen(fen) p.fen, p.epd, p.side_to_move, p.en_passant, p.in_check # str, str, "w", "e6", bool p.piece_at("e1") # "K" f = p.facts(esca.CLASSIC) f = g.facts() # variant taken from the game f.side("b") # esca.US or esca.THEM, whichever Black plays f.pawns.passed[esca.US] # SquareSet list(f.attacks.hanging[esca.THEM]) # ["e5", …] f.king.ring_attack_weight[esca.US] print(f.summary()) # Schema and batch encoding esca.SCHEMA_V0 # Schema esca.SCHEMA_ID # "b8d5…", 32 hex chars esca.WIDTH # 1065 esca.MOVE_WIDTH # 24 esca.schema() # [{"name", "version", "width", "offset"}, …] esca.features_for(esca.CHESS960) # [("state", "in_check"), …] # (n, w) float32 x = esca.encode(fens, variant=esca.CHESS960, groups=["state", "pawns"]) esca.encode_into(fens, out, groups=["state", "pawns"]) # caller's array moves, mx = esca.encode_moves(fen) # list[Move], (m, 24) moves, mx, cuts = esca.encode_moves(fens) # per FEN, (total, 24), (n + 1,) int64 # Lichess dump for batch in esca.lichess.batches(path, batch_size=8192, min_depth=20): batch.fens, batch.features, batch.cp, batch.mate, batch.best_moves ``` -------------------------------- ### Run smoke training session Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/training.md Executes a short training run on a CPU for testing purposes. ```bash uv run python -m pyanglerfish.train \ --dump data-external/lichess_db_eval.jsonl.zst \ --max-rows 20000 --steps 20 --batch-size 256 \ --eval-every 10 --eval-batches 4 --log-every 5 ``` -------------------------------- ### Dependency Graph Visualization Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/architecture.md A visual representation of the crate dependencies and feature flags within the Anglerfish project. ```text cozy-chess (MIT) pyo3, numpy, zstd, serde_json | rayon (feature | (feature python) lichess) | | | +───────────── esca ──────────────+ | anglerfish-core | anglerfish-nn (phase 2) ``` -------------------------------- ### Train the Neural Network Source: https://github.com/anglerfishchess/anglerfish/blob/main/README.md Command to access the training module help documentation. ```sh uv run python -m pyanglerfish.train --help ``` -------------------------------- ### Rust Development Commands Source: https://github.com/anglerfishchess/anglerfish/blob/main/README.md Commands for building, testing, and linting the Rust workspace. ```sh cd rs_anglerfish cargo build --release cargo test cargo fmt --check cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### Analyze chess positions in Rust Source: https://github.com/anglerfishchess/anglerfish/blob/main/rs_anglerfish/esca/README.md Initialize a game, play moves, and extract position facts for neural network encoding. ```rust use esca::{Game, Schema, Side, classic}; let mut game = Game::new(classic()); // Chess960 rules: `esca::chess960()` game.play_san("e4").unwrap(); game.play_uci("e7e5").unwrap(); println!("{}", game.position().fen()); let facts = game.facts(); // side-relative, in the mover's view println!("{}", facts.tactics[Side::Us.index()].legal_move_count); println!("{}", facts.summary()); let schema = Schema::v0(); // the row a net eats: 1065 f32 println!("{}", facts.encode(schema, schema.all()).len()); ``` -------------------------------- ### Analyze chess positions in Python Source: https://github.com/anglerfishchess/anglerfish/blob/main/rs_anglerfish/esca/README.md Initialize a game, play moves, and encode position data for neural network consumption. ```python import esca game = esca.Game() # Chess960 rules: esca.Game(variant=esca.CHESS960) game.play_san("e4") game.play("e7e5") print(game.position.fen) facts = game.facts() # side-relative: index with esca.US / esca.THEM print(facts.tactics[esca.US].legal_move_count) print(facts.summary()) rows = esca.encode([game.position.fen]) # (1, 1065) float32, ready for a net print(rows.shape, esca.SCHEMA_ID) ``` -------------------------------- ### Run UCI Test Suite Source: https://github.com/anglerfishchess/anglerfish/blob/main/README.md Command to verify engine protocol conformance using the UCI test suite. ```sh uvx uci-test-suite ./target/release/anglerfish ``` -------------------------------- ### Project Layout Source: https://github.com/anglerfishchess/anglerfish/blob/main/README.md Directory structure of the Anglerfish repository. ```text pyanglerfish/ trainer, data tooling, CLI (Python) tests/ tests for the Python side rs_anglerfish/ Cargo workspace (Rust) esca/ chess model, position facts, the wheel (published) anglerfish-core/ engine: UCI, search, evaluator interface docs/ architecture, the esca API, the feature schema data-external/ the Lichess dump; gitignored, symlinked in worktrees ``` -------------------------------- ### Configure local editable dependencies in pyproject.toml Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/architecture.md Use this configuration to link the local esca crate as an editable dependency within the anglerfish project. ```toml [project] dependencies = ["esca", …] [tool.uv.sources] esca = { path = "rs_anglerfish/esca", editable = true } ``` -------------------------------- ### Repository directory structure Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/architecture.md Visual representation of the project's file hierarchy, showing the separation between Python and Rust components. ```text anglerfish/ pyproject.toml hatchling, the pure-Python side pyanglerfish/ the trainer: data, scale, model, train (training.md) rs_anglerfish/ Cargo workspace root Cargo.toml [workspace] members esca/ chess model + position facts + wheel (public) anglerfish-core/ engine: search, UCI, evaluator trait (internal) anglerfish-nn/ net loading and forward pass (internal, phase 2) data-external/ the Lichess dump, gitignored, symlinked in worktrees docs/ ``` -------------------------------- ### Implement a new chess variant Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Demonstrates the structure required to implement the Variant trait for custom chess variants. ```rust pub struct Horde; impl Variant for Horde { fn name(&self) -> &'static str { "horde" } fn start_position(&self, _seed: u64) -> Position { /* … */ } fn legal_moves(&self, pos: &Position, out: &mut MoveList) { /* … */ } fn play(&self, pos: &Position, mv: Move) -> Position { /* … */ } fn outcome(&self, pos: &Position) -> Option { /* … also "no units left" */ } /* … */ } let game = Game::new(Arc::new(Horde)); let facts = game.facts(); // unchanged code let defined = Schema::v0().features_for(game.variant()); ``` -------------------------------- ### Encoding Function Signatures Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Reference for the keyword-only arguments and return types for encoding functions. ```python esca.encode(fens, *, variant=..., schema=..., groups=None) -> np.ndarray esca.encode_into(fens, out, *, variant=..., schema=..., groups=None) -> None esca.encode_moves(fen, *, variant=...) -> tuple[list[Move], np.ndarray] esca.encode_moves(fens, *, variant=...) -> tuple[list[list[Move]], np.ndarray, np.ndarray] esca.lichess.batches(path, *, batch_size=8192, min_depth=0, variant=..., schema=..., groups=None) -> Iterator[Batch] ``` -------------------------------- ### Data flow architecture Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/training.md Visual representation of the data pipeline from raw Lichess JSONL files to the final tensor dictionary used for training. ```text lichess_db_eval.jsonl.zst └─ esca.lichess.batches(path, min_depth=…, groups=…) Rust: zstd, JSON, │ position encoding │ fens, features (n, w), cp (n,), mate (n,), best_moves ▼ pyanglerfish.data.EvalBatches │ esca.encode_moves(fens) → per FEN the legal moves, their rows │ stacked (total, 24), and the cuts (n + 1,) │ move_index(moves, best_move) → the policy target │ win_probability(cp, mate, scale) → the value target ▼ dict of tensors: features (b, w), moves (b, m, 24), move_mask (b, m), best (b,), value (b,) ``` -------------------------------- ### Position and State Management API Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Defines the core Position structure, Zobrist keys, scoring, and castling rights for managing chess board states. ```rust #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Position { /* … */ } impl Position { /// Six-field FEN; also accepts a four-field FEN (EPD), taking /// halfmove clock 0, full move 1, and marking the clocks unknown. pub fn from_fen(fen: &str) -> Result; pub fn fen(&self) -> String; pub fn epd(&self) -> String; pub fn side_to_move(&self) -> Colour; pub fn piece_at(&self, sq: Square) -> Option; pub fn by_role(&self, role: Role) -> SquareSet; pub fn by_colour(&self, colour: Colour) -> SquareSet; pub fn by_piece(&self, piece: Piece) -> SquareSet; pub fn occupied(&self) -> SquareSet; pub fn king_of(&self, colour: Colour) -> Square; pub fn castling_rights(&self) -> CastlingRights; pub fn en_passant(&self) -> Option; pub fn in_check(&self) -> bool; pub fn halfmove_clock(&self) -> u32; pub fn fullmove_number(&self) -> u32; /// False when the position came from a four-field FEN. pub fn clocks_known(&self) -> bool; /// Zobrist key: equal for equal placement, side, castling rights and /// en-passant square; independent of the clocks. Valid as an identity /// within one process run — not across runs, and not stored. pub fn key(&self) -> Key; /// Facts of this position under `variant`. pub fn facts(&self, variant: &dyn Variant) -> Facts; /// Same, reusing buffers; no allocation. pub fn facts_in(&self, variant: &dyn Variant, scratch: &mut Scratch) -> Facts; /// Colours swapped and ranks flipped. pub fn mirrored(&self) -> Position; /// Board, side to move and state, for a human reader. Text not stable. pub fn summary(&self) -> String; } /// A Zobrist key. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Key(u64); impl Key { pub fn get(self) -> u64; } /// An evaluation of a position. Positive favours the side to move; `Mate(n)` /// is a forced mate in *n* moves, negative when it is against the side to move. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Score { Cp(i32), Mate(i32) } /// Chess960-compatible: each right names the rook's starting file. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct CastlingRights { /* [[Option; 2]; 2] */ } impl CastlingRights { pub fn short(&self, colour: Colour) -> Option; pub fn long(&self, colour: Colour) -> Option; pub fn any(&self, colour: Colour) -> bool; /// `KQkq` when the rook files are the classic ones, `AHah` otherwise. pub fn to_fen_field(&self) -> String; } ``` -------------------------------- ### Read Lichess evaluation dumps Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Provides structures and functions for streaming Zstandard-compressed JSON-lines evaluation dumps. ```rust pub mod lichess { pub struct Record { pub epd: String, pub evals: Vec } pub struct Eval { pub depth: u32, pub knodes: u64, pub pvs: Vec } pub struct Pv { pub score: Score, pub line: String } impl Record { /// The four-field FEN parsed; `clocks_known()` is false. pub fn position(&self) -> Result; } impl Pv { pub fn best_move(&self, variant: &dyn Variant, pos: &Position) -> Result; } /// Streams a Zstandard-compressed JSON-lines dump; never holds the file. pub fn read(path: &Path) -> io::Result> + use<>>; /// Streams decompressed JSON lines; blank ones are skipped. pub fn read_from(reader: R) -> impl Iterator>; } ``` -------------------------------- ### Move and MoveList Structures Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Defines the Move structure for representing chess moves and the MoveList structure for managing collections of moves without heap allocation. ```rust #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Move { /* from, to, promotion, kind */ } impl Move { pub fn from(&self) -> Square; /// For castling, the rook's square: unambiguous in every variant. pub fn to(&self) -> Square; pub fn promotion(&self) -> Option; pub fn kind(&self) -> MoveKind; pub fn is_capture(&self) -> bool; pub fn is_castling(&self) -> bool; pub fn is_en_passant(&self) -> bool; } /// `kind` is the first case that applies, in the order castling, en passant, /// promotion, capture, quiet; `is_capture` is true for a capturing promotion /// and for en passant as well. pub enum MoveKind { Quiet, Capture, EnPassant, Castling, Promotion } /// Inline storage for the largest legal move count; never allocates. pub struct MoveList { /* … */ } impl MoveList { pub fn new() -> MoveList; pub fn clear(&mut self); pub fn push(&mut self, item: T); pub fn as_slice(&self) -> &[T]; pub fn len(&self) -> usize; pub fn is_empty(&self) -> bool; } ``` -------------------------------- ### esca.lichess.batches Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Utility for processing Lichess data dumps into batches. ```APIDOC ## esca.lichess.batches ### Description Iterates over Lichess data files, yielding Batch objects containing FENs, features, centipawn evaluations, and best moves. ### Parameters - `path` (str) - Required - Path to the Lichess data file. - `batch_size` (int) - Optional - Number of rows per batch (default 8192). - `min_depth` (int) - Optional - Minimum search depth for included records (default 0). ``` -------------------------------- ### Schema ID Hash Format Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/features.md The format used for generating the BLAKE3 hash for schema identification. ```text ::\n ::\n (for each feature, in order) ``` -------------------------------- ### Game State Management Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md The Game structure manages the variant, history, and current position, providing methods for move execution and game state analysis. ```rust pub struct Game { /* … */ } impl Game { /// `variant.start_position(0)`. pub fn new(variant: Arc) -> Game; pub fn with_seed(variant: Arc, seed: u64) -> Game; pub fn from_position(variant: Arc, start: Position) -> Result; pub fn from_fen(variant: Arc, fen: &str) -> Result; pub fn variant(&self) -> &dyn Variant; /// Castling spelling for this game's UCI output; `KingToRook` until set. pub fn castling_output(&self) -> CastlingOutput; pub fn set_castling_output(&mut self, style: CastlingOutput); pub fn move_to_uci(&self, mv: Move) -> String; pub fn move_to_san(&self, mv: Move) -> String; pub fn position(&self) -> &Position; pub fn start_position(&self) -> &Position; pub fn moves(&self) -> &[Move]; /// Every position from the start to the current one. pub fn positions(&self) -> impl Iterator; pub fn ply(&self) -> u32; pub fn legal_moves(&self) -> MoveList; pub fn annotated_moves(&self) -> MoveList; pub fn play(&mut self, mv: Move) -> Result<(), IllegalMove>; pub fn play_uci(&mut self, text: &str) -> Result<(), MoveParseError>; pub fn play_san(&mut self, text: &str) -> Result<(), MoveParseError>; pub fn undo(&mut self) -> Option; /// Automatic terminal conditions, repetition included. pub fn outcome(&self) -> Option; /// Draws a player could claim now, in no particular order. pub fn claims(&self) -> &[DrawClaim]; /// How often the current position has occurred in this game. pub fn repetitions(&self) -> u32; pub fn facts(&self) -> Facts; pub fn facts_in(&self, scratch: &mut Scratch) -> Facts; } ``` -------------------------------- ### Manage Feature Sets and Encode Facts Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Methods for querying feature sets and encoding facts or move facts into buffers. ```rust /// A subset of a schema's features. pub struct FeatureSet { /* … */ } impl FeatureSet { pub fn contains(&self, group: &str, feature: &str) -> bool; pub fn names(&self) -> impl Iterator; } impl Facts { /// Writes the selected groups in schema order; returns values written. /// A feature not defined for the facts' variant is written as zeros, so /// widths and offsets do not depend on the variant. /// Panics if `out` is shorter than `schema.width_of(groups)`. pub fn encode_into(&self, schema: &Schema, groups: GroupSet, out: &mut [f32]) -> usize; pub fn encode(&self, schema: &Schema, groups: GroupSet) -> Vec; } impl MoveFacts { pub const WIDTH: usize = 24; /// Panics if `out` is shorter than `WIDTH`. pub fn encode_into(&self, out: &mut [f32]); } ``` -------------------------------- ### lichess::read Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Streams a Zstandard-compressed JSON-lines dump from a file path. This function returns an iterator over Record objects and does not load the entire file into memory. ```APIDOC ## fn lichess::read ### Description Streams a Zstandard-compressed JSON-lines dump from the specified file path. It returns an iterator that yields `io::Result` items. ### Signature `pub fn read(path: &Path) -> io::Result> + use<>>` ### Parameters - **path** (&Path) - Required - The filesystem path to the Zstandard-compressed JSON-lines file. ``` -------------------------------- ### Define Facts and Side structures Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Core structures for representing chess position facts and side-specific indexing. ```rust pub enum Side { Us, Them } impl Side { pub const ALL: [Side; 2]; /// 0 for us, 1 for them. pub const fn index(self) -> usize; } pub struct Facts { pub state: StateFacts, pub material: MaterialFacts, pub pawns: PawnFacts, pub pieces: PieceFacts, pub king: KingFacts, pub mobility: MobilityFacts, pub attacks: AttackFacts, pub tactics: [TacticsFacts; 2], pub planes: PlaneFacts, pub moves: MoveList, } pub struct PawnFacts { pub pawns: [SquareSet; 2], pub passed: [SquareSet; 2], pub candidates: [SquareSet; 2], pub doubled: [SquareSet; 2], pub isolated: [SquareSet; 2], pub backward: [SquareSet; 2], pub defended: [SquareSet; 2], pub count_by_file: [[u8; 8]; 2], pub count_by_rank: [[u8; 8]; 2], pub open_files: FileSet, pub semi_open_files: [FileSet; 2], pub islands: [u8; 2], pub levers: [u8; 2], pub rams: u8, pub passer_lead_rank: [Option; 2], pub passer_protected: [u8; 2], pub passers_connected: [bool; 2], pub passer_unstoppable: [bool; 2], } pub struct AttackFacts { pub by: [SquareSet; 2], pub by_pawns: [SquareSet; 2], pub by_role: [[SquareSet; 6]; 2], pub hanging: [SquareSet; 2], pub en_prise: [SquareSet; 2], pub pinned: [SquareSet; 2], pub defended: [SquareSet; 2], pub hanging_value: [i32; 2], pub en_prise_max_value: [i32; 2], pub skewer_candidates: [u8; 2], /* the placement the sets were read from */ } impl AttackFacts { pub fn attackers_of(&self, sq: Square, side: Side) -> SquareSet; pub fn is_hanging(&self, sq: Square) -> bool; pub fn units(&self, side: Side) -> SquareSet; } pub struct AnnotatedMove { pub mv: Move, pub facts: MoveFacts, } pub struct MoveFacts { pub victim: Option, pub mover: Role, pub promotion: Option, pub gives_check: bool, pub gives_safe_check: bool, pub is_safe: bool, pub captures_hanging: bool, pub escapes_attack: bool, pub to_attacked_by_pawn: bool, pub is_castling: bool, pub is_en_passant: bool, } impl Facts { /// The variant the facts were computed under. pub fn variant(&self) -> &'static str; /// The colour that plays `Side::Us`. pub fn side_to_move(&self) -> Colour; /// The side `colour` plays: the index into every side-paired fact. pub fn side(&self, colour: Colour) -> Side; /// A page of prose: material, structure, king safety, threats. Text not stable. pub fn summary(&self) -> String; } /// The `available`/`count` fields of a `TacticsFacts` carry the numbers; the /// schema's `*_available` and `only_moves` bits are predicates over them. impl TacticsFacts { pub fn check_available(&self) -> bool; pub fn safe_check_available(&self) -> bool; pub fn promotion_available(&self) -> bool; pub fn safe_promotion_available(&self) -> bool; pub fn capture_available(&self) -> bool; pub fn fork_available(&self) -> bool; pub fn pin_creation_available(&self) -> bool; pub fn only_moves(&self) -> bool; } /// Reusable buffers. One per thread; a search keeps one per node stack. pub struct Scratch { /* … */ } impl Scratch { pub fn new() -> Scratch; } ``` -------------------------------- ### Add esca dependency in Rust Source: https://github.com/anglerfishchess/anglerfish/blob/main/rs_anglerfish/esca/README.md Include the esca crate in your Cargo.toml file. ```toml [dependencies] esca = "0.1" ``` -------------------------------- ### Define ESCA Schema and Feature Structures Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Core structures for defining schemas, groups, and individual feature specifications. ```rust pub struct Schema { /* groups, versions, widths, offsets */ } pub struct GroupSet(u16); pub struct SchemaId([u8; 16]); impl Schema { /// The v0 schema of `features.md`: 9 groups, 1065 values. pub fn v0() -> &'static Schema; pub fn id(&self) -> SchemaId; pub fn semver(&self) -> &str; pub fn width(&self) -> usize; pub fn width_of(&self, groups: GroupSet) -> usize; pub fn groups(&self) -> &[GroupSpec]; pub fn group(&self, name: &str) -> Option<&GroupSpec>; /// The canonical text `id` hashes. pub fn canonical(&self) -> String; pub fn all(&self) -> GroupSet; /// Where a group sits in the schema order. pub fn group_index(&self, name: &str) -> Option; /// The named groups; `None` when a name is not the schema's. pub fn group_set(&self, names: &[&str]) -> Option; pub fn feature_count(&self) -> usize; /// The features whose definitions hold under `variant`. pub fn features_for(&'static self, variant: &dyn Variant) -> FeatureSet; } impl GroupSet { pub const EMPTY: GroupSet; pub const fn only(index: usize) -> GroupSet; pub const fn contains(self, index: usize) -> bool; pub fn insert(&mut self, index: usize); pub fn remove(&mut self, index: usize); pub const fn is_empty(self) -> bool; pub const fn len(self) -> u32; } impl SchemaId { pub const fn bytes(self) -> [u8; 16]; } pub struct GroupSpec { pub name: &'static str, pub version: u16, pub width: usize, pub features: &'static [FeatureSpec], } pub struct FeatureSpec { pub name: &'static str, /// Within the group, in values. pub offset: usize, pub width: usize, /// The encoding kind and scale, as `features.md` §6 spells it. pub encoding: &'static str, /// Variant names the feature is defined for; empty means all of them. pub variants: &'static [&'static str], } impl FeatureSpec { pub fn defined_for(&self, variant_name: &str) -> bool; } ``` -------------------------------- ### Neural Network Architecture and Policy Head Logic Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/training.md Visual representation of the network flow and the mathematical definition of the policy head calculation. ```text features (w) ─ Linear·ReLU × trunk ─ Linear·ReLU ─ embedding (e) ├─ Linear → value logit └─ policy moves (m, 24) ────────────────────────────────────────┘ policy: relu(W_e·embedding + W_m·move) · w → one score per move, −inf where the move is padding, softmax over the legal moves ``` -------------------------------- ### Encode Positions and FENs Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Utility functions for batch encoding chess positions or FEN strings into buffers. ```rust /// One row per position, row-major, into `out` of `positions.len() * width`. pub fn encode_positions( variant: &dyn Variant, positions: &[Position], schema: &Schema, groups: GroupSet, out: &mut [f32], ); /// As above from FEN text; the error names the offending row. pub fn encode_fens( variant: &dyn Variant, fens: &[&str], schema: &Schema, groups: GroupSet, out: &mut [f32], ) -> Result<(), RowError>; pub struct RowError { pub row: usize, pub source: FenError } ``` -------------------------------- ### lichess::read_from Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Streams decompressed JSON lines from a buffered reader. Blank lines are automatically skipped. ```APIDOC ## fn lichess::read_from ### Description Streams decompressed JSON lines from a provided `BufRead` source. Returns an iterator over `io::Result`. ### Signature `pub fn read_from(reader: R) -> impl Iterator>` ### Parameters - **reader** (R: BufRead) - Required - The buffered reader source containing the JSON lines. ``` -------------------------------- ### Define Variant Trait and Castling Output Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md The Variant trait defines the rules for a specific chess variant, while CastlingOutput specifies UCI formatting preferences. ```rust pub trait Variant: Send + Sync + 'static { /// Stable identifier, lower-case, as used in PGN and UCI: "chess", "chess960". fn name(&self) -> &'static str; /// A position to start a game from. `Classic` ignores the seed and /// returns the standard array; `Chess960` returns arrangement /// `seed % 960`. fn start_position(&self, seed: u64) -> Position; /// Appends every legal move in `pos` to `out`. fn legal_moves(&self, pos: &Position, out: &mut MoveList); fn is_legal(&self, pos: &Position, mv: Move) -> bool; /// The position after `mv`. Panics if `mv` is not legal in `pos`. fn play(&self, pos: &Position, mv: Move) -> Position; /// Terminal state of `pos` judged from the position alone: checkmate, /// stalemate, insufficient material, and the automatic move-count draw. /// Repetition and claimable draws need history and belong to `Game`. fn outcome(&self, pos: &Position) -> Option; fn promotion_roles(&self) -> &'static [Role]; /// Whether `pos` is a position this variant can reach and play on. fn validate(&self, pos: &Position) -> Result<(), PositionError>; /// Castling is written as `style` asks; every other move is unaffected. fn move_to_uci(&self, pos: &Position, mv: Move, style: CastlingOutput) -> String; /// Accepts both castling spellings whatever the output style. fn move_from_uci(&self, pos: &Position, text: &str) -> Result; fn move_to_san(&self, pos: &Position, mv: Move) -> String; fn move_from_san(&self, pos: &Position, text: &str) -> Result; } /// How castling is spelled in UCI text. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum CastlingOutput { /// `e1h1`. Correct in every variant. #[default] KingToRook, /// `e1g1`. Classic geometry only, and `Chess960` writes king-to-rook /// whatever the style asks for: a two-square destination there can be /// another legal king move, or the king's own origin. KingTwoSquares, } pub struct Classic; pub struct Chess960; pub static CLASSIC: Classic = Classic; pub static CHESS960: Chess960 = Chess960; /// `Classic`, shared. The default wherever a variant is optional. pub fn classic() -> Arc; pub fn chess960() -> Arc; ``` -------------------------------- ### Variant Accessors Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Functions to retrieve shared instances of supported chess variants. ```APIDOC ## Variant Accessors ### Description Use these functions to obtain an `Arc` instance for the desired ruleset. ### Functions - `classic() -> Arc`: Returns the Classic chess variant. - `chess960() -> Arc`: Returns the Chess960 variant. ``` -------------------------------- ### Error Types Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Enumerations for handling FEN parsing, position validation, and move parsing errors, all implementing Copy, Display, and std::error::Error. ```rust pub enum FenError { FieldCount, Placement, SideToMove, Castling, EnPassant, HalfmoveClock, FullmoveNumber, /// The placement is not a legal chess position. Position, } /// Why a position is not one a variant can play on. pub enum PositionError { CastlingRights } pub enum MoveParseError { /// Not shaped like a move at all. Syntax, /// Well formed, but names no legal move here. Illegal, /// Names more than one legal move. Ambiguous, } pub struct IllegalMove; ``` -------------------------------- ### esca.encode Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Functions for encoding chess positions and moves into numpy arrays for machine learning. ```APIDOC ## Encoding Functions ### Description High-performance functions to encode FEN strings into float32 numpy arrays. These functions release the GIL and parallelize processing. ### Methods - `esca.encode(fens, *, variant=esca.CLASSIC, schema=esca.SCHEMA_V0, groups=None) -> np.ndarray` - `esca.encode_moves(fen, *, variant=esca.CLASSIC) -> tuple[list[Move], np.ndarray]` - `esca.encode_moves(fens, *, variant=esca.CLASSIC) -> tuple[list[list[Move]], np.ndarray, np.ndarray]` ``` -------------------------------- ### esca.Game Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md The Game class manages the state of a chess game, supporting variant selection, move execution, and state inspection. ```APIDOC ## Game Class ### Description Represents a chess game instance. Supports classic and Chess960 variants, move playback, and state retrieval. ### Methods - `Game(variant=esca.CLASSIC, seed=None)`: Initialize a new game. - `Game.from_fen(fen, variant=esca.CLASSIC)`: Initialize a game from a FEN string. - `play(move)`: Play a move in UCI format or as a Move object. - `play_san(san)`: Play a move in SAN format. - `undo()`: Undo the last move. - `legal_moves()`: Returns a list of legal moves. - `outcome()`: Returns the game outcome (e.g., 'checkmate', 'stalemate'). ``` -------------------------------- ### Define Game Outcomes and Draw Claims Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md Enumerations representing terminal game states and types of draw claims. ```rust pub enum Outcome { Checkmate { winner: Colour }, Stalemate, InsufficientMaterial, SeventyFiveMoves, FivefoldRepetition, } pub enum DrawClaim { FiftyMoves, ThreefoldRepetition } ``` -------------------------------- ### Variant Trait Source: https://github.com/anglerfishchess/anglerfish/blob/main/docs/esca-api.md The Variant trait defines the rules for a specific chess variant. Implementations provide methods for move generation, position validation, and UCI/SAN move parsing. ```APIDOC ## Variant Trait ### Description The `Variant` trait is the core interface for defining chess rules. It provides methods to interact with positions, generate legal moves, and handle move notation. ### Methods - `name() -> &'static str`: Returns the stable identifier (e.g., "chess", "chess960"). - `start_position(seed: u64) -> Position`: Returns the starting position for the variant. - `legal_moves(pos: &Position, out: &mut MoveList)`: Appends all legal moves in the given position to the provided list. - `is_legal(pos: &Position, mv: Move) -> bool`: Checks if a move is legal in the given position. - `play(pos: &Position, mv: Move) -> Position`: Returns the position resulting from the move. - `outcome(pos: &Position) -> Option`: Returns the terminal state of the position if applicable. - `validate(pos: &Position) -> Result<(), PositionError>`: Validates if the position is reachable in this variant. - `move_to_uci(pos: &Position, mv: Move, style: CastlingOutput) -> String`: Converts a move to UCI notation. - `move_from_uci(pos: &Position, text: &str) -> Result`: Parses a move from UCI notation. - `move_to_san(pos: &Position, mv: Move) -> String`: Converts a move to SAN notation. - `move_from_san(pos: &Position, text: &str) -> Result`: Parses a move from SAN notation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.