Skip to content

Commit

Permalink
Cast types using numpy for efficiency
Browse files Browse the repository at this point in the history
  • Loading branch information
glatterf42 committed Oct 22, 2024
1 parent 4bbd26a commit 52f3423
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions ixmp4/data/db/optimization/indexset/model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import ClassVar, Literal
from typing import ClassVar

import numpy as np

from ixmp4 import db
from ixmp4.core.exceptions import OptimizationDataValidationError
Expand All @@ -8,20 +10,6 @@
from .. import base


# TODO Feels like there ought to be this kind of functionality already
def cast_data_as_type(
data: "IndexSetData", type: Literal["float", "int", "str"] | None
) -> float | int | str:
if type == "str":
return data.value
elif type == "int":
return int(data.value)
elif type == "float":
return float(data.value)
else: # type is None
return 0


class IndexSet(base.BaseModel):
NotFound: ClassVar = abstract.IndexSet.NotFound
NotUnique: ClassVar = abstract.IndexSet.NotUnique
Expand All @@ -36,7 +24,11 @@ class IndexSet(base.BaseModel):

@db.hybrid_property
def data(self) -> list[float | int | str]:
return [cast_data_as_type(data, self.data_type) for data in self._data]
return (
[]
if self.data_type is None
else np.array([d.value for d in self._data], dtype=self.data_type).tolist()
)

# NOTE For the core layer (setting and retrieving) to work, the property needs a
# setter method
Expand Down

0 comments on commit 52f3423

Please sign in to comment.