Skip to content

base_model

Base model implementation for all MLTE models.

BaseModel

Bases: BaseModel

The base model for all MLTE models.

Source code in mlte/model/base_model.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class BaseModel(pydantic.BaseModel):
    """The base model for all MLTE models."""

    def to_json(self) -> dict[str, Any]:
        """
        Serialize the model. Also check if the result is serializable.
        :return: The JSON representation of the model
        """
        json_object = self.model_dump()

        # Check if object can't be serialized.
        try:
            _ = json.dumps(json_object)
        except TypeError as e:
            raise SerializationError(e, str(type(self)))

        return json_object

    @classmethod
    def from_json(cls, data: dict[str, Any]) -> BaseModel:
        """
        Deserialize a model from data.
        :param data: The raw input data
        :return: A deserialized model instance
        """
        return cls(**data)

    def to_json_string(self) -> str:
        """Serialize to a json string."""
        return json.dumps(self.to_json())

    @classmethod
    def from_json_string(cls, json_str: str) -> Any:
        """Deserialize from a json string."""
        return cls.from_json(json.loads(json_str))

    def post_validation_hook(self, data: Optional[Any] = None) -> Any:
        """Called after validation, lets submodels do any needed post-processing."""
        pass

    def _equal(a: BaseModel, b: BaseModel) -> bool:
        """
        Compare model instances for equality.

        :param a: Input instance
        :param b: Input instance
        :return: `True` if `a` and `b` are equal, `False` otherwise
        """
        return a.to_json() == b.to_json()

    def __eq__(self, other: object) -> bool:
        """Test instance for equality."""
        if not isinstance(other, BaseModel):
            return False
        return self._equal(other)

__eq__(other)

Test instance for equality.

Source code in mlte/model/base_model.py
63
64
65
66
67
def __eq__(self, other: object) -> bool:
    """Test instance for equality."""
    if not isinstance(other, BaseModel):
        return False
    return self._equal(other)

from_json(data) classmethod

Deserialize a model from data.

Parameters:

Name Type Description Default
data dict[str, Any]

The raw input data

required

Returns:

Type Description
BaseModel

A deserialized model instance

Source code in mlte/model/base_model.py
31
32
33
34
35
36
37
38
@classmethod
def from_json(cls, data: dict[str, Any]) -> BaseModel:
    """
    Deserialize a model from data.
    :param data: The raw input data
    :return: A deserialized model instance
    """
    return cls(**data)

from_json_string(json_str) classmethod

Deserialize from a json string.

Source code in mlte/model/base_model.py
44
45
46
47
@classmethod
def from_json_string(cls, json_str: str) -> Any:
    """Deserialize from a json string."""
    return cls.from_json(json.loads(json_str))

post_validation_hook(data=None)

Called after validation, lets submodels do any needed post-processing.

Source code in mlte/model/base_model.py
49
50
51
def post_validation_hook(self, data: Optional[Any] = None) -> Any:
    """Called after validation, lets submodels do any needed post-processing."""
    pass

to_json()

Serialize the model. Also check if the result is serializable.

Returns:

Type Description
dict[str, Any]

The JSON representation of the model

Source code in mlte/model/base_model.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def to_json(self) -> dict[str, Any]:
    """
    Serialize the model. Also check if the result is serializable.
    :return: The JSON representation of the model
    """
    json_object = self.model_dump()

    # Check if object can't be serialized.
    try:
        _ = json.dumps(json_object)
    except TypeError as e:
        raise SerializationError(e, str(type(self)))

    return json_object

to_json_string()

Serialize to a json string.

Source code in mlte/model/base_model.py
40
41
42
def to_json_string(self) -> str:
    """Serialize to a json string."""
    return json.dumps(self.to_json())