Skip to content

Commit ef7cff1

Browse files
dweindlclaude
andcommitted
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 <noreply@anthropic.com>
1 parent b188bb3 commit ef7cff1

4 files changed

Lines changed: 108 additions & 10 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
`petab.v2`: Rows with empty condition IDs in the condition table or empty
2+
experiment IDs in the experiment table now raise `petab.v2.EmptyIdError` when
3+
loading, instead of being silently dropped. `petablint` reports this error
4+
without a traceback. `petab.v2.TableError` is the new common base class of
5+
`EmptyIdError` and `MissingColumnsError`
6+
([#629](https://github.com/PEtab-dev/libpetab-python/pull/629))

‎petab/petablint.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def main():
202202
ret = petab.lint.lint_problem(problem)
203203
sys.exit(ret)
204204
case 2:
205-
from petab.v2.core import MissingColumnsError
205+
from petab.v2.core import TableError
206206
from petab.v2.lint import (
207207
ValidationIssueSeverity,
208208
lint_problem,
@@ -233,7 +233,7 @@ def main():
233233
# https://github.com/pydantic/pydantic/issues/7224
234234
logger.error(f"Error in field(s) `{loc}`: {msg}")
235235
sys.exit(1)
236-
except MissingColumnsError as e:
236+
except TableError as e:
237237
logger.error(str(e))
238238
sys.exit(1)
239239

‎petab/v2/core.py‎

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"Change",
6767
"Condition",
6868
"ConditionTable",
69+
"EmptyIdError",
6970
"Experiment",
7071
"ExperimentPeriod",
7172
"ExperimentTable",
@@ -83,15 +84,24 @@
8384
"PriorDistribution",
8485
"Problem",
8586
"ProblemConfig",
87+
"TableError",
8688
]
8789

8890
logger = logging.getLogger(__name__)
8991

9092

91-
class MissingColumnsError(ValueError):
93+
class TableError(ValueError):
94+
"""A PEtab table is invalid and cannot be loaded."""
95+
96+
97+
class MissingColumnsError(TableError):
9298
"""A PEtab table lacks required columns."""
9399

94100

101+
class EmptyIdError(TableError):
102+
"""A PEtab table has rows with an empty ID."""
103+
104+
95105
def _field_to_column(info: ValidationInfo) -> str:
96106
"""The PEtab column name for the validated field."""
97107
return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get(
@@ -147,36 +157,52 @@ def _prepare_table_df(
147157
df: pd.DataFrame | None,
148158
table_name: str,
149159
required_columns: list[str],
160+
id_column: str | None = None,
150161
rel_path: str | Path | AnyUrl | None = None,
151162
base_path: str | Path | AnyUrl | None = None,
152163
**_,
153164
) -> pd.DataFrame | None:
154165
"""Prepare a DataFrame for creating a PEtab table.
155166
156-
Moves named index levels to columns and checks for required columns.
167+
Moves named index levels to columns and checks for required columns
168+
and empty IDs.
157169
158170
:param df: The table.
159171
:param table_name: The table name for the error message.
160172
:param required_columns: The required columns.
173+
:param id_column: The ID column by which rows are grouped into
174+
elements. Empty values are rejected here, because grouping would
175+
drop those rows. All other values are validated with the elements.
161176
:param rel_path: The table file, for the error message.
162177
:param base_path: The base path of ``rel_path``.
163178
:return: The prepared DataFrame, or ``None`` if ``df`` is ``None`` or
164179
has no columns, i.e., the table is empty.
165180
:raises MissingColumnsError: If any required column is missing.
181+
:raises EmptyIdError: If any row has an empty ID.
166182
"""
167183
if df is None:
168184
return None
169185
df = _reset_index(df)
170186
if df.columns.empty:
171187
return None
188+
file = (
189+
f" File: {_generate_path(rel_path, base_path)}"
190+
if rel_path is not None
191+
else ""
192+
)
172193
if missing := [c for c in required_columns if c not in df.columns]:
173-
msg = (
194+
raise MissingColumnsError(
174195
f"{table_name} is missing required column(s): "
175-
f"{', '.join(missing)}."
196+
f"{', '.join(missing)}.{file}"
176197
)
177-
if rel_path is not None:
178-
msg += f" File: {_generate_path(rel_path, base_path)}"
179-
raise MissingColumnsError(msg)
198+
if id_column is not None:
199+
ids = df[id_column]
200+
if (empty := ids.isna() | (ids == "")).any():
201+
rows = df[empty].to_string(index=False, max_rows=10)
202+
raise EmptyIdError(
203+
f"{table_name} has {empty.sum()} row(s) with empty "
204+
f"{id_column}.{file}\n{rows}"
205+
)
180206
return df
181207

182208

@@ -316,6 +342,9 @@ class BaseTable[T: BaseModel](BaseModel):
316342

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

320349
def __init__(self, elements: list[T] | None = None, **kwargs) -> None:
321350
"""Initialize the BaseTable with a list of elements."""
@@ -352,9 +381,14 @@ def from_df(cls, df: pd.DataFrame | None, **kwargs) -> BaseTable[T]:
352381
:param kwargs: Passed to the constructor
353382
(e.g., ``rel_path``, ``base_path``).
354383
:raises MissingColumnsError: If any required column is missing.
384+
:raises EmptyIdError: If any row has an empty ID.
355385
"""
356386
df = _prepare_table_df(
357-
df, cls.__name__, cls._required_columns, **kwargs
387+
df,
388+
cls.__name__,
389+
cls._required_columns,
390+
id_column=cls._id_column,
391+
**kwargs,
358392
)
359393
if df is None:
360394
return cls(**kwargs)
@@ -707,6 +741,7 @@ class ConditionTable(BaseTable[Condition]):
707741
"""PEtab condition table."""
708742

709743
_required_columns: ClassVar[list[str]] = C.CONDITION_DF_REQUIRED_COLS
744+
_id_column: ClassVar[str] = C.CONDITION_ID
710745

711746
@property
712747
def conditions(self) -> list[Condition]:
@@ -867,6 +902,7 @@ class ExperimentTable(BaseTable[Experiment]):
867902
"""PEtab experiment table."""
868903

869904
_required_columns: ClassVar[list[str]] = C.EXPERIMENT_DF_REQUIRED_COLS
905+
_id_column: ClassVar[str] = C.EXPERIMENT_ID
870906

871907
@property
872908
def experiments(self) -> list[Experiment]:

‎tests/v2/test_core.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,45 @@ def test_condition_table_from_df_condition_id():
536536
assert loaded.to_df()[CONDITION_ID].tolist() == ["c2"]
537537

538538

539+
@pytest.mark.parametrize("empty_id", [np.nan, None, ""])
540+
def test_empty_condition_and_experiment_ids(empty_id):
541+
"""Rows with empty condition or experiment IDs raise an error."""
542+
condition_df = pd.DataFrame(
543+
{
544+
CONDITION_ID: ["c1", empty_id, empty_id],
545+
TARGET_ID: ["k1", "k2", "k3"],
546+
TARGET_VALUE: [1.0, 2.0, 3.0],
547+
}
548+
)
549+
experiment_df = pd.DataFrame(
550+
{
551+
C.EXPERIMENT_ID: ["e1", empty_id, empty_id],
552+
C.TIME: [0.0, 0.0, 0.0],
553+
CONDITION_ID: ["c1", "c1", "c1"],
554+
}
555+
)
556+
with pytest.raises(
557+
EmptyIdError,
558+
match=rf"ConditionTable has 2 row\(s\) with empty {CONDITION_ID}\.",
559+
):
560+
ConditionTable.from_df(condition_df)
561+
with pytest.raises(
562+
EmptyIdError,
563+
match=rf"ExperimentTable has 2 row\(s\) with empty "
564+
rf"{C.EXPERIMENT_ID}\.",
565+
):
566+
ExperimentTable.from_df(experiment_df)
567+
568+
# valid rows only
569+
assert (
570+
ConditionTable.from_df(condition_df.iloc[:1]).conditions[0].id == "c1"
571+
)
572+
assert (
573+
ExperimentTable.from_df(experiment_df.iloc[:1]).experiments[0].id
574+
== "e1"
575+
)
576+
577+
539578
def test_condition_table():
540579
assert ConditionTable().free_symbols == set()
541580

@@ -1323,6 +1362,23 @@ def test_petablint_v2(tmpdir):
13231362
assert "ParameterTable is missing required column(s): estimate" in output
13241363
assert "Traceback" not in output
13251364

1365+
# empty condition IDs are reported without a traceback
1366+
problem.to_files(Path(tmpdir))
1367+
with open(Path(tmpdir, "conditions.tsv"), "a") as f:
1368+
f.write("\tB\t2\n")
1369+
result = subprocess.run( # noqa S607
1370+
["petablint", str(Path(tmpdir, "problem.yaml"))], # noqa S607
1371+
capture_output=True,
1372+
text=True,
1373+
)
1374+
output = result.stdout + result.stderr
1375+
assert result.returncode == 1
1376+
assert (
1377+
f"ConditionTable has 1 row(s) with empty {CONDITION_ID}. File:"
1378+
in output
1379+
)
1380+
assert "Traceback" not in output
1381+
13261382

13271383
def test_problem_id(tmpdir):
13281384
"""Test that the problem ID works as expected."""

0 commit comments

Comments
 (0)