chessai.core.gameannotation

 1import typing
 2
 3import edq.util.json
 4import edq.util.serial
 5
 6import chessai
 7import chessai.core.types
 8
 9GAME_RATING_ANNOTATION_HEADER: str = 'ChessAIStockfishAnalysis'
10""" The PGN header used for a serialized `GameRatingAnnotation`. """
11
12Rating: typing.TypeAlias = float | str
13""" A pawn evaluation or a forced-mate value such as ``"M3"``. """
14
15class RatingEngine(edq.util.serial.DictConverter):
16    """ Identify the chess engine that produced a game rating. """
17
18    def __init__(self, name: str, commit: str) -> None:
19        self.name: str = name
20        """ The engine's display name. """
21
22        self.commit: str = commit
23        """ The source revision used to build the engine. """
24
25class MoveRatingAnnotation(edq.util.serial.DictConverter):
26    """ A rating and optional explanation for the position after one ply of a game. """
27
28    def __init__(self,
29            rating: Rating,
30            ) -> None:
31        self.rating: Rating = rating
32        """ The engine evaluation of this position. """
33
34    @classmethod
35    def from_dict(cls,
36            data: dict[str, typing.Any],
37            context: edq.util.serial.SerializationContext | None = None,
38            ) -> 'MoveRatingAnnotation':
39        data = dict(data)
40        raw_rating = data.pop('rating', 0.0)
41        if isinstance(raw_rating, str):
42            if ("M" not in raw_rating.upper()):
43                try:
44                    raw_rating = float(raw_rating)
45                except Exception as ex: # pylint disable=broad-exception-caught
46                    raise ValueError(f"Failed to parse rating {raw_rating}") from ex
47
48        init_data = super().prep_init_data(data, context)
49        init_data['rating'] = raw_rating
50        return cls(**init_data)
51
52class GameRatingAnnotation(edq.util.serial.DictConverter):
53    """ A versioned collection of engine ratings for every position in a game. """
54
55    def __init__(self,
56            engine: RatingEngine,
57            depth: int,
58            annotations: list[MoveRatingAnnotation] | None = None,
59            score_perspective: chessai.core.types.Color = chessai.core.types.Color.WHITE,
60            ) -> None:
61        if (depth < 1):
62            raise ValueError('The analysis depth must be at least one.')
63
64        self.score_perspective: chessai.core.types.Color = score_perspective
65        """ The player for whom a positive evaluation is favorable. """
66
67        self.engine: RatingEngine = engine
68        """ The engine that evaluated the game. """
69
70        self.depth: int = depth
71        """ The engine search depth used for every rating. """
72
73        if (annotations is None):
74            annotations = []
75
76        self.annotations: list[MoveRatingAnnotation] = annotations
77        """ The initial position and each later position's rating, in ply order. """
78
79    def to_header_value(self) -> str:
80        """ Serialize this annotation as compact JSON suitable for a PGN tag value. """
81
82        return edq.util.json.dumps(self.to_dict(), separators = (',', ':'))
83
84    @classmethod
85    def from_header_value(cls, value: str) -> 'GameRatingAnnotation':
86        """ Deserialize a `GAME_RATING_ANNOTATION_HEADER` tag value. """
87
88        data = edq.util.json.loads(value, strict = True)
89        if (not isinstance(data, dict)):
90            raise ValueError('A game rating annotation header must contain a JSON object.')
91
92        return cls.from_dict(data)
GAME_RATING_ANNOTATION_HEADER: str = 'ChessAIStockfishAnalysis'

The PGN header used for a serialized GameRatingAnnotation.

Rating: TypeAlias = float | str

A pawn evaluation or a forced-mate value such as "M3".

class RatingEngine(edq.util.serial.DictConverter):
16class RatingEngine(edq.util.serial.DictConverter):
17    """ Identify the chess engine that produced a game rating. """
18
19    def __init__(self, name: str, commit: str) -> None:
20        self.name: str = name
21        """ The engine's display name. """
22
23        self.commit: str = commit
24        """ The source revision used to build the engine. """

Identify the chess engine that produced a game rating.

RatingEngine(name: str, commit: str)
19    def __init__(self, name: str, commit: str) -> None:
20        self.name: str = name
21        """ The engine's display name. """
22
23        self.commit: str = commit
24        """ The source revision used to build the engine. """
name: str

The engine's display name.

commit: str

The source revision used to build the engine.

class MoveRatingAnnotation(edq.util.serial.DictConverter):
26class MoveRatingAnnotation(edq.util.serial.DictConverter):
27    """ A rating and optional explanation for the position after one ply of a game. """
28
29    def __init__(self,
30            rating: Rating,
31            ) -> None:
32        self.rating: Rating = rating
33        """ The engine evaluation of this position. """
34
35    @classmethod
36    def from_dict(cls,
37            data: dict[str, typing.Any],
38            context: edq.util.serial.SerializationContext | None = None,
39            ) -> 'MoveRatingAnnotation':
40        data = dict(data)
41        raw_rating = data.pop('rating', 0.0)
42        if isinstance(raw_rating, str):
43            if ("M" not in raw_rating.upper()):
44                try:
45                    raw_rating = float(raw_rating)
46                except Exception as ex: # pylint disable=broad-exception-caught
47                    raise ValueError(f"Failed to parse rating {raw_rating}") from ex
48
49        init_data = super().prep_init_data(data, context)
50        init_data['rating'] = raw_rating
51        return cls(**init_data)

A rating and optional explanation for the position after one ply of a game.

MoveRatingAnnotation(rating: float | str)
29    def __init__(self,
30            rating: Rating,
31            ) -> None:
32        self.rating: Rating = rating
33        """ The engine evaluation of this position. """
rating: float | str

The engine evaluation of this position.

@classmethod
def from_dict( cls, data: dict[str, typing.Any], context: edq.util.common.SerializationContext | None = None) -> MoveRatingAnnotation:
35    @classmethod
36    def from_dict(cls,
37            data: dict[str, typing.Any],
38            context: edq.util.serial.SerializationContext | None = None,
39            ) -> 'MoveRatingAnnotation':
40        data = dict(data)
41        raw_rating = data.pop('rating', 0.0)
42        if isinstance(raw_rating, str):
43            if ("M" not in raw_rating.upper()):
44                try:
45                    raw_rating = float(raw_rating)
46                except Exception as ex: # pylint disable=broad-exception-caught
47                    raise ValueError(f"Failed to parse rating {raw_rating}") from ex
48
49        init_data = super().prep_init_data(data, context)
50        init_data['rating'] = raw_rating
51        return cls(**init_data)

Return an instance of this subclass created using the given dict. If the dict came from to_dict(), the returned object should be equivalent to the original.

By default, this function just calls the class' constructor with the output of prep_init_data(). A child can override this or prep_init_data() depending on the functionality they want.

A general (but inefficient) implementation is provided by default. This implementation will attempt to use type hints (of the classes constructor) to convert enums and DictDeserializers.

class GameRatingAnnotation(edq.util.serial.DictConverter):
53class GameRatingAnnotation(edq.util.serial.DictConverter):
54    """ A versioned collection of engine ratings for every position in a game. """
55
56    def __init__(self,
57            engine: RatingEngine,
58            depth: int,
59            annotations: list[MoveRatingAnnotation] | None = None,
60            score_perspective: chessai.core.types.Color = chessai.core.types.Color.WHITE,
61            ) -> None:
62        if (depth < 1):
63            raise ValueError('The analysis depth must be at least one.')
64
65        self.score_perspective: chessai.core.types.Color = score_perspective
66        """ The player for whom a positive evaluation is favorable. """
67
68        self.engine: RatingEngine = engine
69        """ The engine that evaluated the game. """
70
71        self.depth: int = depth
72        """ The engine search depth used for every rating. """
73
74        if (annotations is None):
75            annotations = []
76
77        self.annotations: list[MoveRatingAnnotation] = annotations
78        """ The initial position and each later position's rating, in ply order. """
79
80    def to_header_value(self) -> str:
81        """ Serialize this annotation as compact JSON suitable for a PGN tag value. """
82
83        return edq.util.json.dumps(self.to_dict(), separators = (',', ':'))
84
85    @classmethod
86    def from_header_value(cls, value: str) -> 'GameRatingAnnotation':
87        """ Deserialize a `GAME_RATING_ANNOTATION_HEADER` tag value. """
88
89        data = edq.util.json.loads(value, strict = True)
90        if (not isinstance(data, dict)):
91            raise ValueError('A game rating annotation header must contain a JSON object.')
92
93        return cls.from_dict(data)

A versioned collection of engine ratings for every position in a game.

GameRatingAnnotation( engine: RatingEngine, depth: int, annotations: list[MoveRatingAnnotation] | None = None, score_perspective: chessai.core.types.Color = Color.WHITE)
56    def __init__(self,
57            engine: RatingEngine,
58            depth: int,
59            annotations: list[MoveRatingAnnotation] | None = None,
60            score_perspective: chessai.core.types.Color = chessai.core.types.Color.WHITE,
61            ) -> None:
62        if (depth < 1):
63            raise ValueError('The analysis depth must be at least one.')
64
65        self.score_perspective: chessai.core.types.Color = score_perspective
66        """ The player for whom a positive evaluation is favorable. """
67
68        self.engine: RatingEngine = engine
69        """ The engine that evaluated the game. """
70
71        self.depth: int = depth
72        """ The engine search depth used for every rating. """
73
74        if (annotations is None):
75            annotations = []
76
77        self.annotations: list[MoveRatingAnnotation] = annotations
78        """ The initial position and each later position's rating, in ply order. """
score_perspective: chessai.core.types.Color

The player for whom a positive evaluation is favorable.

engine: RatingEngine

The engine that evaluated the game.

depth: int

The engine search depth used for every rating.

annotations: list[MoveRatingAnnotation]

The initial position and each later position's rating, in ply order.

def to_header_value(self) -> str:
80    def to_header_value(self) -> str:
81        """ Serialize this annotation as compact JSON suitable for a PGN tag value. """
82
83        return edq.util.json.dumps(self.to_dict(), separators = (',', ':'))

Serialize this annotation as compact JSON suitable for a PGN tag value.

@classmethod
def from_header_value(cls, value: str) -> GameRatingAnnotation:
85    @classmethod
86    def from_header_value(cls, value: str) -> 'GameRatingAnnotation':
87        """ Deserialize a `GAME_RATING_ANNOTATION_HEADER` tag value. """
88
89        data = edq.util.json.loads(value, strict = True)
90        if (not isinstance(data, dict)):
91            raise ValueError('A game rating annotation header must contain a JSON object.')
92
93        return cls.from_dict(data)

Deserialize a GAME_RATING_ANNOTATION_HEADER tag value.