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
6 changes: 6 additions & 0 deletions changelog.d/+v2-empty-condition-experiment-ids.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
`petab.v2`: Rows with empty condition IDs in the condition table or empty
experiment IDs in the experiment table now raise `petab.v2.EmptyIdError` when
loading, instead of being silently dropped. `petablint` reports this error
without a traceback. `petab.v2.TableError` is the new common base class of
`EmptyIdError` and `MissingColumnsError`
([#629](https://github.com/PEtab-dev/libpetab-python/pull/629))
7 changes: 7 additions & 0 deletions changelog.d/+v2-missing-columns.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
v2: Creating a table via `from_df` or `from_tsv` (including the
`Problem.*_df` setters) now raises `petab.v2.MissingColumnsError` if required
columns are missing, naming the table, the missing columns, and the file.
Previously, this led to unspecific errors or, e.g., for missing `estimate` or
`experimentId` columns, was silently accepted. `petablint` reports this error
without a traceback
([#610](https://github.com/PEtab-dev/libpetab-python/pull/610))
4 changes: 4 additions & 0 deletions petab/petablint.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ def main():
ret = petab.lint.lint_problem(problem)
sys.exit(ret)
case 2:
from petab.v2.core import TableError
from petab.v2.lint import (
ValidationIssueSeverity,
lint_problem,
Expand Down Expand Up @@ -232,6 +233,9 @@ def main():
# https://github.com/pydantic/pydantic/issues/7224
logger.error(f"Error in field(s) `{loc}`: {msg}")
sys.exit(1)
except TableError as e:
logger.error(str(e))
sys.exit(1)

case _:
logger.error(
Expand Down
139 changes: 109 additions & 30 deletions petab/v2/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,15 @@
"Change",
"Condition",
"ConditionTable",
"EmptyIdError",
"Experiment",
"ExperimentPeriod",
"ExperimentTable",
"Mapping",
"MappingTable",
"Measurement",
"MeasurementTable",
"MissingColumnsError",
"NoiseDistribution",
"Observable",
"ObservableTable",
Expand All @@ -82,11 +84,24 @@
"PriorDistribution",
"Problem",
"ProblemConfig",
"TableError",
]

logger = logging.getLogger(__name__)


class TableError(ValueError):
"""A PEtab table is invalid and cannot be loaded."""


class MissingColumnsError(TableError):
"""A PEtab table lacks required columns."""


class EmptyIdError(TableError):
"""A PEtab table has rows with an empty ID."""


def _field_to_column(info: ValidationInfo) -> str:
"""The PEtab column name for the validated field."""
return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get(
Expand Down Expand Up @@ -138,6 +153,59 @@ def _reset_index(df: pd.DataFrame) -> pd.DataFrame:
return df.reset_index(drop=all(name is None for name in df.index.names))


def _prepare_table_df(
df: pd.DataFrame | None,
table_name: str,
required_columns: list[str],
id_column: str | None = None,
rel_path: str | Path | AnyUrl | None = None,
base_path: str | Path | AnyUrl | None = None,
**_,
) -> pd.DataFrame | None:
"""Prepare a DataFrame for creating a PEtab table.

Moves named index levels to columns and checks for required columns
and empty IDs.

:param df: The table.
:param table_name: The table name for the error message.
:param required_columns: The required columns.
:param id_column: The ID column by which rows are grouped into
elements. Empty values are rejected here, because grouping would
drop those rows. All other values are validated with the elements.
:param rel_path: The table file, for the error message.
:param base_path: The base path of ``rel_path``.
:return: The prepared DataFrame, or ``None`` if ``df`` is ``None`` or
has no columns, i.e., the table is empty.
:raises MissingColumnsError: If any required column is missing.
:raises EmptyIdError: If any row has an empty ID.
"""
if df is None:
return None
df = _reset_index(df)
if df.columns.empty:
return None
file = (
f" File: {_generate_path(rel_path, base_path)}"
if rel_path is not None
else ""
)
if missing := [c for c in required_columns if c not in df.columns]:
raise MissingColumnsError(
f"{table_name} is missing required column(s): "
f"{', '.join(missing)}.{file}"
)
if id_column is not None:
ids = df[id_column]
if (empty := ids.isna() | (ids == "")).any():
rows = df[empty].to_string(index=False, max_rows=10)
raise EmptyIdError(
f"{table_name} has {empty.sum()} row(s) with empty "
f"{id_column}.{file}\n{rows}"
)
return df


def _column_name(name: str, field: FieldInfo) -> str:
"""Get the table column name for a model field.

Expand Down Expand Up @@ -274,6 +342,9 @@ class BaseTable[T: BaseModel](BaseModel):

#: Columns that are always included, even if empty.
_required_columns: ClassVar[list[str]] = []
#: The ID column by which rows are grouped into elements, if any.
#: Checked for empty values in :meth:`from_df`.
_id_column: ClassVar[str | None] = None

def __init__(self, elements: list[T] | None = None, **kwargs) -> None:
"""Initialize the BaseTable with a list of elements."""
Expand Down Expand Up @@ -301,10 +372,35 @@ def __getitem__(self, id_: str) -> T:

raise KeyError(f"{T.__name__} ID {id_} not found")

@classmethod
def from_df(cls, df: pd.DataFrame | None, **kwargs) -> BaseTable[T]:
"""Create a table from a DataFrame.

:param df: The table. Named index levels are treated as columns.
``None`` or a DataFrame without any columns gives an empty table.
:param kwargs: Passed to the constructor
(e.g., ``rel_path``, ``base_path``).
:raises MissingColumnsError: If any required column is missing.
:raises EmptyIdError: If any row has an empty ID.
"""
df = _prepare_table_df(
df,
cls.__name__,
cls._required_columns,
id_column=cls._id_column,
**kwargs,
)
if df is None:
return cls(**kwargs)
return cls._from_df(df, **kwargs)

@classmethod
@abstractmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]:
"""Create a table from a DataFrame."""
def _from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]:
"""Create a table from a DataFrame with all required columns.

``df`` has no named index levels.
"""

def to_df(
self, *, columns: TableColumns | str | None = None
Expand Down Expand Up @@ -523,12 +619,10 @@ def free_symbols(self) -> set[sp.Symbol]:
)

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable:
"""Create an ObservableTable from a DataFrame."""
if df is None:
return cls(**kwargs)

df = get_observable_df(df.copy())
df = get_observable_df(df)
observables = [
Observable(**row.to_dict())
for _, row in _reset_index(df).iterrows()
Expand Down Expand Up @@ -647,18 +741,16 @@ class ConditionTable(BaseTable[Condition]):
"""PEtab condition table."""

_required_columns: ClassVar[list[str]] = C.CONDITION_DF_REQUIRED_COLS
_id_column: ClassVar[str] = C.CONDITION_ID

@property
def conditions(self) -> list[Condition]:
"""List of conditions."""
return self.elements

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
"""Create a ConditionTable from a DataFrame."""
if df is None or df.empty:
return cls(**kwargs)

conditions = []
for condition_id, sub_df in df.groupby(C.CONDITION_ID):
changes = [
Expand Down Expand Up @@ -810,17 +902,16 @@ class ExperimentTable(BaseTable[Experiment]):
"""PEtab experiment table."""

_required_columns: ClassVar[list[str]] = C.EXPERIMENT_DF_REQUIRED_COLS
_id_column: ClassVar[str] = C.EXPERIMENT_ID

@property
def experiments(self) -> list[Experiment]:
"""List of experiments."""
return self.elements

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable:
"""Create an ExperimentTable from a DataFrame."""
if df is None:
return cls(**kwargs)

experiments = []
for experiment_id, cur_exp_df in df.groupby(C.EXPERIMENT_ID):
Expand Down Expand Up @@ -952,12 +1043,9 @@ def measurements(self) -> list[Measurement]:
return self.elements

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
"""Create a MeasurementTable from a DataFrame."""
if df is None:
return cls(**kwargs)

df = _reset_index(df)
if C.MODEL_ID in df.columns:
df[C.MODEL_ID] = df[C.MODEL_ID].apply(_convert_nan_to_none)

Expand Down Expand Up @@ -1036,14 +1124,10 @@ def mappings(self) -> list[Mapping]:
return self.elements

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable:
"""Create a MappingTable from a DataFrame."""
if df is None:
return cls(**kwargs)

mappings = [
Mapping(**row.to_dict()) for _, row in _reset_index(df).iterrows()
]
mappings = [Mapping(**row.to_dict()) for _, row in df.iterrows()]
return cls(mappings, **kwargs)

def _to_df(self) -> pd.DataFrame:
Expand Down Expand Up @@ -1261,15 +1345,10 @@ def parameters(self) -> list[Parameter]:
return self.elements

@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable:
"""Create a ParameterTable from a DataFrame."""
if df is None:
return cls(**kwargs)

parameters = [
Parameter(**row.to_dict())
for _, row in _reset_index(df).iterrows()
]
parameters = [Parameter(**row.to_dict()) for _, row in df.iterrows()]

return cls(parameters, **kwargs)

Expand Down
5 changes: 5 additions & 0 deletions petab/v2/extensions/sciml.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ def elements(self) -> list[Hybridization]:
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> HybridizationTable:
"""Create a HybridizationTable from a DataFrame."""
from ..core import _prepare_table_df

df = _prepare_table_df(
df, cls.__name__, [C.TARGET_ID, C.TARGET_VALUE], **kwargs
)
if df is None:
return cls(**kwargs)

Expand Down
Loading
Loading