Skip to content

Commit fe57f68

Browse files
dweindlclaude
andcommitted
v2: check for missing required columns when loading tables
Creating v2 tables from DataFrames or TSV files now raises `MissingColumnsError` if required columns are missing, naming the table, the missing columns, and the file. Previously, this resulted in unspecific pydantic errors or `KeyError`s, or was silently accepted (e.g., a missing `estimate` column defaulted to `True`). `petablint` reports this error without a traceback. `BaseTable.from_df` now handles `None`/empty input, moves named index levels to columns, and checks required columns before delegating to the new abstract `_from_df`. The sciml `HybridizationTable` gets the same check. Relates to #369. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d21ee3b commit fe57f68

6 files changed

Lines changed: 186 additions & 30 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
v2: Creating a table via `from_df` or `from_tsv` (including the
2+
`Problem.*_df` setters) now raises `petab.v2.MissingColumnsError` if required
3+
columns are missing, naming the table, the missing columns, and the file.
4+
Previously, this led to unspecific errors or, e.g., for missing `estimate` or
5+
`experimentId` columns, was silently accepted. `petablint` reports this error
6+
without a traceback
7+
([#XXX](https://github.com/PEtab-dev/libpetab-python/pull/XXX))

‎petab/petablint.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +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
205206
from petab.v2.lint import (
206207
ValidationIssueSeverity,
207208
lint_problem,
@@ -232,6 +233,9 @@ def main():
232233
# https://github.com/pydantic/pydantic/issues/7224
233234
logger.error(f"Error in field(s) `{loc}`: {msg}")
234235
sys.exit(1)
236+
except MissingColumnsError as e:
237+
logger.error(str(e))
238+
sys.exit(1)
235239

236240
case _:
237241
logger.error(

‎petab/v2/core.py‎

Lines changed: 73 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
"MappingTable",
7474
"Measurement",
7575
"MeasurementTable",
76+
"MissingColumnsError",
7677
"NoiseDistribution",
7778
"Observable",
7879
"ObservableTable",
@@ -87,6 +88,10 @@
8788
logger = logging.getLogger(__name__)
8889

8990

91+
class MissingColumnsError(ValueError):
92+
"""A PEtab table lacks required columns."""
93+
94+
9095
def _field_to_column(info: ValidationInfo) -> str:
9196
"""The PEtab column name for the validated field."""
9297
return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get(
@@ -138,6 +143,43 @@ def _reset_index(df: pd.DataFrame) -> pd.DataFrame:
138143
return df.reset_index(drop=all(name is None for name in df.index.names))
139144

140145

146+
def _prepare_table_df(
147+
df: pd.DataFrame | None,
148+
table_name: str,
149+
required_columns: list[str],
150+
rel_path: str | Path | AnyUrl | None = None,
151+
base_path: str | Path | AnyUrl | None = None,
152+
**_,
153+
) -> pd.DataFrame | None:
154+
"""Prepare a DataFrame for creating a PEtab table.
155+
156+
Moves named index levels to columns and checks for required columns.
157+
158+
:param df: The table.
159+
:param table_name: The table name for the error message.
160+
:param required_columns: The required columns.
161+
:param rel_path: The table file, for the error message.
162+
:param base_path: The base path of ``rel_path``.
163+
:return: The prepared DataFrame, or ``None`` if ``df`` is ``None`` or
164+
has no columns, i.e., the table is empty.
165+
:raises MissingColumnsError: If any required column is missing.
166+
"""
167+
if df is None:
168+
return None
169+
df = _reset_index(df)
170+
if df.columns.empty:
171+
return None
172+
if missing := [c for c in required_columns if c not in df.columns]:
173+
msg = (
174+
f"{table_name} is missing required column(s): "
175+
f"{', '.join(missing)}."
176+
)
177+
if rel_path is not None:
178+
msg += f" File: {_generate_path(rel_path, base_path)}"
179+
raise MissingColumnsError(msg)
180+
return df
181+
182+
141183
def _column_name(name: str, field: FieldInfo) -> str:
142184
"""Get the table column name for a model field.
143185
@@ -301,10 +343,30 @@ def __getitem__(self, id_: str) -> T:
301343

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

346+
@classmethod
347+
def from_df(cls, df: pd.DataFrame | None, **kwargs) -> BaseTable[T]:
348+
"""Create a table from a DataFrame.
349+
350+
:param df: The table. Named index levels are treated as columns.
351+
``None`` or a DataFrame without any columns gives an empty table.
352+
:param kwargs: Passed to the constructor
353+
(e.g., ``rel_path``, ``base_path``).
354+
:raises MissingColumnsError: If any required column is missing.
355+
"""
356+
df = _prepare_table_df(
357+
df, cls.__name__, cls._required_columns, **kwargs
358+
)
359+
if df is None:
360+
return cls(**kwargs)
361+
return cls._from_df(df, **kwargs)
362+
304363
@classmethod
305364
@abstractmethod
306-
def from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]:
307-
"""Create a table from a DataFrame."""
365+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> BaseTable[T]:
366+
"""Create a table from a DataFrame with all required columns.
367+
368+
``df`` has no named index levels.
369+
"""
308370

309371
def to_df(
310372
self, *, columns: TableColumns | str | None = None
@@ -523,12 +585,10 @@ def free_symbols(self) -> set[sp.Symbol]:
523585
)
524586

525587
@classmethod
526-
def from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable:
588+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable:
527589
"""Create an ObservableTable from a DataFrame."""
528-
if df is None:
529-
return cls(**kwargs)
530590

531-
df = get_observable_df(df.copy())
591+
df = get_observable_df(df)
532592
observables = [
533593
Observable(**row.to_dict())
534594
for _, row in _reset_index(df).iterrows()
@@ -654,11 +714,8 @@ def conditions(self) -> list[Condition]:
654714
return self.elements
655715

656716
@classmethod
657-
def from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
717+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
658718
"""Create a ConditionTable from a DataFrame."""
659-
if df is None or df.empty:
660-
return cls(**kwargs)
661-
662719
conditions = []
663720
for condition_id, sub_df in df.groupby(C.CONDITION_ID):
664721
changes = [
@@ -817,10 +874,8 @@ def experiments(self) -> list[Experiment]:
817874
return self.elements
818875

819876
@classmethod
820-
def from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable:
877+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable:
821878
"""Create an ExperimentTable from a DataFrame."""
822-
if df is None:
823-
return cls(**kwargs)
824879

825880
experiments = []
826881
for experiment_id, cur_exp_df in df.groupby(C.EXPERIMENT_ID):
@@ -952,12 +1007,9 @@ def measurements(self) -> list[Measurement]:
9521007
return self.elements
9531008

9541009
@classmethod
955-
def from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
1010+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
9561011
"""Create a MeasurementTable from a DataFrame."""
957-
if df is None:
958-
return cls(**kwargs)
9591012

960-
df = _reset_index(df)
9611013
if C.MODEL_ID in df.columns:
9621014
df[C.MODEL_ID] = df[C.MODEL_ID].apply(_convert_nan_to_none)
9631015

@@ -1036,14 +1088,10 @@ def mappings(self) -> list[Mapping]:
10361088
return self.elements
10371089

10381090
@classmethod
1039-
def from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable:
1091+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable:
10401092
"""Create a MappingTable from a DataFrame."""
1041-
if df is None:
1042-
return cls(**kwargs)
10431093

1044-
mappings = [
1045-
Mapping(**row.to_dict()) for _, row in _reset_index(df).iterrows()
1046-
]
1094+
mappings = [Mapping(**row.to_dict()) for _, row in df.iterrows()]
10471095
return cls(mappings, **kwargs)
10481096

10491097
def _to_df(self) -> pd.DataFrame:
@@ -1261,15 +1309,10 @@ def parameters(self) -> list[Parameter]:
12611309
return self.elements
12621310

12631311
@classmethod
1264-
def from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable:
1312+
def _from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable:
12651313
"""Create a ParameterTable from a DataFrame."""
1266-
if df is None:
1267-
return cls(**kwargs)
12681314

1269-
parameters = [
1270-
Parameter(**row.to_dict())
1271-
for _, row in _reset_index(df).iterrows()
1272-
]
1315+
parameters = [Parameter(**row.to_dict()) for _, row in df.iterrows()]
12731316

12741317
return cls(parameters, **kwargs)
12751318

‎petab/v2/extensions/sciml.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ def elements(self) -> list[Hybridization]:
7979
@classmethod
8080
def from_df(cls, df: pd.DataFrame, **kwargs) -> HybridizationTable:
8181
"""Create a HybridizationTable from a DataFrame."""
82+
from ..core import _prepare_table_df
83+
84+
df = _prepare_table_df(
85+
df, cls.__name__, [C.TARGET_ID, C.TARGET_VALUE], **kwargs
86+
)
8287
if df is None:
8388
return cls(**kwargs)
8489

‎tests/v2/test_core.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ def test_condition_table_round_trip():
9595
pd.DataFrame(
9696
{
9797
C.OBSERVABLE_ID: ["obs1", "obs2"],
98+
C.EXPERIMENT_ID: ["exp1", "exp1"],
9899
C.TIME: [0.0, 1.0],
99100
C.MEASUREMENT: [1.0, 2.0],
100101
}
@@ -129,6 +130,72 @@ def test_from_df_ignores_unnamed_index(table_cls, df):
129130
assert table2 == table
130131

131132

133+
_VALID_TABLE_ROWS = {
134+
ObservableTable: {
135+
C.OBSERVABLE_ID: "obs1",
136+
C.OBSERVABLE_FORMULA: "x",
137+
C.NOISE_FORMULA: "1",
138+
},
139+
ConditionTable: {
140+
C.CONDITION_ID: "c1",
141+
C.TARGET_ID: "x",
142+
C.TARGET_VALUE: "1",
143+
},
144+
ExperimentTable: {
145+
C.EXPERIMENT_ID: "e1",
146+
C.TIME: 0.0,
147+
C.CONDITION_ID: "c1",
148+
},
149+
MeasurementTable: {
150+
C.OBSERVABLE_ID: "obs1",
151+
C.EXPERIMENT_ID: "e1",
152+
C.TIME: 1.0,
153+
C.MEASUREMENT: 2.0,
154+
},
155+
ParameterTable: {
156+
C.PARAMETER_ID: "p1",
157+
C.LOWER_BOUND: 0.0,
158+
C.UPPER_BOUND: 1.0,
159+
C.NOMINAL_VALUE: 0.5,
160+
C.ESTIMATE: "true",
161+
},
162+
MappingTable: {
163+
PETAB_ENTITY_ID: "a",
164+
MODEL_ENTITY_ID: "1a",
165+
},
166+
}
167+
168+
169+
@pytest.mark.parametrize(
170+
"table_cls", _VALID_TABLE_ROWS, ids=lambda cls: cls.__name__
171+
)
172+
def test_from_df_missing_required_columns(table_cls):
173+
"""Missing required columns are reported."""
174+
row = _VALID_TABLE_ROWS[table_cls]
175+
assert set(row) == set(table_cls._required_columns)
176+
df = pd.DataFrame([row])
177+
table = table_cls.from_df(df)
178+
assert len(table.elements) == 1
179+
# required columns may be in the index
180+
assert table_cls.from_df(df.set_index(df.columns[0])) == table
181+
assert table_cls.from_df(df.set_index(list(df.columns))) == table
182+
# a DataFrame without any columns is an empty table
183+
assert table_cls.from_df(pd.DataFrame()).elements == []
184+
185+
for column in row:
186+
with pytest.raises(
187+
MissingColumnsError, match=f"column.*: {column}\\.$"
188+
):
189+
table_cls.from_df(df.drop(columns=column))
190+
191+
with tempfile.TemporaryDirectory() as tmp_dir:
192+
df.drop(columns=df.columns[-1]).to_csv(
193+
Path(tmp_dir, "table.tsv"), sep="\t", index=False
194+
)
195+
with pytest.raises(MissingColumnsError, match=r"File: .*table\.tsv"):
196+
table_cls.from_tsv("table.tsv", base_path=tmp_dir)
197+
198+
132199
@pytest.mark.filterwarnings(
133200
"ignore:.*Parameter scales are not supported in PEtab v2.*:UserWarning"
134201
)
@@ -1242,6 +1309,20 @@ def test_petablint_v2(tmpdir):
12421309
)
12431310
assert result.returncode == 1
12441311

1312+
# missing required columns are reported without a traceback
1313+
parameter_file = Path(tmpdir, problem.parameter_tables[0].rel_path)
1314+
df = pd.read_csv(parameter_file, sep="\t")
1315+
df.drop(columns=C.ESTIMATE).to_csv(parameter_file, sep="\t", index=False)
1316+
result = subprocess.run( # noqa S607
1317+
["petablint", str(Path(tmpdir, "problem.yaml"))], # noqa S607
1318+
capture_output=True,
1319+
text=True,
1320+
)
1321+
output = result.stdout + result.stderr
1322+
assert result.returncode == 1
1323+
assert "ParameterTable is missing required column(s): estimate" in output
1324+
assert "Traceback" not in output
1325+
12451326

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

‎tests/v2/test_sciml.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pandas as pd
23
import pytest
34
from petab_sciml import Input, Node
45
from pydantic import ConfigDict
@@ -327,6 +328,21 @@ def test_hybridization_table_to_df_petab_math():
327328
assert table.to_df()[C.TARGET_VALUE].tolist() == ["x ^ 2", "abs(y)"]
328329

329330

331+
def test_hybridization_table_missing_required_columns():
332+
"""Missing required columns are reported."""
333+
df = pd.DataFrame({C.TARGET_ID: ["a"], C.TARGET_VALUE: ["x"]})
334+
assert len(HybridizationTable.from_df(df).elements) == 1
335+
assert (
336+
len(HybridizationTable.from_df(df.set_index(C.TARGET_ID)).elements)
337+
== 1
338+
)
339+
for column in df.columns:
340+
with pytest.raises(
341+
MissingColumnsError, match=f"column.*: {column}\\.$"
342+
):
343+
HybridizationTable.from_df(df.drop(columns=column))
344+
345+
330346
def test_hybridization_pre_initialization_not_evaluable():
331347
problem = _get_test_problem()
332348
# net1_input1 is assigned the species `A`, which is not available before

0 commit comments

Comments
 (0)