chmengine.utils¶
Utilities for engine evaluation and scoring logic.
Functions
|
Compute a score for a board state based on heatmap control and king box pressure. |
|
Evaluate the board from a White-minus-Black perspective using heatmap evaluation. |
|
Return a large signed score for checkmate results. |
|
Format a list of (move, score) tuples into UCI strings and formatted scores. |
Compute the list of squares surrounding each king on the board. |
|
Insert a new candidate move into the current player's move list (best to worst). |
|
|
Insert a new candidate move into the opponent's response list (worst to best). |
|
Insert a move into a list of moves sorted from best to worst. |
|
Insert a move into a list of moves sorted from worst to best. |
|
Check if a game result is a draw based on the winner field. |
|
Check if a square is valid for inclusion in a king's bounding box. |
|
Initialize a tuple of target move lists with null entries. |
|
Return the number of pieces on the board |
Return the number of pieces on the board represented by fen. |
|
|
Sets all datetime related game headers for the pgn file. |
|
Sets UTC header info of pgn file data from local timestamp |
- class chmengine.utils.Pick(move: Move, score: Number)¶
Bases:
PickT
Fully featured container for a (move, score) pair.
This class provides tuple-like access, type casting, and rich formatting. It extends PickT and is the public-facing API for move-score pairs.
- Attributes:
- move_getter_keysTuple[int, str, int]
Allowed keys to access the move.
- score_getter_keysTuple[int, str, int]
Allowed keys to access the score.
- property data: Tuple[Move, float64]¶
Read-only access to the pick data as a tuple.
- Returns:
- Tuple[Move, float64]
The (move, score) pair represented by this object.
- property move: Move¶
Read-only access to the move.
- Returns:
- Move
The chess move associated with this Pick.
- move_getter_keys: Tuple[int, str, int] = (0, 'move', -2)¶
- property score: float64¶
Read access to the score.
- Returns:
- float64
The numeric evaluation of the move.
- score_getter_keys: Tuple[int, str, int] = (1, 'score', -1)¶
- chmengine.utils.calculate_score(current_index: int, new_heatmap_transposed: ndarray[Any, dtype[float64]], new_current_king_box: List[int], new_other_king_box: List[int]) float64 ¶
Compute a score for a board state based on heatmap control and king box pressure.
(Deprecated legacy score calc function)
- Parameters:
- current_indexint
Index of the current player in the heatmap data (0 for White, 1 for Black).
- new_heatmap_transposednumpy.typing.NDArray[numpy.float64]
A transposed 2x64 array of heatmap intensities (player x squares).
- new_current_king_boxlist of int
Indices of squares surrounding the current player’s king.
- new_other_king_boxlist of int
Indices of squares surrounding the opponent’s king.
- Returns:
- numpy.float64
Total score computed by summing general control delta and weighted king box pressure.
- chmengine.utils.calculate_white_minus_black_score(board: Board, depth: int) float64 ¶
Evaluate the board from a White-minus-Black perspective using heatmap evaluation.
This function returns a net evaluation score. Positive values favor White, negative values favor Black. Terminal game states return fixed scores. Otherwise, the score is derived from: - Heatmap intensity differences - Control over king box areas
- Parameters:
- boardchess.Board
The chess board to evaluate.
- depthint
Depth of future move evaluation.
- Returns:
- numpy.float64
Net evaluation score (White - Black). Terminal states return extreme values.
Examples
>>> from chmengine.utils import is_draw >>> from chess import Board, Move >>> default_board, d = Board(), 1 >>> calculate_white_minus_black_score(board=default_board, depth=d) 0.0 >>> default_board.push(Move.from_uci('e2e4')) >>> calculate_white_minus_black_score(board=default_board, depth=d) 10.0 >>> default_board.push(Move.from_uci('e7e5')) >>> calculate_white_minus_black_score(board=default_board, depth=d) 0.20689655172414234 >>> default_board.push(Move.from_uci('g1f3')) >>> calculate_white_minus_black_score(board=default_board, depth=d) -2.1379310344827616 >>> default_board.push(Move.from_uci('b8c6')) >>> calculate_white_minus_black_score(board=default_board, depth=d) -3.925925925925924 >>> default_board.push(Move.from_uci('f1b5')) >>> calculate_white_minus_black_score(board=default_board, depth=d) 2.133333333333335 >>> mate_board = Board('8/2p2p2/4p3/2k5/8/6q1/2K5/1r1q4 w - - 2 59') >>> calculate_white_minus_black_score(board=mate_board, depth=d) -1024.0 >>> draw_board = Board('6R1/7p/2p2p1k/p1P2Q2/P7/6K1/5P2/8 b - - 0 52') >>> calculate_white_minus_black_score(board=draw_board, depth=d) 0.0
- chmengine.utils.checkmate_score(board: Board, depth: int) float64 ¶
Return a large signed score for checkmate results.
The score is scaled by number of remaining pieces and depth. Negative if the current player is mated, positive if they deliver mate.
- Parameters:
- boardchess.Board
Board state assumed to be in a terminal position.
- depthint
Search depth used, for scaling the final score.
- Returns:
- numpy.float64
Large positive or negative score depending on the outcome.
Examples
>>> from chmengine.utils import is_draw >>> from chess import Board >>> blk_win_board = Board('8/2p2p2/4p3/2k5/8/6q1/2K5/1r1q4 w - - 2 59') >>> checkmate_score(board=blk_win_board, depth=1) -1024.0
- chmengine.utils.format_moves(picks: List[Pick]) List[Tuple[str, str]] ¶
Format a list of (move, score) tuples into UCI strings and formatted scores.
- Parameters:
- picksList[Pick]
The list of Picks (moves and their evaluation scores.)
- Returns:
- List[Tuple[str, str]
Formatted list where each tuple contains the move in UCI format and the score rounded to two decimal places. Entries with None moves are excluded.
- chmengine.utils.get_white_and_black_king_boxes(board: Board) Tuple[List[int], List[int]] ¶
Compute the list of squares surrounding each king on the board.
These “king boxes” are used for evaluating positional pressure around the kings.
- Parameters:
- boardchess.Board
The board from which to extract king square surroundings.
- Returns:
- tuple of (list of int, list of int)
Tuple containing white king box and black king box square indices. (white_king_box, black_king_box)
Examples
>>> from chmengine.utils import is_draw >>> from chess import Board >>> white_kb, black_kb = get_white_and_black_king_boxes(board=Board()) >>> sorted(white_kb), sorted(black_kb) ([3, 4, 5, 11, 12, 13], [51, 52, 53, 59, 60, 61])
- chmengine.utils.insert_choice_into_current_moves(choices_ordered_best_to_worst: List[Pick], pick: Pick) List[Pick] ¶
Insert a new candidate move into the current player’s move list (best to worst).
- Parameters:
- choices_ordered_best_to_worstList[Pick]
Current ordered list of move choices.
- pickPick
- Returns:
- List[Pick]
Updated list with the move inserted.
- chmengine.utils.insert_ordered_best_to_worst(ordered_picks: List[Pick], pick: Pick) None ¶
Insert a move into a list of moves sorted from best to worst.
- Parameters:
- ordered_picksList[Pick]
Existing list sorted in descending order of score.
- pickPick
- chmengine.utils.insert_ordered_worst_to_best(ordered_picks: List[Pick], pick: Pick) None ¶
Insert a move into a list of moves sorted from worst to best.
- Parameters:
- ordered_picksList[Pick]
Existing list sorted in ascending order of score.
- pickPick
- chmengine.utils.is_draw(winner: Optional[bool]) bool ¶
Check if a game result is a draw based on the winner field.
- Parameters:
- winnerbool or None
Result of Board.outcome(…).winner. True for White win, False for Black win, None for draw.
- Returns:
- bool
True if the game is a draw, False otherwise.
Examples
>>> from chmengine.utils import is_draw >>> from chess import Board >>> mate_board = Board('8/2p2p2/4p3/2k5/8/6q1/2K5/1r1q4 w - - 2 59') >>> is_draw(mate_board.outcome(claim_draw=True).winner) False >>> draw_board = Board('6R1/7p/2p2p1k/p1P2Q2/P7/6K1/5P2/8 b - - 0 52') >>> is_draw(draw_board.outcome(claim_draw=True).winner) True
- chmengine.utils.is_valid_king_box_square(square_id: int, king_square: int) bool ¶
Check if a square is valid for inclusion in a king’s bounding box.
A square is valid if: - It lies on the board (0–63) - It is adjacent to the king’s square (distance ≤ 1)
- Parameters:
- square_idint
Index of the square to evaluate.
- king_squareint
Index of the king’s square.
- Returns:
- bool
True if the square should be included in the king box.
- chmengine.utils.null_target_moves(number: int = 6) Tuple[List[Tuple[Optional[Move], Optional[float64]]], ...] ¶
Initialize a tuple of target move lists with null entries.
This helper method creates a tuple containing ‘number’ lists, each initialized with a single tuple (None, None). These lists serve as starting placeholders for candidate moves and their scores.
- Parameters:
- numberint, default: 6
The number of target move lists to create.
- Returns:
- Tuple[List[Tuple[Optional[chess.Move], Optional[numpy.float64]]], …]
A tuple of lists, each initially containing one tuple (None, None).
- chmengine.utils.pieces_count_from_board(board: Board) int ¶
Return the number of pieces on the board
This uses the internal bitboard to count occupied squares in O(1) time. On Python ≥ 3.8 it calls int.bit_count(). On Python 3.7 it falls back to bin(…).count(‘1’) for compatibility.
- Parameters:
- boardchess.Board
A board object to count pieces from
- Returns:
- int
Number of pieces on the board.
Examples
>>> from chess import Board >>> mate_board = Board('8/2p2p2/4p3/2k5/8/6q1/2K5/1r1q4 w - - 2 59') >>> pieces_count_from_board(mate_board) 8 >>> pieces_count_from_board(Board()) 32
- chmengine.utils.pieces_count_from_fen(fen: str) int ¶
Return the number of pieces on the board represented by fen.
This function converts the FEN string into a Board object, then uses the internal bitboard to count occupied squares in O(1) time. On Python ≥ 3.8, it calls int.bit_count(); on Python 3.7, it falls back to bin(…).count(‘1’) for compatibility.
- Parameters:
- fenstr
A full FEN string representing a chess position.
- Returns:
- int
The count of non‑empty squares (i.e. total pieces) on the board.
Notes
For most use cases, especially when you already have a Board object, prefer using pieces_count_from_board(board) instead. This avoids the overhead of FEN parsing and achieves the same result more efficiently.
Examples
>>> from chess import Board >>> pieces_count_from_fen('8/2p2p2/4p3/2k5/8/6q1/2K5/1r1q4 w - - 2 59') 8 >>> pieces_count_from_fen(Board().fen()) 32
- chmengine.utils.set_all_datetime_headers(game_heads: Headers, local_time: datetime) None ¶
Sets all datetime related game headers for the pgn file.
- Parameters:
- game_headschess.pgn.Headers
- local_timedatetime.datetime
- chmengine.utils.set_utc_headers(game_heads: Headers, local_time: datetime) None ¶
Sets UTC header info of pgn file data from local timestamp
- Parameters:
- game_headschess.pgn.Headers
- local_timedatetime.datetime
Modules
Pick object representing a (move, score) evaluation pair. |