From 30630d098d9996fce0e382cfd27f921db48fc2f9 Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Wed, 25 Nov 2026 16:04:25 +0100 Subject: [PATCH] v2: reject empty condition and experiment IDs Rows with an empty `conditionId` in the condition table or an empty `experimentId` in the experiment table were silently dropped by `groupby` in `ConditionTable.from_df` and `ExperimentTable.from_df`, so neither loading nor linting reported them. Raise an `EmptyIdError` instead, naming the table, the rows, and the file. Add `TableError` as common base class of `EmptyIdError` and `MissingColumnsError`, and report it in `petablint` without a traceback. Co-Authored-By: Claude Opus 5.5 --- .../+v2-empty-condition-experiment-ids.fix.md | 6 ++ petab/petablint.py | 4 +- petab/v2/core.py | 56 +++++++++++++---- tests/v2/test_core.py | 62 ++++++++++++++++++- 4 files changed, 110 insertions(+), 18 deletions(-) create mode 100644 changelog.d/+v2-empty-condition-experiment-ids.fix.md diff --git a/changelog.d/+v2-empty-condition-experiment-ids.fix.md b/changelog.d/+v2-empty-condition-experiment-ids.fix.md new file mode 100644 index 00000000..3ffcf5f2 --- /dev/null +++ b/changelog.d/+v2-empty-condition-experiment-ids.fix.md @@ -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)) diff --git a/petab/petablint.py b/petab/petablint.py index 78846547..b75ceef1 100755 --- a/petab/petablint.py +++ b/petab/petablint.py @@ -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, @@ -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) diff --git a/petab/v2/core.py b/petab/v2/core.py index f3f294fc..3fdb4260 100644 --- a/petab/v2/core.py +++ b/petab/v2/core.py @@ -66,6 +66,7 @@ "Change", "Condition", "ConditionTable", + "EmptyIdError", "Experiment", "ExperimentPeriod", "ExperimentTable", @@ -83,6 +84,7 @@ "PriorDistribution", "Problem", "ProblemConfig", + "TableError", ] logger = logging.getLogger(__name__) @@ -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"``. @@ -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( @@ -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 @@ -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.""" @@ -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) @@ -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]: @@ -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() @@ -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]: diff --git a/tests/v2/test_core.py b/tests/v2/test_core.py index df842827..7265a360 100644 --- a/tests/v2/test_core.py +++ b/tests/v2/test_core.py @@ -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) @@ -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() @@ -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."""