Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/+v2-table-load-perf.perf.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
v2: Loading large condition and measurement tables is faster. Conditions
are now kept in the order of their first occurrence in the condition table,
instead of being sorted by ID
([#634](https://github.com/PEtab-dev/libpetab-python/pull/634))
100 changes: 82 additions & 18 deletions petab/v2/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,52 @@

logger = logging.getLogger(__name__)

#: Keys of caches in the pydantic validation context, to avoid repeatedly
#: validating the same values when creating many objects, e.g., in `from_df`.
#: Sympified values:
_SYMPIFY_CACHE = "sympify_cache"
#: Already validated IDs:
_VALID_IDS = "valid_ids"


def _new_validation_context() -> dict:
"""A pydantic validation context with empty caches."""
return {_SYMPIFY_CACHE: {}, _VALID_IDS: set()}


def _records(df: pd.DataFrame) -> list[dict]:
"""Like ``df.to_dict("records")``, but faster for large DataFrames."""
columns = list(df.columns)

def to_list(series: pd.Series) -> list:
if isinstance(series.dtype, np.dtype):
return series.tolist()
# e.g., nullable dtypes: `pd.NA` -> NaN
return series.to_numpy(dtype=object, na_value=np.nan).tolist()

return [
dict(zip(columns, values, strict=True))
for values in zip(*(to_list(df[c]) for c in columns), strict=True)
]


def _sympify_cached(v, info: ValidationInfo) -> sp.Basic:
"""`sympify_petab(v)`, cached in the validation context, if available."""
cache = info.context.get(_SYMPIFY_CACHE) if info.context else None
if cache is None:
return sympify_petab(v)
# the type is part of the key, because, e.g., `1` and `1.0` compare
# equal, but are sympified differently
key = (type(v), v)
try:
return cache[key]
except KeyError:
cache[key] = result = sympify_petab(v)
return result
except TypeError:
# unhashable
return sympify_petab(v)


def _field_to_column(info: ValidationInfo) -> str:
"""The PEtab column name for the validated field."""
Expand Down Expand Up @@ -166,6 +212,18 @@ def _valid_petab_id(v: str) -> str:
return v


def _valid_petab_id_cached(v: str, info: ValidationInfo) -> str:
"""Like :func:`_valid_petab_id`, but skips IDs that were already
validated in the same validation context."""
valid_ids = info.context.get(_VALID_IDS) if info.context else None
if valid_ids is not None and v in valid_ids:
return v
_valid_petab_id(v)
if valid_ids is not None:
valid_ids.add(v)
return v


def _valid_petab_id_or_none(v: str) -> str | None:
"""Field validator for optional PEtab IDs."""
if not v:
Expand Down Expand Up @@ -571,7 +629,7 @@ class Change(BaseModel):
"""

#: The ID of the target entity to change.
target_id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
target_id: Annotated[str, AfterValidator(_valid_petab_id_cached)] = Field(
alias=C.TARGET_ID
)
#: The value to set the target entity to.
Expand All @@ -588,13 +646,13 @@ class Change(BaseModel):

@field_validator("target_value", mode="before")
@classmethod
def _sympify(cls, v):
def _sympify(cls, v, info: ValidationInfo):
if v is None or isinstance(v, sp.Basic):
return v
if isinstance(v, float) and np.isnan(v):
return None

return sympify_petab(v)
return _sympify_cached(v, info)


class Condition(BaseModel):
Expand Down Expand Up @@ -659,15 +717,22 @@ def from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
if df is None or df.empty:
return cls(**kwargs)

conditions = []
for condition_id, sub_df in df.groupby(C.CONDITION_ID):
changes = [
Change(**row)
for row in sub_df.drop(columns=C.CONDITION_ID).to_dict(
"records"
)
]
conditions.append(Condition(id=condition_id, changes=changes))
# condition ID -> rows, in order of first occurrence
# (rows without condition ID are ignored)
rows_by_id = {}
for row in _records(df[df[C.CONDITION_ID].notna()]):
rows_by_id.setdefault(row.pop(C.CONDITION_ID), []).append(row)

context = _new_validation_context()
conditions = [
Condition(
id=condition_id,
changes=[
Change.model_validate(row, context=context) for row in rows
],
)
for condition_id, rows in rows_by_id.items()
]

return cls(conditions, **kwargs)

Expand Down Expand Up @@ -926,7 +991,7 @@ def convert_nan_to_none(cls, v, info: ValidationInfo):
"observable_parameters", "noise_parameters", mode="before"
)
@classmethod
def _sympify_list(cls, v):
def _sympify_list(cls, v, info: ValidationInfo):
if v is None or v == "":
return []

Expand All @@ -938,7 +1003,7 @@ def _sympify_list(cls, v):
elif not isinstance(v, Sequence):
v = [v]

return [sympify_petab(x) for x in v]
return [_sympify_cached(x, info) for x in v]


class MeasurementTable(BaseTable[Measurement]):
Expand All @@ -961,11 +1026,10 @@ def from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
if C.MODEL_ID in df.columns:
df[C.MODEL_ID] = df[C.MODEL_ID].apply(_convert_nan_to_none)

context = _new_validation_context()
measurements = [
Measurement(
**row.to_dict(),
)
for _, row in df.iterrows()
Measurement.model_validate(row, context=context)
for row in _records(df)
]

return cls(measurements, **kwargs)
Expand Down
40 changes: 40 additions & 0 deletions tests/v2/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,46 @@ def test_condition_table_from_df_condition_id():
assert loaded.to_df()[CONDITION_ID].tolist() == ["c2"]


def test_condition_table_from_df_order_and_types():
"""Conditions are in order of first occurrence, with all their changes,
and equal values of different types are sympified as without caching."""
df = pd.DataFrame(
{
CONDITION_ID: ["c2", "c1", "c2", "c1", None],
TARGET_ID: ["k1", "k1", "k2", "k2", "k3"],
TARGET_VALUE: pd.Series([2, 2.0, 2.0, 2, 2.0], dtype=object),
}
)
conditions = ConditionTable.from_df(df)
assert [
(c.id, [(ch.target_id, type(ch.target_value)) for ch in c.changes])
for c in conditions.conditions
] == [
("c2", [("k1", sp.Integer), ("k2", sp.Float)]),
("c1", [("k1", sp.Float), ("k2", sp.Integer)]),
]

# invalid IDs are still reported
df.loc[0, TARGET_ID] = "1k"
with pytest.raises(ValidationError, match="1k"):
ConditionTable.from_df(df)


def test_measurement_table_from_df_nullable_dtypes():
"""Missing values in nullable columns are treated as empty."""
df = pd.DataFrame(
{
OBSERVABLE_ID: ["obs1", "obs1"],
C.EXPERIMENT_ID: ["e1", "e1"],
C.TIME: [0.0, 1.0],
C.MEASUREMENT: [1.0, 2.0],
C.NOISE_PARAMETERS: pd.array([1, pd.NA], dtype="Int64"),
}
).convert_dtypes()
measurements = MeasurementTable.from_df(df).measurements
assert [m.noise_parameters for m in measurements] == [[sp.Integer(1)], []]


def test_condition_table():
assert ConditionTable().free_symbols == set()

Expand Down
Loading