Skip to content

Commit

Permalink
fix: Allowing serialization with numpy types inside of BaseQuantity (
Browse files Browse the repository at this point in the history
  • Loading branch information
pesap authored Jan 21, 2025
1 parent 7d7fbbf commit 855cf07
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "infrasys"
version = "0.2.3"
version = "0.2.4"
description = ''
readme = "README.md"
requires-python = ">=3.10, <3.13"
Expand Down
2 changes: 2 additions & 0 deletions src/infrasys/base_quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ def to_dict(self) -> dict[str, Any]:
val = self.magnitude
if isinstance(self.magnitude, np.ndarray):
val = self.magnitude.tolist()
elif isinstance(self.magnitude, np.generic):
val = val.item()
return {"value": val, "units": str(self.units)}

@classmethod
Expand Down
13 changes: 13 additions & 0 deletions tests/test_base_quantity.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os
from infrasys.system import System
from pydantic import ValidationError
from infrasys.base_quantity import ureg, BaseQuantity
from infrasys.component import Component
Expand Down Expand Up @@ -102,3 +104,14 @@ def test_custom_serialization():

model_dump = component.model_dump(mode="json", context={"magnitude_only": True})
assert model_dump["voltage"] == 10.0


def test_system_save_with_pint_quantity(tmp_path):
component = BaseQuantityComponent(name="test", voltage=Voltage(np.float32(10.0), units="volt"))
system = System()
system.add_component(component)
custom_folder = "my_system"

fpath = tmp_path / custom_folder / "test_system.json"
system.to_json(fpath)
assert os.path.exists(fpath), f"Folder {fpath} was not created successfully"

0 comments on commit 855cf07

Please sign in to comment.