|
66 | 66 | "Change", |
67 | 67 | "Condition", |
68 | 68 | "ConditionTable", |
| 69 | + "EmptyIdError", |
69 | 70 | "Experiment", |
70 | 71 | "ExperimentPeriod", |
71 | 72 | "ExperimentTable", |
|
83 | 84 | "PriorDistribution", |
84 | 85 | "Problem", |
85 | 86 | "ProblemConfig", |
| 87 | + "TableError", |
86 | 88 | ] |
87 | 89 |
|
88 | 90 | logger = logging.getLogger(__name__) |
89 | 91 |
|
90 | 92 |
|
91 | | -class MissingColumnsError(ValueError): |
| 93 | +class TableError(ValueError): |
| 94 | + """A PEtab table is invalid and cannot be loaded.""" |
| 95 | + |
| 96 | + |
| 97 | +class MissingColumnsError(TableError): |
92 | 98 | """A PEtab table lacks required columns.""" |
93 | 99 |
|
94 | 100 |
|
| 101 | +class EmptyIdError(TableError): |
| 102 | + """A PEtab table has rows with an empty ID.""" |
| 103 | + |
| 104 | + |
95 | 105 | def _field_to_column(info: ValidationInfo) -> str: |
96 | 106 | """The PEtab column name for the validated field.""" |
97 | 107 | return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get( |
@@ -147,36 +157,52 @@ def _prepare_table_df( |
147 | 157 | df: pd.DataFrame | None, |
148 | 158 | table_name: str, |
149 | 159 | required_columns: list[str], |
| 160 | + id_column: str | None = None, |
150 | 161 | rel_path: str | Path | AnyUrl | None = None, |
151 | 162 | base_path: str | Path | AnyUrl | None = None, |
152 | 163 | **_, |
153 | 164 | ) -> pd.DataFrame | None: |
154 | 165 | """Prepare a DataFrame for creating a PEtab table. |
155 | 166 |
|
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. |
157 | 169 |
|
158 | 170 | :param df: The table. |
159 | 171 | :param table_name: The table name for the error message. |
160 | 172 | :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. |
161 | 176 | :param rel_path: The table file, for the error message. |
162 | 177 | :param base_path: The base path of ``rel_path``. |
163 | 178 | :return: The prepared DataFrame, or ``None`` if ``df`` is ``None`` or |
164 | 179 | has no columns, i.e., the table is empty. |
165 | 180 | :raises MissingColumnsError: If any required column is missing. |
| 181 | + :raises EmptyIdError: If any row has an empty ID. |
166 | 182 | """ |
167 | 183 | if df is None: |
168 | 184 | return None |
169 | 185 | df = _reset_index(df) |
170 | 186 | if df.columns.empty: |
171 | 187 | return None |
| 188 | + file = ( |
| 189 | + f" File: {_generate_path(rel_path, base_path)}" |
| 190 | + if rel_path is not None |
| 191 | + else "" |
| 192 | + ) |
172 | 193 | if missing := [c for c in required_columns if c not in df.columns]: |
173 | | - msg = ( |
| 194 | + raise MissingColumnsError( |
174 | 195 | f"{table_name} is missing required column(s): " |
175 | | - f"{', '.join(missing)}." |
| 196 | + f"{', '.join(missing)}.{file}" |
176 | 197 | ) |
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 | + ) |
180 | 206 | return df |
181 | 207 |
|
182 | 208 |
|
@@ -316,6 +342,9 @@ class BaseTable[T: BaseModel](BaseModel): |
316 | 342 |
|
317 | 343 | #: Columns that are always included, even if empty. |
318 | 344 | _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 |
319 | 348 |
|
320 | 349 | def __init__(self, elements: list[T] | None = None, **kwargs) -> None: |
321 | 350 | """Initialize the BaseTable with a list of elements.""" |
@@ -352,9 +381,14 @@ def from_df(cls, df: pd.DataFrame | None, **kwargs) -> BaseTable[T]: |
352 | 381 | :param kwargs: Passed to the constructor |
353 | 382 | (e.g., ``rel_path``, ``base_path``). |
354 | 383 | :raises MissingColumnsError: If any required column is missing. |
| 384 | + :raises EmptyIdError: If any row has an empty ID. |
355 | 385 | """ |
356 | 386 | 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, |
358 | 392 | ) |
359 | 393 | if df is None: |
360 | 394 | return cls(**kwargs) |
@@ -707,6 +741,7 @@ class ConditionTable(BaseTable[Condition]): |
707 | 741 | """PEtab condition table.""" |
708 | 742 |
|
709 | 743 | _required_columns: ClassVar[list[str]] = C.CONDITION_DF_REQUIRED_COLS |
| 744 | + _id_column: ClassVar[str] = C.CONDITION_ID |
710 | 745 |
|
711 | 746 | @property |
712 | 747 | def conditions(self) -> list[Condition]: |
@@ -867,6 +902,7 @@ class ExperimentTable(BaseTable[Experiment]): |
867 | 902 | """PEtab experiment table.""" |
868 | 903 |
|
869 | 904 | _required_columns: ClassVar[list[str]] = C.EXPERIMENT_DF_REQUIRED_COLS |
| 905 | + _id_column: ClassVar[str] = C.EXPERIMENT_ID |
870 | 906 |
|
871 | 907 | @property |
872 | 908 | def experiments(self) -> list[Experiment]: |
|
0 commit comments