forked from PEtab-dev/libpetab-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
2379 lines (2000 loc) · 74.6 KB
/
core.py
File metadata and controls
2379 lines (2000 loc) · 74.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Types around the PEtab object model."""
from __future__ import annotations
import copy
import logging
import os
import tempfile
import traceback
from abc import abstractmethod
from collections.abc import Sequence
from enum import Enum
from itertools import chain
from math import nan
from numbers import Number
from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any, Generic, TypeVar, get_args
import numpy as np
import pandas as pd
import sympy as sp
from pydantic import (
AfterValidator,
AnyUrl,
BaseModel,
BeforeValidator,
ConfigDict,
Field,
ValidationInfo,
field_serializer,
field_validator,
model_validator,
)
from typing_extensions import Self
from .._utils import _generate_path
from ..v1 import (
validate_yaml_syntax,
yaml,
)
from ..v1.distributions import *
from ..v1.lint import is_valid_identifier
from ..v1.math import petab_math_str, sympify_petab
from ..v1.models.model import Model, model_factory
from ..v1.yaml import get_path_prefix
from ..versions import parse_version
from . import C, get_observable_df
if TYPE_CHECKING:
from ..v2.lint import ValidationResultList, ValidationTask
__all__ = [
"Problem",
"ProblemConfig",
"Observable",
"ObservableTable",
"NoiseDistribution",
"Change",
"Condition",
"ConditionTable",
"ExperimentPeriod",
"Experiment",
"ExperimentTable",
"Measurement",
"MeasurementTable",
"Mapping",
"MappingTable",
"Parameter",
"ParameterScale",
"ParameterTable",
]
def _is_finite_or_neg_inf(v: float, info: ValidationInfo) -> float:
if not np.isfinite(v) and v != -np.inf:
raise ValueError(
f"{info.field_name} value must be finite or -inf but got {v}"
)
return v
def _is_finite_or_pos_inf(v: float, info: ValidationInfo) -> float:
if not np.isfinite(v) and v != np.inf:
raise ValueError(
f"{info.field_name} value must be finite or inf but got {v}"
)
return v
def _not_nan(v: float, info: ValidationInfo) -> float:
if np.isnan(v):
raise ValueError(f"{info.field_name} value must not be nan.")
return v
def _convert_nan_to_none(v):
"""Convert NaN or "" to None."""
if isinstance(v, float) and np.isnan(v):
return None
if isinstance(v, str) and v == "":
return None
return v
def _valid_petab_id(v: str) -> str:
"""Field validator for PEtab IDs."""
if not v:
raise ValueError("ID must not be empty.")
if not is_valid_identifier(v):
raise ValueError(f"Invalid ID: {v}")
return v
def _valid_petab_id_or_none(v: str) -> str:
"""Field validator for optional PEtab IDs."""
if not v:
return None
if not is_valid_identifier(v):
raise ValueError(f"Invalid ID: {v}")
return v
class ParameterScale(str, Enum):
"""Parameter scales.
Parameter scales as used in the PEtab parameter table.
"""
LIN = C.LIN
LOG = C.LOG
LOG10 = C.LOG10
class NoiseDistribution(str, Enum):
"""Noise distribution types.
Noise distributions as used in the PEtab observable table.
"""
#: Normal distribution
NORMAL = C.NORMAL
#: Laplace distribution
LAPLACE = C.LAPLACE
#: Log-normal distribution
LOG_NORMAL = C.LOG_NORMAL
#: Log-Laplace distribution
LOG_LAPLACE = C.LOG_LAPLACE
#: Log10-Normal
LOG10_NORMAL = C.LOG10_NORMAL
class PriorDistribution(str, Enum):
"""Prior types.
Prior types as used in the PEtab parameter table.
"""
#: Cauchy distribution.
CAUCHY = C.CAUCHY
#: Chi-squared distribution.
CHI_SQUARED = C.CHI_SQUARED
#: Exponential distribution.
EXPONENTIAL = C.EXPONENTIAL
#: Gamma distribution.
GAMMA = C.GAMMA
#: Laplace distribution.
LAPLACE = C.LAPLACE
#: Log10-normal distribution.
LOG10_NORMAL = C.LOG10_NORMAL
#: Log-Laplace distribution
LOG_LAPLACE = C.LOG_LAPLACE
#: Log-normal distribution.
LOG_NORMAL = C.LOG_NORMAL
#: Log-uniform distribution.
LOG_UNIFORM = C.LOG_UNIFORM
#: Normal distribution.
NORMAL = C.NORMAL
#: Rayleigh distribution.
RAYLEIGH = C.RAYLEIGH
#: Uniform distribution.
UNIFORM = C.UNIFORM
assert set(C.PRIOR_DISTRIBUTIONS) == {e.value for e in PriorDistribution}, (
"PriorDistribution enum does not match C.PRIOR_DISTRIBUTIONS "
f"{set(C.PRIOR_DISTRIBUTIONS)} vs { {e.value for e in PriorDistribution} }"
)
_prior_to_cls = {
PriorDistribution.CAUCHY: Cauchy,
PriorDistribution.CHI_SQUARED: ChiSquare,
PriorDistribution.EXPONENTIAL: Exponential,
PriorDistribution.GAMMA: Gamma,
PriorDistribution.LAPLACE: Laplace,
PriorDistribution.LOG10_NORMAL: Normal,
PriorDistribution.LOG_LAPLACE: Laplace,
PriorDistribution.LOG_NORMAL: Normal,
PriorDistribution.LOG_UNIFORM: Uniform,
PriorDistribution.NORMAL: Normal,
PriorDistribution.RAYLEIGH: Rayleigh,
PriorDistribution.UNIFORM: Uniform,
}
assert not (_mismatch := set(PriorDistribution) ^ set(_prior_to_cls)), (
"PriorDistribution enum does not match _prior_to_cls. "
f"Mismatches: {_mismatch}"
)
T = TypeVar("T", bound=BaseModel)
class BaseTable(BaseModel, Generic[T]):
"""Base class for PEtab tables."""
#: The table elements
elements: list[T]
#: The path to the table file, if applicable.
#: Relative to the base path, if the base path is set and rel_path is not
#: an absolute path.
rel_path: AnyUrl | Path | None = Field(exclude=True, default=None)
#: The base path for the table file, if applicable.
#: This is usually the directory of the PEtab YAML file.
base_path: AnyUrl | Path | None = Field(exclude=True, default=None)
def __init__(self, elements: list[T] = None, **kwargs) -> None:
"""Initialize the BaseTable with a list of elements."""
if elements is None:
elements = []
super().__init__(elements=elements, **kwargs)
def __getitem__(self, id_: str) -> T:
"""Get an element by ID.
:param id_: The ID of the element to retrieve.
:return: The element with the given ID.
:raises KeyError: If no element with the given ID exists.
:raises NotImplementedError:
If the element type does not have an ID attribute.
"""
if "id" not in self._element_class().model_fields:
raise NotImplementedError(
f"__getitem__ is not implemented for {self.__class__.__name__}"
)
for element in self.elements:
if element.id == id_:
return element
raise KeyError(f"{T.__name__} ID {id_} not found")
@classmethod
@abstractmethod
def from_df(cls, df: pd.DataFrame) -> BaseTable[T]:
"""Create a table from a DataFrame."""
pass
@abstractmethod
def to_df(self) -> pd.DataFrame:
"""Convert the table to a DataFrame."""
pass
@classmethod
def from_tsv(
cls, file_path: str | Path, base_path: str | Path | None = None
) -> BaseTable[T]:
"""Create table from a TSV file."""
df = pd.read_csv(_generate_path(file_path, base_path), sep="\t")
return cls.from_df(df, rel_path=file_path, base_path=base_path)
def to_tsv(self, file_path: str | Path = None) -> None:
"""Write the table to a TSV file."""
df = self.to_df()
df.to_csv(
file_path or _generate_path(self.rel_path, self.base_path),
sep="\t",
index=not isinstance(df.index, pd.RangeIndex),
)
@classmethod
def _element_class(cls) -> type[T]:
"""Get the class of the elements in the table."""
return get_args(cls.model_fields["elements"].annotation)[0]
def __add__(self, other: T) -> BaseTable[T]:
"""Add an item to the table."""
if not isinstance(other, self._element_class()):
raise TypeError(
f"Can only add {self._element_class().__name__} "
f"to {self.__class__.__name__}"
)
return self.__class__(elements=self.elements + [other])
def __iadd__(self, other: T) -> BaseTable[T]:
"""Add an item to the table in place."""
if not isinstance(other, self._element_class()):
raise TypeError(
f"Can only add {self._element_class().__name__} "
f"to {self.__class__.__name__}"
)
self.elements.append(other)
return self
class Observable(BaseModel):
"""Observable definition."""
#: Observable ID.
id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
alias=C.OBSERVABLE_ID
)
#: Observable name.
name: str | None = Field(alias=C.OBSERVABLE_NAME, default=None)
#: Observable formula.
formula: sp.Basic | None = Field(alias=C.OBSERVABLE_FORMULA, default=None)
#: Noise formula.
noise_formula: sp.Basic | None = Field(alias=C.NOISE_FORMULA, default=None)
#: Noise distribution.
noise_distribution: NoiseDistribution = Field(
alias=C.NOISE_DISTRIBUTION, default=NoiseDistribution.NORMAL
)
#: Placeholder symbols for the observable formula.
observable_placeholders: list[sp.Symbol] = Field(
alias=C.OBSERVABLE_PLACEHOLDERS, default=[]
)
#: Placeholder symbols for the noise formula.
noise_placeholders: list[sp.Symbol] = Field(
alias=C.NOISE_PLACEHOLDERS, default=[]
)
#: :meta private:
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
extra="allow",
validate_assignment=True,
)
@field_validator(
"name",
"formula",
"noise_formula",
"noise_distribution",
mode="before",
)
@classmethod
def _convert_nan_to_default(cls, v, info: ValidationInfo):
if isinstance(v, float) and np.isnan(v):
return cls.model_fields[info.field_name].default
return v
@field_validator("formula", "noise_formula", mode="before")
@classmethod
def _sympify(cls, v):
if v is None or isinstance(v, sp.Basic):
return v
if isinstance(v, float) and np.isnan(v):
return None
return sympify_petab(v)
@field_validator(
"observable_placeholders", "noise_placeholders", mode="before"
)
@classmethod
def _sympify_id_list(cls, v):
if v is None:
return []
if isinstance(v, float) and np.isnan(v):
return []
if isinstance(v, str):
v = v.split(C.PARAMETER_SEPARATOR)
elif not isinstance(v, Sequence):
v = [v]
v = [pid.strip() for pid in v]
return [sympify_petab(_valid_petab_id(pid)) for pid in v if pid]
class ObservableTable(BaseTable[Observable]):
"""PEtab observable table."""
@property
def observables(self) -> list[Observable]:
"""List of observables."""
return self.elements
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ObservableTable:
"""Create an ObservableTable from a DataFrame."""
if df is None:
return cls(**kwargs)
df = get_observable_df(df)
observables = [
Observable(**row.to_dict())
for _, row in df.reset_index().iterrows()
]
return cls(observables, **kwargs)
def to_df(self) -> pd.DataFrame:
"""Convert the ObservableTable to a DataFrame."""
records = self.model_dump(by_alias=True)["elements"]
for record in records:
obs = record[C.OBSERVABLE_FORMULA]
noise = record[C.NOISE_FORMULA]
record[C.OBSERVABLE_FORMULA] = petab_math_str(obs)
record[C.NOISE_FORMULA] = petab_math_str(noise)
record[C.OBSERVABLE_PLACEHOLDERS] = C.PARAMETER_SEPARATOR.join(
map(str, record[C.OBSERVABLE_PLACEHOLDERS])
)
record[C.NOISE_PLACEHOLDERS] = C.PARAMETER_SEPARATOR.join(
map(str, record[C.NOISE_PLACEHOLDERS])
)
return pd.DataFrame(records).set_index([C.OBSERVABLE_ID])
class Change(BaseModel):
"""A change to the model or model state.
A change to the model or model state, corresponding to an individual
row of the PEtab condition table.
>>> Change(
... target_id="k1",
... target_value="10",
... ) # doctest: +NORMALIZE_WHITESPACE
Change(target_id='k1', target_value=10.0000000000000)
"""
#: The ID of the target entity to change.
target_id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
alias=C.TARGET_ID
)
#: The value to set the target entity to.
target_value: sp.Basic = Field(alias=C.TARGET_VALUE)
#: :meta private:
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
use_enum_values=True,
extra="allow",
validate_assignment=True,
)
@field_validator("target_value", mode="before")
@classmethod
def _sympify(cls, v):
if v is None or isinstance(v, sp.Basic):
return v
if isinstance(v, float) and np.isnan(v):
return None
return sympify_petab(v)
class Condition(BaseModel):
"""A set of changes to the model or model state.
A set of simultaneously occurring changes to the model or model state,
corresponding to a perturbation of the underlying system. This corresponds
to all rows of the PEtab condition table with the same condition ID.
>>> Condition(
... id="condition1",
... changes=[
... Change(
... target_id="k1",
... target_value="10",
... )
... ],
... ) # doctest: +NORMALIZE_WHITESPACE
Condition(id='condition1',
changes=[Change(target_id='k1', target_value=10.0000000000000)])
"""
#: The condition ID.
id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
alias=C.CONDITION_ID
)
#: The changes associated with this condition.
changes: list[Change]
#: :meta private:
model_config = ConfigDict(
populate_by_name=True, extra="allow", validate_assignment=True
)
def __add__(self, other: Change) -> Condition:
"""Add a change to the set."""
if not isinstance(other, Change):
raise TypeError("Can only add Change to Condition")
return Condition(id=self.id, changes=self.changes + [other])
def __iadd__(self, other: Change) -> Condition:
"""Add a change to the set in place."""
if not isinstance(other, Change):
raise TypeError("Can only add Change to Condition")
self.changes.append(other)
return self
class ConditionTable(BaseTable[Condition]):
"""PEtab condition table."""
@property
def conditions(self) -> list[Condition]:
"""List of conditions."""
return self.elements
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ConditionTable:
"""Create a ConditionTable from a DataFrame."""
if df is None or df.empty:
return cls(**kwargs)
conditions = []
for condition_id, sub_df in df.groupby(C.CONDITION_ID):
changes = [Change(**row) for row in sub_df.to_dict("records")]
conditions.append(Condition(id=condition_id, changes=changes))
return cls(conditions, **kwargs)
def to_df(self) -> pd.DataFrame:
"""Convert the ConditionTable to a DataFrame."""
records = [
{C.CONDITION_ID: condition.id, **change.model_dump(by_alias=True)}
for condition in self.conditions
for change in condition.changes
]
for record in records:
record[C.TARGET_VALUE] = (
float(record[C.TARGET_VALUE])
if record[C.TARGET_VALUE].is_number
else str(record[C.TARGET_VALUE])
)
return (
pd.DataFrame(records)
if records
else pd.DataFrame(columns=C.CONDITION_DF_REQUIRED_COLS)
)
@property
def free_symbols(self) -> set[sp.Symbol]:
"""Get all free symbols in the condition table.
This includes all free symbols in the target values of the changes,
independently of whether it is referenced by any experiment, or
(indirectly) by any measurement.
"""
return set(
chain.from_iterable(
change.target_value.free_symbols
for condition in self.conditions
for change in condition.changes
if change.target_value is not None
)
)
class ExperimentPeriod(BaseModel):
"""A period of a timecourse or experiment defined by a start time
and a list of condition IDs.
This corresponds to a row of the PEtab experiment table.
"""
#: The start time of the period in time units as defined in the model.
time: Annotated[float, AfterValidator(_is_finite_or_neg_inf)] = Field(
alias=C.TIME
)
#: The IDs of the conditions to be applied at the start time.
condition_ids: list[str] = Field(default_factory=list)
#: :meta private:
model_config = ConfigDict(
populate_by_name=True, extra="allow", validate_assignment=True
)
@field_validator("condition_ids", mode="before")
@classmethod
def _validate_ids(cls, condition_ids):
if condition_ids in [None, "", [], [""]]:
# unspecified, or "use-model-as-is"
return []
for condition_id in condition_ids:
# The empty condition ID for "use-model-as-is" has been handled
# above. Having a combination of empty and non-empty IDs is an
# error, since the targets of conditions to be combined must be
# disjoint.
if not is_valid_identifier(condition_id):
raise ValueError(f"Invalid {C.CONDITION_ID}: `{condition_id}'")
return condition_ids
@property
def is_preequilibration(self) -> bool:
"""Check if this period is a preequilibration period."""
return self.time == C.TIME_PREEQUILIBRATION
class Experiment(BaseModel):
"""An experiment or a timecourse defined by an ID and a set of different
periods.
Corresponds to a group of rows of the PEtab experiment table with the same
experiment ID.
"""
#: The experiment ID.
id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
alias=C.EXPERIMENT_ID
)
#: The periods of the experiment.
periods: list[ExperimentPeriod] = []
#: :meta private:
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
extra="allow",
validate_assignment=True,
)
def __add__(self, other: ExperimentPeriod) -> Experiment:
"""Add a period to the experiment."""
if not isinstance(other, ExperimentPeriod):
raise TypeError("Can only add ExperimentPeriod to Experiment")
return Experiment(id=self.id, periods=self.periods + [other])
def __iadd__(self, other: ExperimentPeriod) -> Experiment:
"""Add a period to the experiment in place."""
if not isinstance(other, ExperimentPeriod):
raise TypeError("Can only add ExperimentPeriod to Experiment")
self.periods.append(other)
return self
@property
def has_preequilibration(self) -> bool:
"""Check if the experiment has preequilibration enabled."""
return any(period.is_preequilibration for period in self.periods)
@property
def sorted_periods(self) -> list[ExperimentPeriod]:
"""Get the periods of the experiment sorted by time."""
return sorted(self.periods, key=lambda period: period.time)
def sort_periods(self) -> None:
"""Sort the periods of the experiment by time."""
self.periods.sort(key=lambda period: period.time)
class ExperimentTable(BaseTable[Experiment]):
"""PEtab experiment table."""
@property
def experiments(self) -> list[Experiment]:
"""List of experiments."""
return self.elements
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> ExperimentTable:
"""Create an ExperimentTable from a DataFrame."""
if df is None:
return cls(**kwargs)
experiments = []
for experiment_id, cur_exp_df in df.groupby(C.EXPERIMENT_ID):
periods = []
for timepoint in cur_exp_df[C.TIME].unique():
condition_ids = [
cid
for cid in cur_exp_df.loc[
cur_exp_df[C.TIME] == timepoint, C.CONDITION_ID
]
if not pd.isna(cid)
]
periods.append(
ExperimentPeriod(
time=timepoint,
condition_ids=condition_ids,
)
)
experiments.append(Experiment(id=experiment_id, periods=periods))
return cls(experiments, **kwargs)
def to_df(self) -> pd.DataFrame:
"""Convert the ExperimentTable to a DataFrame."""
records = [
{
C.EXPERIMENT_ID: experiment.id,
C.TIME: period.time,
C.CONDITION_ID: condition_id,
}
for experiment in self.experiments
for period in experiment.periods
for condition_id in period.condition_ids or [""]
]
return (
pd.DataFrame(records)
if records
else pd.DataFrame(columns=C.EXPERIMENT_DF_REQUIRED_COLS)
)
class Measurement(BaseModel):
"""A measurement.
A measurement of an observable at a specific time point in a specific
experiment.
"""
#: The model ID.
model_id: Annotated[
str | None, BeforeValidator(_valid_petab_id_or_none)
] = Field(alias=C.MODEL_ID, default=None)
#: The observable ID.
observable_id: Annotated[str, BeforeValidator(_valid_petab_id)] = Field(
alias=C.OBSERVABLE_ID
)
#: The experiment ID.
experiment_id: Annotated[
str | None, BeforeValidator(_valid_petab_id_or_none)
] = Field(alias=C.EXPERIMENT_ID, default=None)
#: The time point of the measurement in time units as defined in the model.
time: Annotated[float, AfterValidator(_is_finite_or_pos_inf)] = Field(
alias=C.TIME
)
#: The measurement value.
measurement: Annotated[float, AfterValidator(_not_nan)] = Field(
alias=C.MEASUREMENT
)
#: Values for placeholder parameters in the observable formula.
observable_parameters: list[sp.Basic] = Field(
alias=C.OBSERVABLE_PARAMETERS, default_factory=list
)
#: Values for placeholder parameters in the noise formula.
noise_parameters: list[sp.Basic] = Field(
alias=C.NOISE_PARAMETERS, default_factory=list
)
#: :meta private:
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
extra="allow",
validate_assignment=True,
)
@field_validator(
"experiment_id",
"observable_parameters",
"noise_parameters",
mode="before",
)
@classmethod
def convert_nan_to_none(cls, v, info: ValidationInfo):
if isinstance(v, float) and np.isnan(v):
return cls.model_fields[info.field_name].default
return v
@field_validator(
"observable_parameters", "noise_parameters", mode="before"
)
@classmethod
def _sympify_list(cls, v):
if v is None:
return []
if isinstance(v, float) and np.isnan(v):
return []
if isinstance(v, str):
v = v.split(C.PARAMETER_SEPARATOR)
elif not isinstance(v, Sequence):
v = [v]
return [sympify_petab(x) for x in v]
class MeasurementTable(BaseTable[Measurement]):
"""PEtab measurement table."""
@property
def measurements(self) -> list[Measurement]:
"""List of measurements."""
return self.elements
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> MeasurementTable:
"""Create a MeasurementTable from a DataFrame."""
if df is None:
return cls(**kwargs)
if C.MODEL_ID in df.columns:
df[C.MODEL_ID] = df[C.MODEL_ID].apply(_convert_nan_to_none)
measurements = [
Measurement(
**row.to_dict(),
)
for _, row in df.reset_index().iterrows()
]
return cls(measurements, **kwargs)
def to_df(self) -> pd.DataFrame:
"""Convert the MeasurementTable to a DataFrame."""
records = self.model_dump(by_alias=True)["elements"]
for record in records:
record[C.OBSERVABLE_PARAMETERS] = C.PARAMETER_SEPARATOR.join(
map(str, record[C.OBSERVABLE_PARAMETERS])
)
record[C.NOISE_PARAMETERS] = C.PARAMETER_SEPARATOR.join(
map(str, record[C.NOISE_PARAMETERS])
)
return pd.DataFrame(records)
class Mapping(BaseModel):
"""Mapping PEtab entities to model entities."""
#: PEtab entity ID.
petab_id: Annotated[str, AfterValidator(_valid_petab_id)] = Field(
alias=C.PETAB_ENTITY_ID
)
#: Model entity ID.
model_id: Annotated[str | None, BeforeValidator(_convert_nan_to_none)] = (
Field(alias=C.MODEL_ENTITY_ID, default=None)
)
#: Arbitrary name
name: Annotated[str | None, BeforeValidator(_convert_nan_to_none)] = Field(
alias=C.NAME, default=None
)
#: :meta private:
model_config = ConfigDict(
populate_by_name=True, extra="allow", validate_assignment=True
)
class MappingTable(BaseTable[Mapping]):
"""PEtab mapping table."""
@property
def mappings(self) -> list[Mapping]:
"""List of mappings."""
return self.elements
@classmethod
def from_df(cls, df: pd.DataFrame, **kwargs) -> MappingTable:
"""Create a MappingTable from a DataFrame."""
if df is None:
return cls(**kwargs)
mappings = [
Mapping(**row.to_dict()) for _, row in df.reset_index().iterrows()
]
return cls(mappings, **kwargs)
def to_df(self) -> pd.DataFrame:
"""Convert the MappingTable to a DataFrame."""
res = (
pd.DataFrame(self.model_dump(by_alias=True)["elements"])
if self.mappings
else pd.DataFrame(columns=C.MAPPING_DF_REQUIRED_COLS)
)
return res.set_index([C.PETAB_ENTITY_ID])
def __getitem__(self, petab_id: str) -> Mapping:
"""Get a mapping by PEtab ID."""
for mapping in self.mappings:
if mapping.petab_id == petab_id:
return mapping
raise KeyError(f"PEtab ID {petab_id} not found")
def get(self, petab_id, default=None):
"""Get a mapping by PEtab ID or return a default value."""
try:
return self[petab_id]
except KeyError:
return default
class Parameter(BaseModel):
"""Parameter definition."""
#: Parameter ID.
id: Annotated[str, BeforeValidator(_valid_petab_id)] = Field(
alias=C.PARAMETER_ID
)
#: Lower bound.
lb: Annotated[float | None, BeforeValidator(_convert_nan_to_none)] = Field(
alias=C.LOWER_BOUND, default=None
)
#: Upper bound.
ub: Annotated[float | None, BeforeValidator(_convert_nan_to_none)] = Field(
alias=C.UPPER_BOUND, default=None
)
#: Nominal value.
nominal_value: Annotated[
float | None, BeforeValidator(_convert_nan_to_none)
] = Field(alias=C.NOMINAL_VALUE, default=None)
#: Is the parameter to be estimated?
estimate: bool = Field(alias=C.ESTIMATE, default=True)
#: Type of parameter prior distribution.
prior_distribution: Annotated[
PriorDistribution | None, BeforeValidator(_convert_nan_to_none)
] = Field(alias=C.PRIOR_DISTRIBUTION, default=None)
#: Prior distribution parameters.
prior_parameters: list[float] = Field(
alias=C.PRIOR_PARAMETERS, default_factory=list
)
#: :meta private:
model_config = ConfigDict(
arbitrary_types_allowed=True,
populate_by_name=True,
use_enum_values=True,
extra="allow",
validate_assignment=True,
)
@field_validator("prior_parameters", mode="before")
@classmethod
def _validate_prior_parameters(
cls, v: str | list[str] | float | None | np.ndarray
):
if v is None:
return []
if isinstance(v, float) and np.isnan(v):
return []
if isinstance(v, str):
if v == "":
return []
v = v.split(C.PARAMETER_SEPARATOR)
elif not isinstance(v, Sequence):
v = [v]
return [float(x) for x in v]
@field_validator("estimate", mode="before")
@classmethod
def _validate_estimate_before(cls, v: bool | str):
if isinstance(v, bool):
return v
if isinstance(v, str):
v = v.strip().lower()
if v == "true":
return True
if v == "false":
return False
raise ValueError(
f"Invalid value for estimate: {v}. Must be `true` or `false`."
)
@field_serializer("estimate")
def _serialize_estimate(self, estimate: bool, _info):
return str(estimate).lower()
@field_serializer("prior_distribution")
def _serialize_prior_distribution(
self, prior_distribution: PriorDistribution | None, _info
):
if prior_distribution is None:
return ""
return str(prior_distribution)
@field_serializer("prior_parameters")
def _serialize_prior_parameters(
self, prior_parameters: list[float], _info
) -> str:
return C.PARAMETER_SEPARATOR.join(map(str, prior_parameters))
@model_validator(mode="after")
def _validate(self) -> Self:
if not self.estimate and self.nominal_value is None:
raise ValueError(
"Non-estimated parameter must have a nominal value"
)
if self.estimate and (self.lb is None or self.ub is None):
raise ValueError(
"Estimated parameter must have lower and upper bounds set"
)
if self.lb is not None and self.ub is not None and self.lb > self.ub:
raise ValueError(
"Lower bound must be less than or equal to upper bound."
)