mobidicpy 0.2.2__tar.gz → 0.4.0__tar.gz

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.
Files changed (71) hide show
  1. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/CITATION.cff +1 -1
  2. {mobidicpy-0.2.2/mobidicpy.egg-info → mobidicpy-0.4.0}/PKG-INFO +19 -1
  3. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/README.md +18 -0
  4. mobidicpy-0.4.0/mobidic/__init__.py +168 -0
  5. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/__init__.py +4 -0
  6. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/config.py +21 -6
  7. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/forward_model.py +8 -5
  8. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/parameter_mapping.py +18 -0
  9. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/pest_setup.py +47 -0
  10. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/results.py +55 -15
  11. mobidicpy-0.4.0/mobidic/cli/__init__.py +8 -0
  12. mobidicpy-0.4.0/mobidic/cli/_common.py +64 -0
  13. mobidicpy-0.4.0/mobidic/cli/commands/__init__.py +1 -0
  14. mobidicpy-0.4.0/mobidic/cli/commands/calibration.py +113 -0
  15. mobidicpy-0.4.0/mobidic/cli/commands/check.py +70 -0
  16. mobidicpy-0.4.0/mobidic/cli/commands/hyetograph.py +55 -0
  17. mobidicpy-0.4.0/mobidic/cli/commands/meteo.py +40 -0
  18. mobidicpy-0.4.0/mobidic/cli/commands/preprocess.py +60 -0
  19. mobidicpy-0.4.0/mobidic/cli/commands/simulation.py +114 -0
  20. mobidicpy-0.4.0/mobidic/cli/main.py +63 -0
  21. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/config/schema.py +39 -4
  22. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/simulation.py +8 -5
  23. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/hyetograph.py +186 -57
  24. {mobidicpy-0.2.2 → mobidicpy-0.4.0/mobidicpy.egg-info}/PKG-INFO +19 -1
  25. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidicpy.egg-info/SOURCES.txt +11 -0
  26. mobidicpy-0.4.0/mobidicpy.egg-info/entry_points.txt +2 -0
  27. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/pyproject.toml +8 -2
  28. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/tests/test_package.py +8 -4
  29. mobidicpy-0.2.2/mobidic/__init__.py +0 -140
  30. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/LICENSE +0 -0
  31. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/MANIFEST.in +0 -0
  32. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/instruction.py +0 -0
  33. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/metrics.py +0 -0
  34. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/observation.py +0 -0
  35. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/calibration/template.py +0 -0
  36. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/config/__init__.py +0 -0
  37. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/config/parser.py +0 -0
  38. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/__init__.py +0 -0
  39. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/constants.py +0 -0
  40. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/crop_coefficients.py +0 -0
  41. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/energy_balance.py +0 -0
  42. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/groundwater.py +0 -0
  43. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/interpolation.py +0 -0
  44. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/pet.py +0 -0
  45. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/reservoir.py +0 -0
  46. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/routing.py +0 -0
  47. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/core/soil_water_balance.py +0 -0
  48. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/data/__init__.py +0 -0
  49. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/data/kc_clc_mapping.csv +0 -0
  50. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/io/__init__.py +0 -0
  51. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/io/meteo.py +0 -0
  52. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/io/report.py +0 -0
  53. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/io/state.py +0 -0
  54. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/__init__.py +0 -0
  55. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/gis_reader.py +0 -0
  56. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/grid_operations.py +0 -0
  57. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/hillslope_reach_mapping.py +0 -0
  58. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/io.py +0 -0
  59. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/meteo_preprocessing.py +0 -0
  60. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/meteo_raster.py +0 -0
  61. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/preprocessor.py +0 -0
  62. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/reservoirs.py +0 -0
  63. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/preprocessing/river_network.py +0 -0
  64. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/py.typed +0 -0
  65. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/utils/__init__.py +0 -0
  66. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/utils/crs.py +0 -0
  67. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidic/utils/logging.py +0 -0
  68. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidicpy.egg-info/dependency_links.txt +0 -0
  69. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidicpy.egg-info/requires.txt +0 -0
  70. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/mobidicpy.egg-info/top_level.txt +0 -0
  71. {mobidicpy-0.2.2 → mobidicpy-0.4.0}/setup.cfg +0 -0
@@ -9,7 +9,7 @@ authors:
9
9
  - family-names: Castelli
10
10
  given-names: Fabio
11
11
  orcid: "https://orcid.org/0000-0003-0304-0289"
12
- version: "0.2.2"
12
+ version: "0.4.0"
13
13
  repository-code: "https://github.com/mobidichydro/mobidicpy"
14
14
  keywords:
15
15
  - "Hydrology"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mobidicpy
3
- Version: 0.2.2
3
+ Version: 0.4.0
4
4
  Summary: MOBIDICpy - Distributed and continuous hydrological balance model
5
5
  Author-email: Matteo Masi <matteo.masi@unifi.it>, Fabio Castelli <fabio.castelli@unifi.it>
6
6
  License-Expression: Apache-2.0
@@ -76,6 +76,22 @@ MOBIDIC (MOdello di Bilancio Idrologico DIstribuito e Continuo – distributed a
76
76
 
77
77
  MOBIDICpy is a Python implementation of the MOBIDIC model, originally developed in MATLAB by Castelli et al. See [References](https://github.com/mobidichydro/MOBIDICpy#references) for more details.
78
78
 
79
+ ## Model overview
80
+
81
+ <p align="left">
82
+ <img src="https://raw.githubusercontent.com/mobidichydro/mobidicpy/main/docs/assets/mobidic_processes.png" alt="MOBIDICpy hydrological processes" width="500">
83
+ </p>
84
+
85
+ The diagram above shows the main components of the hydrological cycle as simulated by MOBIDICpy. The model discretizes the basin horizontally using a regular mesh grid and resolves vertical processes across four layers: vegetation, surface storage, soil, and aquifer.
86
+
87
+ Precipitation partitioning, evapotranspiration, and soil moisture dynamics are represented through a five-reservoir scheme comprising plant interception, surface storage, and two soil reservoirs. Following a dual-pore approach (Castillo et al., 2015), the soil is described by two nonlinear reservoirs: a gravitational reservoir, representing the larger pores from which water drains under gravity, and a capillary reservoir, representing the smaller pores that retain water through capillary forces. The model also includes an aquifer reservoir to represent groundwater storage and baseflow contributions to the river network.
88
+
89
+ The simulated processes include interception, evapotranspiration, infiltration, Horton and Dunne runoff, exchange between the two soil reservoirs (absorption and capillary rise), percolation, hypodermic (subsurface) flow, groundwater baseflow, and propagation through the river network via channel (and reservoir) routing.
90
+
91
+ Model parameters can be calibrated against observed data through the USGS [PEST++](https://github.com/usgs/pestpp), a suite of tools for parameter estimation and uncertainty analysis. MOBIDICpy provides an interface to PEST++ with current support for Gauss-Levenberg-Marquardt (GLM) optimization, iterative ensemble smoother (IES), sensitivity analysis (SEN), and parameter sweep (SWP) tools.
92
+
93
+
94
+
79
95
  ## Installation
80
96
 
81
97
  The package can be installed locally via pip:
@@ -159,6 +175,8 @@ Ercolani, G., Chiaradia, E. A., Gandolfi, C., Castelli, F., Masseroni, D. (2018)
159
175
  Masi, M., Masseroni, D., Castelli, F. (2025). Coupled hydrologic, hydraulic, and surface water quality models for pollution management in urban–rural areas.
160
176
  Journal of Hydrology, 657, 133172. DOI: [10.1016/j.jhydrol.2025.133172](https://doi.org/10.1016/j.jhydrol.2025.133172).
161
177
 
178
+ Masi, M., Moghaddam, M. B., Castelli, F., & Arrighi, C. (2026). Modelling nutrient loads in data-scarce large catchments using spatially regularized ensemble calibration. Science of The Total Environment, 1038, 181900. DOI: [10.1016/j.scitotenv.2026.181900](https://doi.org/10.1016/j.scitotenv.2026.181900)
179
+
162
180
  Yang, J., Castelli, F., Chen, Y. (2014). Multiobjective sensitivity analysis and optimization of
163
181
  distributed hydrologic model MOBIDIC. Hydrology and Earth System Sciences, 18(10), 4101–4112.
164
182
  DOI: [10.5194/HESS-18-4101-2014](https://doi.org/10.5194/HESS-18-4101-2014)
@@ -21,6 +21,22 @@ MOBIDIC (MOdello di Bilancio Idrologico DIstribuito e Continuo – distributed a
21
21
 
22
22
  MOBIDICpy is a Python implementation of the MOBIDIC model, originally developed in MATLAB by Castelli et al. See [References](https://github.com/mobidichydro/MOBIDICpy#references) for more details.
23
23
 
24
+ ## Model overview
25
+
26
+ <p align="left">
27
+ <img src="https://raw.githubusercontent.com/mobidichydro/mobidicpy/main/docs/assets/mobidic_processes.png" alt="MOBIDICpy hydrological processes" width="500">
28
+ </p>
29
+
30
+ The diagram above shows the main components of the hydrological cycle as simulated by MOBIDICpy. The model discretizes the basin horizontally using a regular mesh grid and resolves vertical processes across four layers: vegetation, surface storage, soil, and aquifer.
31
+
32
+ Precipitation partitioning, evapotranspiration, and soil moisture dynamics are represented through a five-reservoir scheme comprising plant interception, surface storage, and two soil reservoirs. Following a dual-pore approach (Castillo et al., 2015), the soil is described by two nonlinear reservoirs: a gravitational reservoir, representing the larger pores from which water drains under gravity, and a capillary reservoir, representing the smaller pores that retain water through capillary forces. The model also includes an aquifer reservoir to represent groundwater storage and baseflow contributions to the river network.
33
+
34
+ The simulated processes include interception, evapotranspiration, infiltration, Horton and Dunne runoff, exchange between the two soil reservoirs (absorption and capillary rise), percolation, hypodermic (subsurface) flow, groundwater baseflow, and propagation through the river network via channel (and reservoir) routing.
35
+
36
+ Model parameters can be calibrated against observed data through the USGS [PEST++](https://github.com/usgs/pestpp), a suite of tools for parameter estimation and uncertainty analysis. MOBIDICpy provides an interface to PEST++ with current support for Gauss-Levenberg-Marquardt (GLM) optimization, iterative ensemble smoother (IES), sensitivity analysis (SEN), and parameter sweep (SWP) tools.
37
+
38
+
39
+
24
40
  ## Installation
25
41
 
26
42
  The package can be installed locally via pip:
@@ -104,6 +120,8 @@ Ercolani, G., Chiaradia, E. A., Gandolfi, C., Castelli, F., Masseroni, D. (2018)
104
120
  Masi, M., Masseroni, D., Castelli, F. (2025). Coupled hydrologic, hydraulic, and surface water quality models for pollution management in urban–rural areas.
105
121
  Journal of Hydrology, 657, 133172. DOI: [10.1016/j.jhydrol.2025.133172](https://doi.org/10.1016/j.jhydrol.2025.133172).
106
122
 
123
+ Masi, M., Moghaddam, M. B., Castelli, F., & Arrighi, C. (2026). Modelling nutrient loads in data-scarce large catchments using spatially regularized ensemble calibration. Science of The Total Environment, 1038, 181900. DOI: [10.1016/j.scitotenv.2026.181900](https://doi.org/10.1016/j.scitotenv.2026.181900)
124
+
107
125
  Yang, J., Castelli, F., Chen, Y. (2014). Multiobjective sensitivity analysis and optimization of
108
126
  distributed hydrologic model MOBIDIC. Hydrology and Earth System Sciences, 18(10), 4101–4112.
109
127
  DOI: [10.5194/HESS-18-4101-2014](https://doi.org/10.5194/HESS-18-4101-2014)
@@ -0,0 +1,168 @@
1
+ """MOBIDIC - Distributed and continuous hydrological balance model."""
2
+
3
+ import importlib
4
+ from typing import TYPE_CHECKING
5
+
6
+ from mobidic.utils import configure_logger as _configure_logger
7
+
8
+ __version__ = "0.4.0"
9
+
10
+ # Lazy imports (PEP 562)
11
+ _LAZY_IMPORTS = {
12
+ # Configuration
13
+ "MOBIDICConfig": "mobidic.config",
14
+ "load_config": "mobidic.config",
15
+ # Logging utilities
16
+ "configure_logger": "mobidic.utils",
17
+ "configure_logger_from_config": "mobidic.utils",
18
+ # GIS preprocessing
19
+ "GISData": "mobidic.preprocessing",
20
+ "grid_to_matrix": "mobidic.preprocessing",
21
+ "decimate_raster": "mobidic.preprocessing",
22
+ "decimate_flow_direction": "mobidic.preprocessing",
23
+ "read_shapefile": "mobidic.preprocessing",
24
+ "process_river_network": "mobidic.preprocessing",
25
+ "compute_hillslope_cells": "mobidic.preprocessing",
26
+ "map_hillslope_to_reach": "mobidic.preprocessing",
27
+ "run_preprocessing": "mobidic.preprocessing",
28
+ "load_network": "mobidic.preprocessing",
29
+ "save_network": "mobidic.preprocessing",
30
+ "load_gisdata": "mobidic.preprocessing",
31
+ "save_gisdata": "mobidic.preprocessing",
32
+ "load_reservoirs": "mobidic.preprocessing",
33
+ "save_reservoirs": "mobidic.preprocessing",
34
+ "MeteoData": "mobidic.preprocessing",
35
+ "MeteoRaster": "mobidic.preprocessing",
36
+ "convert_mat_to_netcdf": "mobidic.preprocessing",
37
+ "Reservoir": "mobidic.preprocessing",
38
+ "Reservoirs": "mobidic.preprocessing",
39
+ "process_reservoirs": "mobidic.preprocessing",
40
+ "IDFParameters": "mobidic.preprocessing",
41
+ "HyetographGenerator": "mobidic.preprocessing",
42
+ "read_idf_parameters": "mobidic.preprocessing",
43
+ "read_idf_parameters_resampled": "mobidic.preprocessing",
44
+ "resample_raster_to_grid": "mobidic.preprocessing",
45
+ "idf_depth": "mobidic.preprocessing",
46
+ # Core simulation
47
+ "constants": "mobidic.core",
48
+ "soil_mass_balance": "mobidic.core",
49
+ "capillary_rise": "mobidic.core",
50
+ "hillslope_routing": "mobidic.core",
51
+ "linear_channel_routing": "mobidic.core",
52
+ "groundwater_linear": "mobidic.core",
53
+ "compute_energy_balance_1l": "mobidic.core",
54
+ "diurnal_radiation_cycle": "mobidic.core",
55
+ "energy_balance_1l": "mobidic.core",
56
+ "saturation_specific_humidity": "mobidic.core",
57
+ "solar_hours": "mobidic.core",
58
+ "solar_position": "mobidic.core",
59
+ "Simulation": "mobidic.core",
60
+ "SimulationState": "mobidic.core",
61
+ "SimulationResults": "mobidic.core",
62
+ # I/O
63
+ "load_state": "mobidic.io",
64
+ "StateWriter": "mobidic.io",
65
+ "MeteoWriter": "mobidic.io",
66
+ "save_discharge_report": "mobidic.io",
67
+ "save_lateral_inflow_report": "mobidic.io",
68
+ "load_discharge_report": "mobidic.io",
69
+ # Calibration (optional dependency: pyemu)
70
+ "CalibrationConfig": "mobidic.calibration",
71
+ "CalibrationResults": "mobidic.calibration",
72
+ "PestSetup": "mobidic.calibration",
73
+ "load_calibration_config": "mobidic.calibration",
74
+ }
75
+
76
+ # Names backed by the optional ``calibration`` extra. Accessing one without the
77
+ # extra installed yields a helpful AttributeError instead of a raw ImportError.
78
+ _CALIBRATION_NAMES = {name for name, mod in _LAZY_IMPORTS.items() if mod == "mobidic.calibration"}
79
+
80
+ if TYPE_CHECKING:
81
+ # Make static analysers and IDEs aware of the lazily exported symbols.
82
+ from mobidic.calibration import CalibrationConfig
83
+ from mobidic.calibration import CalibrationResults
84
+ from mobidic.calibration import PestSetup
85
+ from mobidic.calibration import load_calibration_config
86
+ from mobidic.config import MOBIDICConfig
87
+ from mobidic.config import load_config
88
+ from mobidic.core import Simulation
89
+ from mobidic.core import SimulationResults
90
+ from mobidic.core import SimulationState
91
+ from mobidic.core import capillary_rise
92
+ from mobidic.core import compute_energy_balance_1l
93
+ from mobidic.core import constants
94
+ from mobidic.core import diurnal_radiation_cycle
95
+ from mobidic.core import energy_balance_1l
96
+ from mobidic.core import groundwater_linear
97
+ from mobidic.core import hillslope_routing
98
+ from mobidic.core import linear_channel_routing
99
+ from mobidic.core import saturation_specific_humidity
100
+ from mobidic.core import soil_mass_balance
101
+ from mobidic.core import solar_hours
102
+ from mobidic.core import solar_position
103
+ from mobidic.io import MeteoWriter
104
+ from mobidic.io import StateWriter
105
+ from mobidic.io import load_discharge_report
106
+ from mobidic.io import load_state
107
+ from mobidic.io import save_discharge_report
108
+ from mobidic.io import save_lateral_inflow_report
109
+ from mobidic.preprocessing import GISData
110
+ from mobidic.preprocessing import HyetographGenerator
111
+ from mobidic.preprocessing import IDFParameters
112
+ from mobidic.preprocessing import MeteoData
113
+ from mobidic.preprocessing import MeteoRaster
114
+ from mobidic.preprocessing import Reservoir
115
+ from mobidic.preprocessing import Reservoirs
116
+ from mobidic.preprocessing import compute_hillslope_cells
117
+ from mobidic.preprocessing import convert_mat_to_netcdf
118
+ from mobidic.preprocessing import decimate_flow_direction
119
+ from mobidic.preprocessing import decimate_raster
120
+ from mobidic.preprocessing import grid_to_matrix
121
+ from mobidic.preprocessing import idf_depth
122
+ from mobidic.preprocessing import load_gisdata
123
+ from mobidic.preprocessing import load_network
124
+ from mobidic.preprocessing import load_reservoirs
125
+ from mobidic.preprocessing import map_hillslope_to_reach
126
+ from mobidic.preprocessing import process_reservoirs
127
+ from mobidic.preprocessing import process_river_network
128
+ from mobidic.preprocessing import read_idf_parameters
129
+ from mobidic.preprocessing import read_idf_parameters_resampled
130
+ from mobidic.preprocessing import read_shapefile
131
+ from mobidic.preprocessing import resample_raster_to_grid
132
+ from mobidic.preprocessing import run_preprocessing
133
+ from mobidic.preprocessing import save_gisdata
134
+ from mobidic.preprocessing import save_network
135
+ from mobidic.preprocessing import save_reservoirs
136
+ from mobidic.utils import configure_logger
137
+ from mobidic.utils import configure_logger_from_config
138
+
139
+
140
+ def __getattr__(name: str):
141
+ """Lazily import and cache a public symbol on first access (PEP 562)."""
142
+ module_name = _LAZY_IMPORTS.get(name)
143
+ if module_name is None:
144
+ raise AttributeError(f"module 'mobidic' has no attribute '{name}'")
145
+
146
+ try:
147
+ module = importlib.import_module(module_name)
148
+ except ImportError as exc:
149
+ if name in _CALIBRATION_NAMES:
150
+ raise AttributeError(
151
+ f"'{name}' requires the calibration extra. Install it with: pip install mobidicpy[calibration]"
152
+ ) from exc
153
+ raise
154
+
155
+ value = getattr(module, name)
156
+ globals()[name] = value # cache so subsequent lookups skip __getattr__
157
+ return value
158
+
159
+
160
+ def __dir__():
161
+ """Include lazily exported names in ``dir(mobidic)`` for completion."""
162
+ return sorted(set(globals()) | set(_LAZY_IMPORTS))
163
+
164
+
165
+ __all__ = ["__version__", *sorted(_LAZY_IMPORTS)]
166
+
167
+ # Configure default logging on import. Users can reconfigure via configure_logger().
168
+ _configure_logger(level="INFO")
@@ -23,6 +23,7 @@ from mobidic.calibration.observation import (
23
23
  align_observations_to_simulation,
24
24
  load_observations,
25
25
  )
26
+ from mobidic.calibration.parameter_mapping import apply_optimal_parameters, apply_parameters_to_yaml
26
27
  from mobidic.calibration.pest_setup import PestSetup
27
28
  from mobidic.calibration.results import CalibrationResults
28
29
 
@@ -43,4 +44,7 @@ __all__ = [
43
44
  # Metrics
44
45
  "compute_metrics",
45
46
  "METRIC_REGISTRY",
47
+ # Parameter mapping and export
48
+ "apply_optimal_parameters",
49
+ "apply_parameters_to_yaml",
46
50
  ]
@@ -259,18 +259,21 @@ class CalibrationConfig(BaseModel):
259
259
 
260
260
  observations: list[ObservationGroup] = Field(..., min_length=1, description="List of observation groups")
261
261
 
262
- pest_tool: Literal["glm", "ies", "sen", "da", "opt", "mou", "sqp"] = Field("glm", description="PEST++ tool to use")
262
+ pest_tool: Literal["glm", "ies", "sen", "swp", "da", "opt", "mou", "sqp"] = Field(
263
+ "glm", description="PEST++ tool to use"
264
+ )
263
265
 
264
266
  case_name: Optional[str] = Field(
265
267
  None,
266
- description="File name prefix for PEST++ output files (e.g. 'calibration', 'sensitivity'). "
267
- "Defaults to 'sensitivity' when pest_tool='sen', 'calibration' otherwise.",
268
+ description="File name prefix for PEST++ output files (e.g. 'calibration', 'sensitivity', 'sweep'). "
269
+ "Defaults to 'sensitivity' when pest_tool='sen', 'sweep' when pest_tool='swp', 'calibration' otherwise.",
268
270
  )
269
271
 
270
272
  pest_options: Optional[dict] = Field(
271
273
  default_factory=dict,
272
274
  description="PEST++ and tool-specific options (e.g., noptmax, "
273
- "relparmax, facparmax, pst_version, ies_num_reals)",
275
+ "relparmax, facparmax, pst_version, ies_num_reals, sweep_parameter_csv_file). "
276
+ "sweep_parameter_csv_file is required when pest_tool='swp'.",
274
277
  )
275
278
 
276
279
  working_dir: str = Field("pest_run", description="Working directory for PEST++ files")
@@ -279,9 +282,21 @@ class CalibrationConfig(BaseModel):
279
282
 
280
283
  @model_validator(mode="after")
281
284
  def set_case_name_default(self) -> "CalibrationConfig":
282
- """Default case_name to 'sensitivity' for pestpp-sen, 'calibration' otherwise."""
285
+ """Default case_name per tool: 'sensitivity' (sen), 'sweep' (swp), 'calibration' otherwise."""
283
286
  if self.case_name is None:
284
- self.case_name = "sensitivity" if self.pest_tool == "sen" else "calibration"
287
+ if self.pest_tool == "sen":
288
+ self.case_name = "sensitivity"
289
+ elif self.pest_tool == "swp":
290
+ self.case_name = "sweep"
291
+ else:
292
+ self.case_name = "calibration"
293
+ return self
294
+
295
+ @model_validator(mode="after")
296
+ def check_sweep_file_present(self) -> "CalibrationConfig":
297
+ """Require pest_options.sweep_parameter_csv_file when pest_tool='swp'."""
298
+ if self.pest_tool == "swp" and not (self.pest_options or {}).get("sweep_parameter_csv_file"):
299
+ raise ValueError("pest_options.sweep_parameter_csv_file is required when pest_tool='swp'")
285
300
  return self
286
301
 
287
302
  @model_validator(mode="after")
@@ -16,7 +16,7 @@ from pathlib import Path
16
16
  import numpy as np
17
17
  from loguru import logger
18
18
 
19
- from mobidic.calibration.parameter_mapping import apply_parameters_to_yaml, read_model_input_csv
19
+ from mobidic.calibration.parameter_mapping import apply_optimal_parameters, read_model_input_csv
20
20
 
21
21
 
22
22
  def _recalculate_routing_parameters(network, config):
@@ -74,7 +74,7 @@ def run_forward_model(
74
74
  obs_data_json: JSON string with observation metadata for metric computation.
75
75
  routing_params_calibrated: If True, recalculate routing params from config.
76
76
  """
77
- from mobidic.config import load_config
77
+ from mobidic.config import load_config, save_config
78
78
  from mobidic.core.simulation import Simulation
79
79
  from mobidic.preprocessing.io import load_gisdata
80
80
  from mobidic.preprocessing.meteo_raster import MeteoRaster
@@ -83,10 +83,13 @@ def run_forward_model(
83
83
  param_updates = read_model_input_csv(input_path)
84
84
  logger.info(f"Read {len(param_updates)} parameters from {input_path}")
85
85
 
86
- # Step 2: Apply parameter updates to YAML and create modified config
86
+ # Step 2: Load the base config and apply parameter updates in-memory.
87
+ config = load_config(base_config_path)
88
+ apply_optimal_parameters(config, param_updates)
89
+
90
+ # Persist the effective config for inspection/debugging (paths absolute).
87
91
  modified_yaml = input_path.parent / "_modified_config.yaml"
88
- apply_parameters_to_yaml(base_config_path, param_updates, modified_yaml)
89
- config = load_config(modified_yaml)
92
+ save_config(config, modified_yaml)
90
93
 
91
94
  # Step 3: Load pre-processed data
92
95
  gisdata = load_gisdata(gisdata_path, network_path)
@@ -58,6 +58,24 @@ def set_dot_path(obj: dict, dot_path: str, value: Any) -> None:
58
58
  current[parts[-1]] = value
59
59
 
60
60
 
61
+ def apply_optimal_parameters(config: Any, optimal: dict[str, float]) -> None:
62
+ """Apply optimized parameter values to a loaded config in-place.
63
+
64
+ Args:
65
+ config: A MOBIDICConfig object to modify in-place.
66
+ optimal: Dict mapping dot-notation YAML paths (e.g.
67
+ ``"parameters.multipliers.ks_factor"``) to their optimized
68
+ values, as returned by
69
+ :meth:`CalibrationResults.get_optimal_parameters`.
70
+ """
71
+ for dot_path, value in optimal.items():
72
+ parts = dot_path.split(".")
73
+ obj = config
74
+ for part in parts[:-1]:
75
+ obj = getattr(obj, part)
76
+ setattr(obj, parts[-1], value)
77
+
78
+
61
79
  def apply_parameters_to_yaml(
62
80
  base_yaml_path: Path,
63
81
  parameter_updates: dict[str, float],
@@ -37,6 +37,7 @@ PEST_TOOL_MAP = {
37
37
  "glm": "pestpp-glm",
38
38
  "ies": "pestpp-ies",
39
39
  "sen": "pestpp-sen",
40
+ "swp": "pestpp-swp",
40
41
  "da": "pestpp-da",
41
42
  "opt": "pestpp-opt",
42
43
  "mou": "pestpp-mou",
@@ -68,6 +69,7 @@ class PestSetup:
68
69
  self._working_dir = None
69
70
  self._obs_data = None # Cached observation alignment data
70
71
  self._n_obs_per_group = None
72
+ self._sweep_csv_name = None # Basename of the copied sweep CSV (swp tool)
71
73
 
72
74
  @property
73
75
  def working_dir(self) -> Path:
@@ -155,6 +157,11 @@ class PestSetup:
155
157
  routing_keys = {"parameters.routing.wcel", "parameters.routing.Br0", "parameters.routing.NBr"}
156
158
  routing_calibrated = any(p.parameter_key in routing_keys for p in cc.parameters)
157
159
 
160
+ # For the sweep tool, copy the parameter sweep CSV into the working dir and
161
+ # validate that its columns cover all calibration parameters.
162
+ if cc.pest_tool == "swp":
163
+ self._prepare_sweep_file(wd)
164
+
158
165
  # 1. Generate template file
159
166
  generate_template_file(cc, wd / "model_input.csv.tpl")
160
167
 
@@ -320,6 +327,42 @@ class PestSetup:
320
327
 
321
328
  logger.info(f"Observation group '{obs_group.name}': {n_obs} matched observations")
322
329
 
330
+ def _prepare_sweep_file(self, wd: Path) -> None:
331
+ """Copy the parameter sweep CSV into the working dir and validate its columns.
332
+
333
+ The sweep CSV (an ``.par.csv`` produced by pestpp-ies) must contain one
334
+ column per calibration parameter, since pestpp-swp runs the forward model
335
+ once per row using those columns. PEST lowercases parameter names, so the
336
+ column check is case-insensitive.
337
+
338
+ Populates ``self._sweep_csv_name`` with the copied file's basename.
339
+
340
+ Raises:
341
+ FileNotFoundError: If the sweep CSV does not exist.
342
+ ValueError: If any calibration parameter has no matching column.
343
+ """
344
+ cc = self.calib_config
345
+
346
+ sweep_src = Path(cc.pest_options["sweep_parameter_csv_file"])
347
+ if not sweep_src.is_absolute():
348
+ sweep_src = self.base_path / sweep_src
349
+ if not sweep_src.exists():
350
+ raise FileNotFoundError(f"sweep_parameter_csv_file not found: {sweep_src}")
351
+
352
+ # Validate that every parameter name appears as a column (case-insensitive)
353
+ columns = pd.read_csv(sweep_src, nrows=0).columns
354
+ column_set = {c.lower() for c in columns}
355
+ missing = [p.name for p in cc.parameters if p.name.lower() not in column_set]
356
+ if missing:
357
+ raise ValueError(
358
+ f"Sweep CSV '{sweep_src}' is missing columns for calibration "
359
+ f"parameter(s): {missing}. Available columns: {list(columns)}"
360
+ )
361
+
362
+ shutil.copy2(sweep_src, wd / sweep_src.name)
363
+ self._sweep_csv_name = sweep_src.name
364
+ logger.info(f"Copied parameter sweep CSV to working dir: {sweep_src.name}")
365
+
323
366
  def _build_pst(self, obs_names: list[str], wd: Path):
324
367
  """Build the PEST control file (.pst) using pyemu.
325
368
 
@@ -448,6 +491,10 @@ class PestSetup:
448
491
  continue
449
492
  pst.pestpp_options[key] = value
450
493
 
494
+ # For the sweep tool, point PEST++ at the (copied) parameter sweep CSV
495
+ if cc.pest_tool == "swp":
496
+ pst.pestpp_options["sweep_parameter_csv_file"] = self._sweep_csv_name
497
+
451
498
  logger.info(
452
499
  f"Built PEST control file: {len(cc.parameters)} parameters, "
453
500
  f"{len(obs_data)} observations, tool={self._pest_exe}"
@@ -59,9 +59,21 @@ class CalibrationResults:
59
59
  def get_optimal_parameters(self) -> dict[str, float]:
60
60
  """Get the optimal parameter values from the calibration.
61
61
 
62
+ PEST lowercases all parameter names, so the mapping from PEST
63
+ names back to ``parameter_key`` is done case-insensitively.
64
+
62
65
  Returns:
63
- Dict mapping parameter name to optimal value.
66
+ Dict mapping each parameter's ``parameter_key`` (dot-notation
67
+ path into the MOBIDIC YAML config) to its optimal value.
68
+
69
+ Raises:
70
+ KeyError: If a PEST parameter has no matching entry in
71
+ ``calib_config.parameters``.
64
72
  """
73
+ if self.calib_config.pest_tool == "swp":
74
+ logger.info("pest_tool='swp' performs no optimization; use get_sweep_results().")
75
+ return {}
76
+
65
77
  # Try to read from .par file (final parameter values)
66
78
  par_files = sorted(self.master_dir.glob(f"{self.calib_config.case_name}.*.par"))
67
79
  if not par_files:
@@ -71,13 +83,24 @@ class CalibrationResults:
71
83
  # Use the last .par file
72
84
  par_file = par_files[-1]
73
85
  logger.info(f"Reading optimal parameters from: {par_file}")
74
- return self._parse_par_file(par_file)
75
-
76
- # Fallback: read from .pst parameter_data (initial values)
77
- if self.pst is not None:
78
- return dict(zip(self.pst.parameter_data.index, self.pst.parameter_data["parval1"]))
79
-
80
- return {}
86
+ raw = self._parse_par_file(par_file)
87
+ elif self.pst is not None:
88
+ # Fallback: read from .pst parameter_data (initial values)
89
+ raw = dict(zip(self.pst.parameter_data.index, self.pst.parameter_data["parval1"]))
90
+ else:
91
+ return {}
92
+
93
+ name_to_key = {p.name.lower(): p.parameter_key for p in self.calib_config.parameters}
94
+ result = {}
95
+ for name, value in raw.items():
96
+ key = name_to_key.get(name.lower())
97
+ if key is None:
98
+ raise KeyError(
99
+ f"PEST parameter '{name}' has no matching entry in calib_config.parameters. "
100
+ f"Known parameters: {sorted(name_to_key)}"
101
+ )
102
+ result[key] = value
103
+ return result
81
104
 
82
105
  def get_objective_function_history(self) -> pd.DataFrame | None:
83
106
  """Get objective function values across iterations.
@@ -217,6 +240,23 @@ class CalibrationResults:
217
240
  return None
218
241
  return results
219
242
 
243
+ def get_sweep_results(self) -> pd.DataFrame | None:
244
+ """Read the pestpp-swp output ensemble (``{case}.sweep_out.csv``).
245
+
246
+ Each row corresponds to one forward run (one row of the input parameter
247
+ sweep CSV) and contains the run id, phi, and one column per observation.
248
+
249
+ Returns:
250
+ DataFrame of sweep outputs, or None if the file is not found.
251
+ """
252
+ path = self.master_dir / "sweep_out.csv"
253
+ if not path.exists():
254
+ logger.warning(f"Sweep output file not found: {path}")
255
+ return None
256
+ df = pd.read_csv(path)
257
+ logger.info(f"Read sweep output from {path}: {len(df)} runs")
258
+ return df
259
+
220
260
  def _parse_par_file(self, par_file: Path) -> dict[str, float]:
221
261
  """Parse a PEST .par file to extract parameter values."""
222
262
  params = {}
@@ -233,13 +273,13 @@ class CalibrationResults:
233
273
 
234
274
  def _parse_ies_phi(self, phi_path: Path) -> pd.DataFrame:
235
275
  """Parse objective function history from IES calibration.phi.actual.csv."""
236
- df = pd.read_csv(phi_path, index_col=0)
237
- df.index.name = "iteration"
238
- df = df.reset_index()
239
- member_cols = [c for c in df.columns if c != "iteration"]
240
- df["phi"] = df[member_cols].mean(axis=1)
241
- df["std"] = df[member_cols].std(axis=1)
242
- logger.info(f"Read IES phi history from {phi_path}: {len(df)} iterations, {len(member_cols)} ensemble members")
276
+ df = pd.read_csv(phi_path)
277
+ # Skip first 6 columns
278
+ num_members = len(df.columns) - 6
279
+ # Add phi and std columns for consistency with GLM
280
+ df["phi"] = df["mean"]
281
+ df["std"] = df["standard_deviation"]
282
+ logger.info(f"Read IES phi history from {phi_path}: {len(df)} iterations, {num_members} ensemble members")
243
283
  return df
244
284
 
245
285
  def _parse_iobj_phi(self, iobj_path: Path) -> pd.DataFrame:
@@ -0,0 +1,8 @@
1
+ """Command-line interface for MOBIDICpy.
2
+
3
+ Exposes the ``mobidic`` console script (see ``pyproject.toml``)
4
+ """
5
+
6
+ from mobidic.cli.main import main
7
+
8
+ __all__ = ["main"]
@@ -0,0 +1,64 @@
1
+ """Shared helpers for MOBIDIC CLI subcommands."""
2
+
3
+ from argparse import ArgumentParser
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+
7
+ LOG_LEVELS = ["DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR"]
8
+
9
+
10
+ class CLIError(Exception):
11
+ """Raised for expected, user-facing errors that should not show a traceback."""
12
+
13
+
14
+ def add_log_level_arg(parser: ArgumentParser) -> None:
15
+ """Add the common ``--log-level`` option to a subcommand parser."""
16
+ parser.add_argument(
17
+ "--log-level",
18
+ choices=LOG_LEVELS,
19
+ default=None,
20
+ help="Override the logging level (default: from config, or INFO).",
21
+ )
22
+
23
+
24
+ def configure_cli_logging(config=None, log_level: str | None = None) -> None:
25
+ """Configure logging for a CLI command.
26
+
27
+ Explicit setting of ``--log-level`` takes precedence; otherwise the config's
28
+ ``advanced`` section is used. With neither, the package default (INFO) is used.
29
+
30
+ Args:
31
+ config: Optional :class:`~mobidic.MOBIDICConfig` to read log settings from.
32
+ log_level: Optional explicit level that overrides the config.
33
+ """
34
+ # Imported lazily so building the parser / printing --help stays fast.
35
+ from mobidic.utils import configure_logger, configure_logger_from_config
36
+
37
+ if log_level is not None:
38
+ configure_logger(level=log_level)
39
+ elif config is not None:
40
+ configure_logger_from_config(config)
41
+
42
+
43
+ def parse_date(value: str) -> datetime:
44
+ """Parse an ISO-8601 date/datetime string into a :class:`datetime`.
45
+
46
+ Args:
47
+ value: ISO date or datetime string (e.g. ``2023-11-01`` or
48
+ ``2023-11-01T06:00``).
49
+
50
+ Returns:
51
+ Parsed datetime.
52
+
53
+ Raises:
54
+ CLIError: If the string is not valid ISO-8601.
55
+ """
56
+ try:
57
+ return datetime.fromisoformat(value)
58
+ except ValueError as exc:
59
+ raise CLIError(f"Invalid date '{value}': expected ISO format (e.g. 2023-11-01).") from exc
60
+
61
+
62
+ def resolved_config_dir(config_file: str | Path) -> Path:
63
+ """Return the directory containing the config file (for resolving relative paths)."""
64
+ return Path(config_file).resolve().parent
@@ -0,0 +1 @@
1
+ """MOBIDIC CLI subcommands."""