|
73 | 73 | "MappingTable", |
74 | 74 | "Measurement", |
75 | 75 | "MeasurementTable", |
| 76 | + "MissingColumnsError", |
76 | 77 | "NoiseDistribution", |
77 | 78 | "Observable", |
78 | 79 | "ObservableTable", |
|
87 | 88 | logger = logging.getLogger(__name__) |
88 | 89 |
|
89 | 90 |
|
| 91 | +class MissingColumnsError(ValueError): |
| 92 | + """A PEtab table lacks required columns.""" |
| 93 | + |
| 94 | + |
90 | 95 | def _field_to_column(info: ValidationInfo) -> str: |
91 | 96 | """The PEtab column name for the validated field.""" |
92 | 97 | return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get( |
@@ -138,6 +143,43 @@ def _reset_index(df: pd.DataFrame) -> pd.DataFrame: |
138 | 143 | return df.reset_index(drop=all(name is None for name in df.index.names)) |
139 | 144 |
|
140 | 145 |
|
| 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 | + |
141 | 183 | def _column_name(name: str, field: FieldInfo) -> str: |
142 | 184 | """Get the table column name for a model field. |
143 | 185 |
|
@@ -301,10 +343,30 @@ def __getitem__(self, id_: str) -> T: |
301 | 343 |
|
302 | 344 | raise KeyError(f"{T.__name__} ID {id_} not found") |
303 | 345 |
|
| 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 | + |
304 | 363 | @classmethod |
305 | 364 | @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 | + """ |
308 | 370 |
|
309 | 371 | def to_df( |
310 | 372 | self, *, columns: TableColumns | str | None = None |
@@ -523,12 +585,10 @@ def free_symbols(self) -> set[sp.Symbol]: |
523 | 585 | ) |
524 | 586 |
|
525 | 587 | @classmethod |
526 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable: |
| 588 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable: |
527 | 589 | """Create an ObservableTable from a DataFrame.""" |
528 | | - if df is None: |
529 | | - return cls(**kwargs) |
530 | 590 |
|
531 | | - df = get_observable_df(df.copy()) |
| 591 | + df = get_observable_df(df) |
532 | 592 | observables = [ |
533 | 593 | Observable(**row.to_dict()) |
534 | 594 | for _, row in _reset_index(df).iterrows() |
@@ -654,11 +714,8 @@ def conditions(self) -> list[Condition]: |
654 | 714 | return self.elements |
655 | 715 |
|
656 | 716 | @classmethod |
657 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable: |
| 717 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable: |
658 | 718 | """Create a ConditionTable from a DataFrame.""" |
659 | | - if df is None or df.empty: |
660 | | - return cls(**kwargs) |
661 | | - |
662 | 719 | conditions = [] |
663 | 720 | for condition_id, sub_df in df.groupby(C.CONDITION_ID): |
664 | 721 | changes = [ |
@@ -817,10 +874,8 @@ def experiments(self) -> list[Experiment]: |
817 | 874 | return self.elements |
818 | 875 |
|
819 | 876 | @classmethod |
820 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable: |
| 877 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable: |
821 | 878 | """Create an ExperimentTable from a DataFrame.""" |
822 | | - if df is None: |
823 | | - return cls(**kwargs) |
824 | 879 |
|
825 | 880 | experiments = [] |
826 | 881 | for experiment_id, cur_exp_df in df.groupby(C.EXPERIMENT_ID): |
@@ -952,12 +1007,9 @@ def measurements(self) -> list[Measurement]: |
952 | 1007 | return self.elements |
953 | 1008 |
|
954 | 1009 | @classmethod |
955 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable: |
| 1010 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable: |
956 | 1011 | """Create a MeasurementTable from a DataFrame.""" |
957 | | - if df is None: |
958 | | - return cls(**kwargs) |
959 | 1012 |
|
960 | | - df = _reset_index(df) |
961 | 1013 | if C.MODEL_ID in df.columns: |
962 | 1014 | df[C.MODEL_ID] = df[C.MODEL_ID].apply(_convert_nan_to_none) |
963 | 1015 |
|
@@ -1036,14 +1088,10 @@ def mappings(self) -> list[Mapping]: |
1036 | 1088 | return self.elements |
1037 | 1089 |
|
1038 | 1090 | @classmethod |
1039 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable: |
| 1091 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable: |
1040 | 1092 | """Create a MappingTable from a DataFrame.""" |
1041 | | - if df is None: |
1042 | | - return cls(**kwargs) |
1043 | 1093 |
|
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()] |
1047 | 1095 | return cls(mappings, **kwargs) |
1048 | 1096 |
|
1049 | 1097 | def _to_df(self) -> pd.DataFrame: |
@@ -1261,15 +1309,10 @@ def parameters(self) -> list[Parameter]: |
1261 | 1309 | return self.elements |
1262 | 1310 |
|
1263 | 1311 | @classmethod |
1264 | | - def from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable: |
| 1312 | + def _from_df(cls, df: pd.DataFrame, **kwargs) -> ParameterTable: |
1265 | 1313 | """Create a ParameterTable from a DataFrame.""" |
1266 | | - if df is None: |
1267 | | - return cls(**kwargs) |
1268 | 1314 |
|
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()] |
1273 | 1316 |
|
1274 | 1317 | return cls(parameters, **kwargs) |
1275 | 1318 |
|
|
0 commit comments