chmengine.utils

Utilities for engine evaluation and scoring logic.

Functions

better_checkmate_score(board, depth)

Compute an enhanced checkmate evaluation score.

calculate_better_white_minus_black_score(board)

Compute an enhanced White-minus-Black evaluation for a given board position.

calculate_score(current_index, ...)

Compute a score for a board state based on heatmap control and king box pressure.

calculate_white_minus_black_score(board, depth)

Evaluate the board from a White-minus-Black perspective using heatmap evaluation.

checkmate_score(board, depth)

Return a large signed score for checkmate results.

format_moves(picks)

Format a list of (move, score) tuples into UCI strings and formatted scores.

format_picks(picks)

Format a list of Picks into UCI strings and formatted scores.

get_static_delta_score(heatmap)

Compute the static piece-based delta score from a ChessMoveHeatmap.

get_static_value(piece)

Retrieve the static movement-based value for a given chess piece.

get_white_and_black_king_boxes(board)

Compute the list of squares surrounding each king on the board.

insert_choice_into_current_moves(...)

Insert a new candidate move into the current player's move list (best to worst).

insert_choice_into_response_moves(...)

Insert a new candidate move into the opponent's response list (worst to best).

insert_ordered_best_to_worst(ordered_picks, pick)

Insert a move into a list of moves sorted from best to worst.

insert_ordered_worst_to_best(ordered_picks, pick)

Insert a move into a list of moves sorted from worst to best.

is_draw(winner)

Check if a game result is a draw based on the winner field.

is_valid_king_box_square(square_id, king_square)

Check if a square is valid for inclusion in a king's bounding box.

null_target_moves([number])

Initialize a tuple of target move lists with null entries.

pieces_count_from_board(board)

Return the number of pieces on the board

pieces_count_from_fen(fen)

Return the number of pieces on the board represented by fen.

set_all_datetime_headers(game_heads, local_time)

Sets all datetime related game headers for the pgn file.

set_utc_headers(game_heads, local_time)

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.better_checkmate_score(board: Board, depth: int) float64

Compute an enhanced checkmate evaluation score.

This function returns a large-magnitude score to represent a checkmate outcome, scaled by the number of pieces remaining, the search depth, and an additional safety margin multiplier. By multiplying by 64 (squares) and 27 (maximum queen moves), we ensure that non-checkmate positional scores remain bounded in comparison.

The sign encodes which side is to move: - If it is White’s turn (i.e., White has just been checkmated), returns a

large negative score (bad for White).

  • If it is Black’s turn (i.e., Black has just been checkmated), returns

    a large positive score (good for White).

Parameters:
boardchess.Board

The board position where checkmate has occurred.

depthint

The recursion depth used in the evaluation, included to amplify the score further for deeper searches.

Returns:
numpy.float64

A signed checkmate score with large magnitude, where positive values favor White and negative values favor Black.

chmengine.utils.calculate_better_white_minus_black_score(board: Board, depth: int = 1) float64

Compute an enhanced White-minus-Black evaluation for a given board position.

This function combines three components into a single signed score:

  1. Game termination:
    • If the position is a draw, returns 0.

    • If the position is checkmate, returns a high upper-bound value via checkmate_score().

  2. Heatmap mobility delta:

    Difference in total possible moves between White and Black, computed by calculate_chess_move_heatmap_with_better_discount().

  3. King-box mobility delta:

    Difference in potential moves targeting the opponent’s king region and defending the own king region.

  4. Static delta:

    Material-mobility delta from get_static_delta_score().

The final score is the sum of the mobility delta, king-box delta, and static delta, representing White’s advantage minus Black’s.

Parameters:
boardchess.Board

The chess board position to evaluate.

depthint, default: 1

Recursion depth for the heatmap calculation. Higher values yield more thorough mobility estimates at the cost of increased computation time.

Returns:
numpy.float64

The signed evaluation: positive values favor White, negative values favor Black.

Notes

  • Time complexity is O(b^d) for the heatmap portion (where b ≈ 35 is the branching factor).

  • Checkmate scores use an upper-bound heuristic: all remaining pieces can move to every square,

    scaled by (depth + 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.format_picks(picks: List[Pick]) str

Format a list of Picks into UCI strings and formatted scores.

Parameters:
picksList[Pick]

The list of Picks (moves and their evaluation scores.)

Returns:
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_static_delta_score(heatmap: ChessMoveHeatmap) float64

Compute the static piece-based delta score from a ChessMoveHeatmap.

This function multiplies each piece’s move count (from the heatmap’s piece_counts) by its static movement value (from get_static_value) and returns the difference between White’s total and Black’s total. It serves as a simple material–mobility heuristic.

Parameters:
heatmapheatmaps.ChessMoveHeatmap

The heatmap object containing per-piece move counts for each square.

Returns:
numpy.float64

The signed delta score: (White’s static total) − (Black’s static total).

chmengine.utils.get_static_value(piece: Piece) int

Retrieve the static movement-based value for a given chess piece.

This function returns a fixed integer value representing the maximum number of moves that the specified piece can make on an empty board. These values serve as a simple heuristic for piece mobility.

Parameters:
piecechess.Piece

The chess piece for which to look up the static move value.

Returns:
int

The static movement value for the piece, or 0 if the piece is not in the map.

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:
boardBoard

The board from which to extract king square surroundings.

Returns:
Tuple[List[int], List[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

chmengine.utils.pick

Pick object representing a (move, score) evaluation pair.