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))
4 changes: 2 additions & 2 deletions petab/petablint.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def main():
ret = petab.lint.lint_problem(problem)
sys.exit(ret)
case 2:
from petab.v2.core import MissingColumnsError
from petab.v2.core import TableError
from petab.v2.lint import (
ValidationIssueSeverity,
lint_problem,
Expand Down Expand Up @@ -233,7 +233,7 @@ def main():
# https://github.com/pydantic/pydantic/issues/7224
logger.error(f"Error in field(s) `{loc}`: {msg}")
sys.exit(1)
except MissingColumnsError as e:
except TableError as e:
logger.error(str(e))
sys.exit(1)

Expand Down
56 changes: 43 additions & 13 deletions petab/v2/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"Change",
"Condition",
"ConditionTable",
"EmptyIdError",
"Experiment",
"ExperimentPeriod",
"ExperimentTable",
Expand All @@ -83,6 +84,7 @@
"PriorDistribution",
"Problem",
"ProblemConfig",
"TableError",
]

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -141,7 +143,11 @@ def _sympify_cached(v, info: ValidationInfo) -> sp.Basic:
return sympify_petab(v)


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


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

:param table: The table type, e.g., ``"ParameterTable"``.
Expand Down Expand Up @@ -182,6 +188,10 @@ def __init__(
super().__init__(msg)


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 @@ -237,39 +247,50 @@ 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.
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 neither rows nor 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 and len(df) == 0:
return None
file = (
_generate_path(rel_path, base_path) if rel_path is not None else None
)
if missing := [c for c in required_columns if c not in df.columns]:
raise MissingColumnsError(
table_name,
missing,
file=(
_generate_path(rel_path, base_path)
if rel_path is not None
else None
),
columns=list(df.columns),
table_name, missing, file=file, columns=list(df.columns)
)
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)
file_msg = f" File: {file}" if file is not None else ""
raise EmptyIdError(
f"{table_name} has {empty.sum()} row(s) with empty "
f"{id_column}.{file_msg}\n{rows}"
)
return df


Expand Down Expand Up @@ -421,6 +442,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 @@ -459,9 +483,14 @@ def from_df(cls, df: pd.DataFrame | None, **kwargs) -> BaseTable[T]:
(e.g., ``rel_path``, ``base_path``).
:return: The table.
: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, **kwargs
df,
cls.__name__,
cls._required_columns,
id_column=cls._id_column,
**kwargs,
)
if df is None:
return cls(**kwargs)
Expand Down Expand Up @@ -810,6 +839,7 @@ 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]:
Expand All @@ -820,9 +850,8 @@ def conditions(self) -> list[Condition]:
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
"""Create a ConditionTable from a DataFrame."""
# 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()]):
for row in _records(df):
rows_by_id.setdefault(row.pop(C.CONDITION_ID), []).append(row)

context = _new_validation_context()
Expand Down Expand Up @@ -977,6 +1006,7 @@ 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]:
Expand Down
62 changes: 59 additions & 3 deletions tests/v2/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,9 +569,9 @@ def test_condition_table_from_df_order_and_types():
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),
CONDITION_ID: ["c2", "c1", "c2", "c1"],
TARGET_ID: ["k1", "k1", "k2", "k2"],
TARGET_VALUE: pd.Series([2, 2.0, 2.0, 2], dtype=object),
}
)
conditions = ConditionTable.from_df(df)
Expand Down Expand Up @@ -624,6 +624,45 @@ def test_from_df_malformed_columns():
ParameterTable.from_df(pd.DataFrame(index=[0, 1]))


@pytest.mark.parametrize("empty_id", [np.nan, None, ""])
def test_empty_condition_and_experiment_ids(empty_id):
"""Rows with empty condition or experiment IDs raise an error."""
condition_df = pd.DataFrame(
{
CONDITION_ID: ["c1", empty_id, empty_id],
TARGET_ID: ["k1", "k2", "k3"],
TARGET_VALUE: [1.0, 2.0, 3.0],
}
)
experiment_df = pd.DataFrame(
{
C.EXPERIMENT_ID: ["e1", empty_id, empty_id],
C.TIME: [0.0, 0.0, 0.0],
CONDITION_ID: ["c1", "c1", "c1"],
}
)
with pytest.raises(
EmptyIdError,
match=rf"ConditionTable has 2 row\(s\) with empty {CONDITION_ID}\.",
):
ConditionTable.from_df(condition_df)
with pytest.raises(
EmptyIdError,
match=rf"ExperimentTable has 2 row\(s\) with empty "
rf"{C.EXPERIMENT_ID}\.",
):
ExperimentTable.from_df(experiment_df)

# valid rows only
assert (
ConditionTable.from_df(condition_df.iloc[:1]).conditions[0].id == "c1"
)
assert (
ExperimentTable.from_df(experiment_df.iloc[:1]).experiments[0].id
== "e1"
)


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

Expand Down Expand Up @@ -1411,6 +1450,23 @@ def test_petablint_v2(tmpdir):
assert "ParameterTable is missing required column(s): estimate" in output
assert "Traceback" not in output

# empty condition IDs are reported without a traceback
problem.to_files(Path(tmpdir))
with open(Path(tmpdir, "conditions.tsv"), "a") as f:
f.write("\tB\t2\n")
result = subprocess.run( # noqa S607
["petablint", str(Path(tmpdir, "problem.yaml"))], # noqa S607
capture_output=True,
text=True,
)
output = result.stdout + result.stderr
assert result.returncode == 1
assert (
f"ConditionTable has 1 row(s) with empty {CONDITION_ID}. File:"
in output
)
assert "Traceback" not in output


def test_problem_id(tmpdir):
"""Test that the problem ID works as expected."""
Expand Down
Loading