mobidicpy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mobidic/__init__.py +126 -0
- mobidic/calibration/__init__.py +56 -0
- mobidic/calibration/config.py +281 -0
- mobidic/calibration/forward_model.py +319 -0
- mobidic/calibration/instruction.py +85 -0
- mobidic/calibration/metrics.py +162 -0
- mobidic/calibration/observation.py +110 -0
- mobidic/calibration/parameter_mapping.py +111 -0
- mobidic/calibration/pest_setup.py +555 -0
- mobidic/calibration/results.py +300 -0
- mobidic/calibration/template.py +78 -0
- mobidic/config/__init__.py +6 -0
- mobidic/config/parser.py +177 -0
- mobidic/config/schema.py +605 -0
- mobidic/core/__init__.py +28 -0
- mobidic/core/constants.py +32 -0
- mobidic/core/interpolation.py +385 -0
- mobidic/core/pet.py +56 -0
- mobidic/core/reservoir.py +380 -0
- mobidic/core/routing.py +440 -0
- mobidic/core/simulation.py +1571 -0
- mobidic/core/soil_water_balance.py +453 -0
- mobidic/io/__init__.py +14 -0
- mobidic/io/meteo.py +267 -0
- mobidic/io/report.py +257 -0
- mobidic/io/state.py +773 -0
- mobidic/preprocessing/__init__.py +81 -0
- mobidic/preprocessing/gis_reader.py +154 -0
- mobidic/preprocessing/grid_operations.py +324 -0
- mobidic/preprocessing/hillslope_reach_mapping.py +370 -0
- mobidic/preprocessing/hyetograph.py +1049 -0
- mobidic/preprocessing/io.py +490 -0
- mobidic/preprocessing/meteo_preprocessing.py +654 -0
- mobidic/preprocessing/meteo_raster.py +339 -0
- mobidic/preprocessing/preprocessor.py +484 -0
- mobidic/preprocessing/reservoirs.py +523 -0
- mobidic/preprocessing/river_network.py +605 -0
- mobidic/py.typed +0 -0
- mobidic/utils/__init__.py +13 -0
- mobidic/utils/crs.py +267 -0
- mobidic/utils/logging.py +110 -0
- mobidicpy-0.1.0.dist-info/METADATA +161 -0
- mobidicpy-0.1.0.dist-info/RECORD +46 -0
- mobidicpy-0.1.0.dist-info/WHEEL +5 -0
- mobidicpy-0.1.0.dist-info/licenses/LICENSE +201 -0
- mobidicpy-0.1.0.dist-info/top_level.txt +1 -0
mobidic/__init__.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""MOBIDIC - Distributed and continuous hydrological balance model."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from mobidic.config import MOBIDICConfig
|
|
6
|
+
from mobidic.config import load_config
|
|
7
|
+
from mobidic.utils import configure_logger, configure_logger_from_config
|
|
8
|
+
from mobidic.preprocessing import GISData
|
|
9
|
+
|
|
10
|
+
from mobidic.preprocessing import (
|
|
11
|
+
grid_to_matrix,
|
|
12
|
+
decimate_raster,
|
|
13
|
+
decimate_flow_direction,
|
|
14
|
+
read_shapefile,
|
|
15
|
+
process_river_network,
|
|
16
|
+
compute_hillslope_cells,
|
|
17
|
+
map_hillslope_to_reach,
|
|
18
|
+
run_preprocessing,
|
|
19
|
+
load_network,
|
|
20
|
+
save_network,
|
|
21
|
+
load_gisdata,
|
|
22
|
+
save_gisdata,
|
|
23
|
+
load_reservoirs,
|
|
24
|
+
save_reservoirs,
|
|
25
|
+
MeteoData,
|
|
26
|
+
MeteoRaster,
|
|
27
|
+
convert_mat_to_netcdf,
|
|
28
|
+
Reservoir,
|
|
29
|
+
Reservoirs,
|
|
30
|
+
process_reservoirs,
|
|
31
|
+
IDFParameters,
|
|
32
|
+
HyetographGenerator,
|
|
33
|
+
read_idf_parameters,
|
|
34
|
+
read_idf_parameters_resampled,
|
|
35
|
+
resample_raster_to_grid,
|
|
36
|
+
idf_depth,
|
|
37
|
+
)
|
|
38
|
+
from mobidic.core import (
|
|
39
|
+
constants,
|
|
40
|
+
soil_mass_balance,
|
|
41
|
+
capillary_rise,
|
|
42
|
+
hillslope_routing,
|
|
43
|
+
linear_channel_routing,
|
|
44
|
+
Simulation,
|
|
45
|
+
SimulationState,
|
|
46
|
+
SimulationResults,
|
|
47
|
+
)
|
|
48
|
+
from mobidic.io import (
|
|
49
|
+
load_state,
|
|
50
|
+
StateWriter,
|
|
51
|
+
MeteoWriter,
|
|
52
|
+
save_discharge_report,
|
|
53
|
+
save_lateral_inflow_report,
|
|
54
|
+
load_discharge_report,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Configure default logging behavior on package import
|
|
58
|
+
# Users can reconfigure by calling configure_logger() with custom settings
|
|
59
|
+
configure_logger(level="INFO")
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"__version__",
|
|
63
|
+
"constants",
|
|
64
|
+
"MOBIDICConfig",
|
|
65
|
+
"load_config",
|
|
66
|
+
"configure_logger",
|
|
67
|
+
"configure_logger_from_config",
|
|
68
|
+
"GISData",
|
|
69
|
+
"grid_to_matrix",
|
|
70
|
+
"decimate_raster",
|
|
71
|
+
"decimate_flow_direction",
|
|
72
|
+
"read_shapefile",
|
|
73
|
+
"process_river_network",
|
|
74
|
+
"compute_hillslope_cells",
|
|
75
|
+
"map_hillslope_to_reach",
|
|
76
|
+
"run_preprocessing",
|
|
77
|
+
"load_network",
|
|
78
|
+
"save_network",
|
|
79
|
+
"load_gisdata",
|
|
80
|
+
"save_gisdata",
|
|
81
|
+
"load_reservoirs",
|
|
82
|
+
"save_reservoirs",
|
|
83
|
+
"MeteoData",
|
|
84
|
+
"MeteoRaster",
|
|
85
|
+
"convert_mat_to_netcdf",
|
|
86
|
+
"Reservoir",
|
|
87
|
+
"Reservoirs",
|
|
88
|
+
"process_reservoirs",
|
|
89
|
+
"IDFParameters",
|
|
90
|
+
"HyetographGenerator",
|
|
91
|
+
"read_idf_parameters",
|
|
92
|
+
"read_idf_parameters_resampled",
|
|
93
|
+
"resample_raster_to_grid",
|
|
94
|
+
"idf_depth",
|
|
95
|
+
"soil_mass_balance",
|
|
96
|
+
"capillary_rise",
|
|
97
|
+
"hillslope_routing",
|
|
98
|
+
"linear_channel_routing",
|
|
99
|
+
"Simulation",
|
|
100
|
+
"SimulationState",
|
|
101
|
+
"SimulationResults",
|
|
102
|
+
"load_state",
|
|
103
|
+
"StateWriter",
|
|
104
|
+
"MeteoWriter",
|
|
105
|
+
"save_discharge_report",
|
|
106
|
+
"save_lateral_inflow_report",
|
|
107
|
+
"load_discharge_report",
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
# Calibration module (optional dependency: pyemu)
|
|
111
|
+
try:
|
|
112
|
+
from mobidic.calibration import (
|
|
113
|
+
CalibrationConfig,
|
|
114
|
+
CalibrationResults,
|
|
115
|
+
PestSetup,
|
|
116
|
+
load_calibration_config,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
__all__ += [
|
|
120
|
+
"CalibrationConfig",
|
|
121
|
+
"CalibrationResults",
|
|
122
|
+
"PestSetup",
|
|
123
|
+
"load_calibration_config",
|
|
124
|
+
]
|
|
125
|
+
except ImportError:
|
|
126
|
+
pass
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""PEST++ calibration interface for MOBIDICpy.
|
|
2
|
+
|
|
3
|
+
This package provides tools for model calibration, sensitivity analysis,
|
|
4
|
+
and uncertainty quantification using PEST++ via pyemu.
|
|
5
|
+
|
|
6
|
+
Requires calibration dependencies: pyemu, HydroErr
|
|
7
|
+
Install with: pip install mobidic[calibration]
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from mobidic.calibration.config import (
|
|
11
|
+
CalibrationConfig,
|
|
12
|
+
CalibrationParameter,
|
|
13
|
+
CalibrationPeriod,
|
|
14
|
+
MetricConfig,
|
|
15
|
+
ObservationGroup,
|
|
16
|
+
load_calibration_config,
|
|
17
|
+
)
|
|
18
|
+
from mobidic.calibration.metrics import (
|
|
19
|
+
compute_metrics,
|
|
20
|
+
kge,
|
|
21
|
+
nse,
|
|
22
|
+
nse_log,
|
|
23
|
+
pbias,
|
|
24
|
+
peak_error,
|
|
25
|
+
rmse,
|
|
26
|
+
)
|
|
27
|
+
from mobidic.calibration.observation import (
|
|
28
|
+
align_observations_to_simulation,
|
|
29
|
+
load_observations,
|
|
30
|
+
)
|
|
31
|
+
from mobidic.calibration.pest_setup import PestSetup
|
|
32
|
+
from mobidic.calibration.results import CalibrationResults
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
# Config
|
|
36
|
+
"CalibrationConfig",
|
|
37
|
+
"CalibrationParameter",
|
|
38
|
+
"CalibrationPeriod",
|
|
39
|
+
"MetricConfig",
|
|
40
|
+
"ObservationGroup",
|
|
41
|
+
"load_calibration_config",
|
|
42
|
+
# Setup and results
|
|
43
|
+
"PestSetup",
|
|
44
|
+
"CalibrationResults",
|
|
45
|
+
# Observations
|
|
46
|
+
"load_observations",
|
|
47
|
+
"align_observations_to_simulation",
|
|
48
|
+
# Metrics
|
|
49
|
+
"nse",
|
|
50
|
+
"nse_log",
|
|
51
|
+
"pbias",
|
|
52
|
+
"peak_error",
|
|
53
|
+
"rmse",
|
|
54
|
+
"kge",
|
|
55
|
+
"compute_metrics",
|
|
56
|
+
]
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Pydantic models for PEST++ calibration configuration."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal, Optional
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from loguru import logger
|
|
9
|
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CalibrationParameter(BaseModel):
|
|
13
|
+
"""A single parameter to be calibrated by PEST++."""
|
|
14
|
+
|
|
15
|
+
name: str = Field(..., description="Parameter name (used in PEST++ control file)")
|
|
16
|
+
parameter_key: str = Field(
|
|
17
|
+
..., description="Dot-notation path into MOBIDIC YAML config (e.g., parameters.multipliers.ks_factor)"
|
|
18
|
+
)
|
|
19
|
+
initial_value: float = Field(..., description="Starting value for optimization")
|
|
20
|
+
lower_bound: float = Field(..., description="Lower bound for parameter")
|
|
21
|
+
upper_bound: float = Field(..., description="Upper bound for parameter")
|
|
22
|
+
transform: Literal["none", "log", "fixed"] = Field("none", description="Parameter transformation")
|
|
23
|
+
scale: float = Field(1.0, description="Multiplication factor applied by PEST++")
|
|
24
|
+
offset: float = Field(0.0, description="Additive offset applied by PEST++")
|
|
25
|
+
par_group: str = Field("default", description="Parameter group name")
|
|
26
|
+
|
|
27
|
+
@field_validator("name")
|
|
28
|
+
@classmethod
|
|
29
|
+
def check_name_no_spaces(cls, v: str) -> str:
|
|
30
|
+
"""PEST++ parameter names cannot contain spaces."""
|
|
31
|
+
if " " in v:
|
|
32
|
+
raise ValueError("Parameter name cannot contain spaces")
|
|
33
|
+
return v
|
|
34
|
+
|
|
35
|
+
@model_validator(mode="after")
|
|
36
|
+
def check_bounds(self) -> "CalibrationParameter":
|
|
37
|
+
"""Validate that lower_bound < upper_bound and initial_value is within bounds."""
|
|
38
|
+
if self.lower_bound >= self.upper_bound:
|
|
39
|
+
raise ValueError(f"lower_bound ({self.lower_bound}) must be less than upper_bound ({self.upper_bound})")
|
|
40
|
+
if not self.lower_bound <= self.initial_value <= self.upper_bound:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f"initial_value ({self.initial_value}) must be between "
|
|
43
|
+
f"lower_bound ({self.lower_bound}) and upper_bound ({self.upper_bound})"
|
|
44
|
+
)
|
|
45
|
+
if self.transform == "log" and self.lower_bound <= 0:
|
|
46
|
+
raise ValueError("lower_bound must be positive when transform='log'")
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MetricConfig(BaseModel):
|
|
51
|
+
"""Configuration for a derived metric used as pseudo-observation."""
|
|
52
|
+
|
|
53
|
+
metric: str = Field(..., description="Metric name (nse, nse_log, pbias, peak_error, rmse, kge)")
|
|
54
|
+
target: float = Field(..., description="Target value PEST++ tries to match (e.g., 1.0 for NSE)")
|
|
55
|
+
weight: float = Field(1.0, description="Observation weight for this metric")
|
|
56
|
+
|
|
57
|
+
@field_validator("metric")
|
|
58
|
+
@classmethod
|
|
59
|
+
def check_metric_name(cls, v: str) -> str:
|
|
60
|
+
"""Validate metric name is supported."""
|
|
61
|
+
supported = {"nse", "nse_log", "pbias", "peak_error", "rmse", "kge"}
|
|
62
|
+
if v not in supported:
|
|
63
|
+
raise ValueError(f"Unsupported metric '{v}'. Supported: {sorted(supported)}")
|
|
64
|
+
return v
|
|
65
|
+
|
|
66
|
+
@field_validator("weight")
|
|
67
|
+
@classmethod
|
|
68
|
+
def check_weight_non_negative(cls, v: float) -> float:
|
|
69
|
+
"""Weights must be non-negative."""
|
|
70
|
+
if v < 0:
|
|
71
|
+
raise ValueError("Weight must be non-negative")
|
|
72
|
+
return v
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ObservationGroup(BaseModel):
|
|
76
|
+
"""An observation group (e.g., discharge at a specific gauging station)."""
|
|
77
|
+
|
|
78
|
+
name: str = Field(..., description="PEST++ observation group identifier (prefix for obs names)")
|
|
79
|
+
obs_file: str = Field(..., description="Path to observed data CSV file (relative to calibration config)")
|
|
80
|
+
reach_id: int = Field(..., description="Reach ID (mobidic_id) where observations are located")
|
|
81
|
+
weight: float = Field(1.0, description="Default weight for all observations in this group")
|
|
82
|
+
time_column: str = Field("time", description="Column name for timestamps in obs_file")
|
|
83
|
+
value_column: str = Field(..., description="Column name for observed values in obs_file")
|
|
84
|
+
metrics: Optional[list[MetricConfig]] = Field(None, description="Optional derived metrics as pseudo-observations")
|
|
85
|
+
|
|
86
|
+
@field_validator("name")
|
|
87
|
+
@classmethod
|
|
88
|
+
def check_name_no_spaces(cls, v: str) -> str:
|
|
89
|
+
"""PEST++ observation names cannot contain spaces."""
|
|
90
|
+
if " " in v:
|
|
91
|
+
raise ValueError("Observation group name cannot contain spaces")
|
|
92
|
+
return v
|
|
93
|
+
|
|
94
|
+
@field_validator("weight")
|
|
95
|
+
@classmethod
|
|
96
|
+
def check_weight_non_negative(cls, v: float) -> float:
|
|
97
|
+
"""Weights must be non-negative."""
|
|
98
|
+
if v < 0:
|
|
99
|
+
raise ValueError("Weight must be non-negative")
|
|
100
|
+
return v
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CalibrationPeriod(BaseModel):
|
|
104
|
+
"""A date range with start and end dates.
|
|
105
|
+
|
|
106
|
+
Used for both calibration_period and simulation_period.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
start_date: str = Field(..., description="Start date (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS)")
|
|
110
|
+
end_date: str = Field(..., description="End date (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS)")
|
|
111
|
+
|
|
112
|
+
@field_validator("start_date", "end_date")
|
|
113
|
+
@classmethod
|
|
114
|
+
def check_date_format(cls, v: str) -> str:
|
|
115
|
+
"""Validate that date strings are parseable as YYYY-MM-DD or YYYY-MM-DD HH:MM:SS."""
|
|
116
|
+
import re
|
|
117
|
+
|
|
118
|
+
if not re.match(r"^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$", v):
|
|
119
|
+
raise ValueError(f"Invalid date format: '{v}'. Expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'.")
|
|
120
|
+
try:
|
|
121
|
+
pd.Timestamp(v)
|
|
122
|
+
except ValueError as e:
|
|
123
|
+
raise ValueError(f"Invalid date format: '{v}'. Expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'.") from e
|
|
124
|
+
return v
|
|
125
|
+
|
|
126
|
+
@model_validator(mode="after")
|
|
127
|
+
def check_start_before_end(self) -> "CalibrationPeriod":
|
|
128
|
+
"""Validate that start_date < end_date."""
|
|
129
|
+
start = pd.Timestamp(self.start_date)
|
|
130
|
+
end = pd.Timestamp(self.end_date)
|
|
131
|
+
if start >= end:
|
|
132
|
+
raise ValueError(f"start_date ({self.start_date}) must be before end_date ({self.end_date})")
|
|
133
|
+
return self
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class ParallelConfig(BaseModel):
|
|
137
|
+
"""Configuration for parallel PEST++ execution."""
|
|
138
|
+
|
|
139
|
+
num_workers: Optional[int] = Field(None, description="Workers per node (null = all available CPUs)")
|
|
140
|
+
port: int = Field(4004, description="TCP port for manager-agent communication")
|
|
141
|
+
manager_ip: Optional[str] = Field(None, description="Manager IP for cluster mode (None = local mode)")
|
|
142
|
+
|
|
143
|
+
@field_validator("num_workers")
|
|
144
|
+
@classmethod
|
|
145
|
+
def check_num_workers(cls, v: int | None) -> int | None:
|
|
146
|
+
"""Validate num_workers is positive and does not exceed available CPUs."""
|
|
147
|
+
if v is None:
|
|
148
|
+
return v
|
|
149
|
+
if v <= 0:
|
|
150
|
+
raise ValueError("num_workers must be a positive integer or null (all CPUs)")
|
|
151
|
+
available = os.cpu_count()
|
|
152
|
+
if available is not None and v > available:
|
|
153
|
+
logger.warning(f"num_workers={v} exceeds available CPUs ({available}). Consider reducing it.")
|
|
154
|
+
return v
|
|
155
|
+
|
|
156
|
+
@field_validator("port")
|
|
157
|
+
@classmethod
|
|
158
|
+
def check_port_range(cls, v: int) -> int:
|
|
159
|
+
"""Validate port is in valid range."""
|
|
160
|
+
if not 1024 <= v <= 65535:
|
|
161
|
+
raise ValueError("Port must be between 1024 and 65535")
|
|
162
|
+
return v
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class CalibrationConfig(BaseModel):
|
|
166
|
+
"""Complete calibration configuration for PEST++ integration."""
|
|
167
|
+
|
|
168
|
+
mobidic_config: str = Field(..., description="Path to MOBIDIC simulation YAML config file")
|
|
169
|
+
|
|
170
|
+
simulation_period: Optional[CalibrationPeriod] = Field(
|
|
171
|
+
None,
|
|
172
|
+
description="Simulation period (start_date, end_date) for the forward model. "
|
|
173
|
+
"Can be longer than calibration_period to include warm-up. "
|
|
174
|
+
"Must be contained within the forcing data time range. "
|
|
175
|
+
"If None, defaults to calibration_period.",
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
calibration_period: Optional[CalibrationPeriod] = Field(
|
|
179
|
+
None,
|
|
180
|
+
description="Calibration period (start_date, end_date): only observations within "
|
|
181
|
+
"this window are used by PEST++. Must be contained within simulation_period. "
|
|
182
|
+
"If None, defaults to full observation period.",
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
use_raster_forcing: bool = Field(
|
|
186
|
+
False,
|
|
187
|
+
description="If True, make a first forward run to rasterize station forcing for faster subsequent runs",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
parameters: list[CalibrationParameter] = Field(..., min_length=1, description="List of parameters to calibrate")
|
|
191
|
+
|
|
192
|
+
observations: list[ObservationGroup] = Field(..., min_length=1, description="List of observation groups")
|
|
193
|
+
|
|
194
|
+
pest_tool: Literal["glm", "ies", "sen", "da", "opt", "mou", "sqp"] = Field("glm", description="PEST++ tool to use")
|
|
195
|
+
|
|
196
|
+
case_name: Optional[str] = Field(
|
|
197
|
+
None,
|
|
198
|
+
description="File name prefix for PEST++ output files (e.g. 'calibration', 'sensitivity'). "
|
|
199
|
+
"Defaults to 'sensitivity' when pest_tool='sen', 'calibration' otherwise.",
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
pest_options: Optional[dict] = Field(
|
|
203
|
+
default_factory=dict,
|
|
204
|
+
description="PEST++ and tool-specific options (e.g., noptmax, "
|
|
205
|
+
"relparmax, facparmax, pst_version, ies_num_reals)",
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
working_dir: str = Field("pest_run", description="Working directory for PEST++ files")
|
|
209
|
+
|
|
210
|
+
parallel: Optional[ParallelConfig] = Field(default_factory=ParallelConfig)
|
|
211
|
+
|
|
212
|
+
@model_validator(mode="after")
|
|
213
|
+
def set_case_name_default(self) -> "CalibrationConfig":
|
|
214
|
+
"""Default case_name to 'sensitivity' for pestpp-sen, 'calibration' otherwise."""
|
|
215
|
+
if self.case_name is None:
|
|
216
|
+
self.case_name = "sensitivity" if self.pest_tool == "sen" else "calibration"
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
@model_validator(mode="after")
|
|
220
|
+
def check_parameter_names_unique(self) -> "CalibrationConfig":
|
|
221
|
+
"""Ensure all parameter names are unique."""
|
|
222
|
+
names = [p.name for p in self.parameters]
|
|
223
|
+
if len(names) != len(set(names)):
|
|
224
|
+
duplicates = [n for n in names if names.count(n) > 1]
|
|
225
|
+
raise ValueError(f"Duplicate parameter names: {set(duplicates)}")
|
|
226
|
+
return self
|
|
227
|
+
|
|
228
|
+
@model_validator(mode="after")
|
|
229
|
+
def check_observation_names_unique(self) -> "CalibrationConfig":
|
|
230
|
+
"""Ensure all observation group names are unique."""
|
|
231
|
+
names = [o.name for o in self.observations]
|
|
232
|
+
if len(names) != len(set(names)):
|
|
233
|
+
duplicates = [n for n in names if names.count(n) > 1]
|
|
234
|
+
raise ValueError(f"Duplicate observation group names: {set(duplicates)}")
|
|
235
|
+
return self
|
|
236
|
+
|
|
237
|
+
@model_validator(mode="after")
|
|
238
|
+
def check_calibration_within_simulation(self) -> "CalibrationConfig":
|
|
239
|
+
"""Ensure calibration_period is contained within simulation_period.
|
|
240
|
+
|
|
241
|
+
If simulation_period is not set, it defaults to calibration_period at runtime.
|
|
242
|
+
But if both are set, calibration must be within simulation.
|
|
243
|
+
"""
|
|
244
|
+
if self.simulation_period is not None and self.calibration_period is not None:
|
|
245
|
+
sim_start = pd.Timestamp(self.simulation_period.start_date)
|
|
246
|
+
sim_end = pd.Timestamp(self.simulation_period.end_date)
|
|
247
|
+
cal_start = pd.Timestamp(self.calibration_period.start_date)
|
|
248
|
+
cal_end = pd.Timestamp(self.calibration_period.end_date)
|
|
249
|
+
|
|
250
|
+
if cal_start < sim_start:
|
|
251
|
+
raise ValueError(
|
|
252
|
+
f"calibration_period.start_date ({self.calibration_period.start_date}) "
|
|
253
|
+
f"must be >= simulation_period.start_date ({self.simulation_period.start_date})"
|
|
254
|
+
)
|
|
255
|
+
if cal_end > sim_end:
|
|
256
|
+
raise ValueError(
|
|
257
|
+
f"calibration_period.end_date ({self.calibration_period.end_date}) "
|
|
258
|
+
f"must be <= simulation_period.end_date ({self.simulation_period.end_date})"
|
|
259
|
+
)
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def load_calibration_config(config_path: str | Path) -> CalibrationConfig:
|
|
264
|
+
"""Load and validate calibration configuration from YAML file.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
config_path: Path to the calibration YAML file.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
Validated CalibrationConfig object.
|
|
271
|
+
"""
|
|
272
|
+
import yaml
|
|
273
|
+
|
|
274
|
+
config_path = Path(config_path)
|
|
275
|
+
if not config_path.exists():
|
|
276
|
+
raise FileNotFoundError(f"Calibration config file not found: {config_path}")
|
|
277
|
+
|
|
278
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
279
|
+
config_dict = yaml.safe_load(f)
|
|
280
|
+
|
|
281
|
+
return CalibrationConfig(**config_dict)
|