mobidicpy 0.2.0__tar.gz → 0.2.2__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 (59) hide show
  1. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/CITATION.cff +1 -1
  2. {mobidicpy-0.2.0/mobidicpy.egg-info → mobidicpy-0.2.2}/PKG-INFO +2 -2
  3. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/__init__.py +1 -1
  4. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/__init__.py +2 -12
  5. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/config.py +73 -5
  6. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/metrics.py +98 -48
  7. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/config/schema.py +8 -0
  8. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/routing.py +14 -10
  9. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/simulation.py +33 -23
  10. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/io/state.py +47 -1
  11. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/grid_operations.py +55 -38
  12. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/hillslope_reach_mapping.py +2 -1
  13. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/io.py +1 -1
  14. {mobidicpy-0.2.0 → mobidicpy-0.2.2/mobidicpy.egg-info}/PKG-INFO +2 -2
  15. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidicpy.egg-info/requires.txt +1 -1
  16. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/pyproject.toml +3 -3
  17. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/LICENSE +0 -0
  18. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/MANIFEST.in +0 -0
  19. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/README.md +0 -0
  20. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/forward_model.py +0 -0
  21. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/instruction.py +0 -0
  22. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/observation.py +0 -0
  23. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/parameter_mapping.py +0 -0
  24. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/pest_setup.py +0 -0
  25. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/results.py +0 -0
  26. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/calibration/template.py +0 -0
  27. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/config/__init__.py +0 -0
  28. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/config/parser.py +0 -0
  29. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/__init__.py +0 -0
  30. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/constants.py +0 -0
  31. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/crop_coefficients.py +0 -0
  32. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/energy_balance.py +0 -0
  33. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/groundwater.py +0 -0
  34. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/interpolation.py +0 -0
  35. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/pet.py +0 -0
  36. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/reservoir.py +0 -0
  37. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/core/soil_water_balance.py +0 -0
  38. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/data/__init__.py +0 -0
  39. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/data/kc_clc_mapping.csv +0 -0
  40. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/io/__init__.py +0 -0
  41. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/io/meteo.py +0 -0
  42. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/io/report.py +0 -0
  43. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/__init__.py +0 -0
  44. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/gis_reader.py +0 -0
  45. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/hyetograph.py +0 -0
  46. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/meteo_preprocessing.py +0 -0
  47. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/meteo_raster.py +0 -0
  48. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/preprocessor.py +0 -0
  49. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/reservoirs.py +0 -0
  50. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/preprocessing/river_network.py +0 -0
  51. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/py.typed +0 -0
  52. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/utils/__init__.py +0 -0
  53. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/utils/crs.py +0 -0
  54. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidic/utils/logging.py +0 -0
  55. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidicpy.egg-info/SOURCES.txt +0 -0
  56. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidicpy.egg-info/dependency_links.txt +0 -0
  57. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/mobidicpy.egg-info/top_level.txt +0 -0
  58. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/setup.cfg +0 -0
  59. {mobidicpy-0.2.0 → mobidicpy-0.2.2}/tests/test_package.py +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.0"
12
+ version: "0.2.2"
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.0
3
+ Version: 0.2.2
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
@@ -38,7 +38,7 @@ Requires-Dist: pytest>=7.0; extra == "dev"
38
38
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
39
39
  Requires-Dist: coverage>=7.0; extra == "dev"
40
40
  Requires-Dist: genbadge[coverage]>=1.1.3; extra == "dev"
41
- Requires-Dist: ruff>=0.2.0; extra == "dev"
41
+ Requires-Dist: ruff>=0.2.1; extra == "dev"
42
42
  Requires-Dist: bump-my-version>=1.0; extra == "dev"
43
43
  Provides-Extra: calibration
44
44
  Requires-Dist: pyemu>=1.4.0; extra == "calibration"
@@ -1,6 +1,6 @@
1
1
  """MOBIDIC - Distributed and continuous hydrological balance model."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.2.2"
4
4
 
5
5
  from mobidic.config import MOBIDICConfig
6
6
  from mobidic.config import load_config
@@ -16,13 +16,8 @@ from mobidic.calibration.config import (
16
16
  load_calibration_config,
17
17
  )
18
18
  from mobidic.calibration.metrics import (
19
+ METRIC_REGISTRY,
19
20
  compute_metrics,
20
- kge,
21
- nse,
22
- nse_log,
23
- pbias,
24
- peak_error,
25
- rmse,
26
21
  )
27
22
  from mobidic.calibration.observation import (
28
23
  align_observations_to_simulation,
@@ -46,11 +41,6 @@ __all__ = [
46
41
  "load_observations",
47
42
  "align_observations_to_simulation",
48
43
  # Metrics
49
- "nse",
50
- "nse_log",
51
- "pbias",
52
- "peak_error",
53
- "rmse",
54
- "kge",
55
44
  "compute_metrics",
45
+ "METRIC_REGISTRY",
56
46
  ]
@@ -1,14 +1,69 @@
1
1
  """Pydantic models for PEST++ calibration configuration."""
2
2
 
3
3
  import os
4
+ import types
4
5
  from pathlib import Path
5
- from typing import Literal, Optional
6
+ from typing import Literal, Optional, Union, get_args, get_origin
6
7
 
7
8
  import pandas as pd
8
9
  from loguru import logger
9
10
  from pydantic import BaseModel, Field, field_validator, model_validator
10
11
 
11
12
 
13
+ def _unwrap_optional(annotation: object) -> object:
14
+ """Strip a single layer of Optional/Union-with-None wrapping."""
15
+ origin = get_origin(annotation)
16
+ if origin is Union or origin is types.UnionType:
17
+ non_none = [a for a in get_args(annotation) if a is not type(None)]
18
+ if len(non_none) == 1:
19
+ return non_none[0]
20
+ return annotation
21
+
22
+
23
+ def _validate_mobidic_parameter_path(dot_path: str) -> None:
24
+ """Verify dot-notation path resolves to a numeric field in MOBIDICConfig.
25
+
26
+ Walks the Pydantic schema field-by-field to ensure every segment exists,
27
+ and that the leaf type is float or int (i.e. a calibratable scalar).
28
+ """
29
+ from mobidic.config.schema import MOBIDICConfig
30
+
31
+ parts = dot_path.split(".")
32
+ if not parts or not all(p for p in parts):
33
+ raise ValueError(
34
+ f"parameter_key '{dot_path}' is not a valid dot-notation path "
35
+ "(expected non-empty dot-separated segments, e.g. 'parameters.multipliers.ks_factor')"
36
+ )
37
+
38
+ current: object = MOBIDICConfig
39
+ for i, part in enumerate(parts):
40
+ if not (isinstance(current, type) and issubclass(current, BaseModel)):
41
+ joined = ".".join(parts[:i]) or "<root>"
42
+ raise ValueError(
43
+ f"parameter_key '{dot_path}': cannot descend into '{part}' because "
44
+ f"'{joined}' is not a Pydantic model in MOBIDICConfig schema"
45
+ )
46
+ if part not in current.model_fields:
47
+ joined = ".".join(parts[:i]) or "<root>"
48
+ valid = sorted(current.model_fields.keys())
49
+ raise ValueError(
50
+ f"parameter_key '{dot_path}': '{part}' is not a field of "
51
+ f"{current.__name__} (at '{joined}'). Valid fields: {valid}"
52
+ )
53
+ current = _unwrap_optional(current.model_fields[part].annotation)
54
+
55
+ if isinstance(current, type) and issubclass(current, BaseModel):
56
+ raise ValueError(
57
+ f"parameter_key '{dot_path}' resolves to nested model '{current.__name__}', "
58
+ "not a scalar field. Provide a dot-path to a numeric leaf parameter."
59
+ )
60
+ if current is not float and current is not int:
61
+ raise ValueError(
62
+ f"parameter_key '{dot_path}' resolves to type {current!r}, but calibration "
63
+ "parameters must point to a numeric (float or int) field in MOBIDICConfig"
64
+ )
65
+
66
+
12
67
  class CalibrationParameter(BaseModel):
13
68
  """A single parameter to be calibrated by PEST++."""
14
69
 
@@ -32,6 +87,13 @@ class CalibrationParameter(BaseModel):
32
87
  raise ValueError("Parameter name cannot contain spaces")
33
88
  return v
34
89
 
90
+ @field_validator("parameter_key")
91
+ @classmethod
92
+ def check_parameter_key_resolves(cls, v: str) -> str:
93
+ """Validate that parameter_key points to a numeric field in MOBIDICConfig."""
94
+ _validate_mobidic_parameter_path(v)
95
+ return v
96
+
35
97
  @model_validator(mode="after")
36
98
  def check_bounds(self) -> "CalibrationParameter":
37
99
  """Validate that lower_bound < upper_bound and initial_value is within bounds."""
@@ -50,7 +112,12 @@ class CalibrationParameter(BaseModel):
50
112
  class MetricConfig(BaseModel):
51
113
  """Configuration for a derived metric used as pseudo-observation."""
52
114
 
53
- metric: str = Field(..., description="Metric name (nse, nse_log, pbias, peak_error, rmse, kge)")
115
+ metric: str = Field(
116
+ ...,
117
+ description="Metric name. Custom: nse, nse_log, pbias, peak_error. "
118
+ "Plus all HydroErr metrics (rmse, kge, kge_2009, kge_2012, mle, mae, mape, "
119
+ "r_squared, pearson_r, ve, d, d1, ...). See METRIC_REGISTRY for the full list.",
120
+ )
54
121
  target: float = Field(..., description="Target value PEST++ tries to match (e.g., 1.0 for NSE)")
55
122
  weight: float = Field(1.0, description="Observation weight for this metric")
56
123
 
@@ -58,9 +125,10 @@ class MetricConfig(BaseModel):
58
125
  @classmethod
59
126
  def check_metric_name(cls, v: str) -> str:
60
127
  """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)}")
128
+ from mobidic.calibration.metrics import METRIC_REGISTRY
129
+
130
+ if v not in METRIC_REGISTRY:
131
+ raise ValueError(f"Unsupported metric '{v}'. Supported: {sorted(METRIC_REGISTRY.keys())}")
64
132
  return v
65
133
 
66
134
  @field_validator("weight")
@@ -2,9 +2,17 @@
2
2
 
3
3
  Metrics are computed from simulated and observed time series and can be passed
4
4
  to PEST++ as pseudo-observations for custom objective functions.
5
+
6
+ Includes custom implementations (nse, nse_log, pbias, peak_error) and the full
7
+ catalog of HydroErr metrics exposed via the ``he`` module
8
+ (see https://hydroerr.readthedocs.io/en/stable/list_of_metrics.html).
5
9
  """
6
10
 
7
11
  import numpy as np
12
+ import HydroErr as he
13
+
14
+
15
+ ######## CUSTOM METRIC IMPLEMENTATIONS ########
8
16
 
9
17
 
10
18
  def nse(simulated: np.ndarray, observed: np.ndarray) -> float:
@@ -80,63 +88,105 @@ def peak_error(simulated: np.ndarray, observed: np.ndarray) -> float:
80
88
  return (np.max(simulated) - obs_peak) / obs_peak
81
89
 
82
90
 
83
- def rmse(simulated: np.ndarray, observed: np.ndarray) -> float:
84
- """Root Mean Square Error.
85
-
86
- Perfect score: 0.0
87
-
88
- Args:
89
- simulated: Simulated values.
90
- observed: Observed values.
91
-
92
- Returns:
93
- RMSE value.
94
- """
95
- return float(np.sqrt(np.mean((simulated - observed) ** 2)))
96
-
97
-
98
- def kge(simulated: np.ndarray, observed: np.ndarray) -> float:
99
- """Kling-Gupta Efficiency.
100
-
101
- KGE = 1 - sqrt((r - 1)^2 + (alpha - 1)^2 + (beta - 1)^2)
102
- where r = correlation, alpha = std(sim)/std(obs), beta = mean(sim)/mean(obs)
103
- Perfect score: 1.0
104
-
105
- Args:
106
- simulated: Simulated values.
107
- observed: Observed values.
108
-
109
- Returns:
110
- KGE value (range: -inf to 1.0).
111
- """
112
- obs_mean = np.mean(observed)
113
- sim_mean = np.mean(simulated)
114
- obs_std = np.std(observed)
115
- sim_std = np.std(simulated)
116
-
117
- if obs_std == 0 or obs_mean == 0:
118
- return np.nan
119
-
120
- # Correlation
121
- r = np.corrcoef(simulated, observed)[0, 1]
122
- # Variability ratio
123
- alpha = sim_std / obs_std
124
- # Bias ratio
125
- beta = sim_mean / obs_mean
126
-
127
- return 1.0 - np.sqrt((r - 1) ** 2 + (alpha - 1) ** 2 + (beta - 1) ** 2)
91
+ ######## HYDROERR METRIC CATALOG ########
92
+ # Maps each HydroErr function name to its perfect-match target value.
93
+ _HYDROERR_TARGETS: dict[str, float] = {
94
+ # Efficiency / agreement / correlation metrics (perfect = 1.0)
95
+ "nse": 1.0,
96
+ "nse_mod": 1.0,
97
+ "nse_rel": 1.0,
98
+ "kge_2009": 1.0,
99
+ "kge_2012": 1.0,
100
+ "lm_index": 1.0,
101
+ "ve": 1.0,
102
+ "d": 1.0,
103
+ "d1": 1.0,
104
+ "d1_p": 1.0,
105
+ "dmod": 1.0,
106
+ "dr": 1.0,
107
+ "drel": 1.0,
108
+ "r_squared": 1.0,
109
+ "pearson_r": 1.0,
110
+ "spearman_r": 1.0,
111
+ "acc": 1.0,
112
+ "mb_r": 1.0,
113
+ "watt_m": 1.0,
114
+ "g_mean_diff": 1.0,
115
+ # Error metrics (perfect = 0.0)
116
+ "rmse": 0.0,
117
+ "mae": 0.0,
118
+ "me": 0.0,
119
+ "mse": 0.0,
120
+ "mle": 0.0,
121
+ "male": 0.0,
122
+ "mape": 0.0,
123
+ "mapd": 0.0,
124
+ "maape": 0.0,
125
+ "mase": 0.0,
126
+ "mdae": 0.0,
127
+ "mde": 0.0,
128
+ "mdse": 0.0,
129
+ "msle": 0.0,
130
+ "rmsle": 0.0,
131
+ "smape1": 0.0,
132
+ "smape2": 0.0,
133
+ "ed": 0.0,
134
+ "ned": 0.0,
135
+ "irmse": 0.0,
136
+ "nrmse_iqr": 0.0,
137
+ "nrmse_mean": 0.0,
138
+ "nrmse_range": 0.0,
139
+ "mean_var": 0.0,
140
+ # Spectral metrics (perfect = 0.0)
141
+ "sa": 0.0,
142
+ "sc": 0.0,
143
+ "sga": 0.0,
144
+ "sid": 0.0,
145
+ # H-series error metrics (perfect = 0.0)
146
+ "h1_mhe": 0.0,
147
+ "h1_mahe": 0.0,
148
+ "h1_rmshe": 0.0,
149
+ "h2_mhe": 0.0,
150
+ "h2_mahe": 0.0,
151
+ "h2_rmshe": 0.0,
152
+ "h3_mhe": 0.0,
153
+ "h3_mahe": 0.0,
154
+ "h3_rmshe": 0.0,
155
+ "h4_mhe": 0.0,
156
+ "h4_mahe": 0.0,
157
+ "h4_rmshe": 0.0,
158
+ "h5_mhe": 0.0,
159
+ "h5_mahe": 0.0,
160
+ "h5_rmshe": 0.0,
161
+ "h6_mhe": 0.0,
162
+ "h6_mahe": 0.0,
163
+ "h6_rmshe": 0.0,
164
+ "h7_mhe": 0.0,
165
+ "h7_mahe": 0.0,
166
+ "h7_rmshe": 0.0,
167
+ "h8_mhe": 0.0,
168
+ "h8_mahe": 0.0,
169
+ "h8_rmshe": 0.0,
170
+ "h10_mhe": 0.0,
171
+ "h10_mahe": 0.0,
172
+ "h10_rmshe": 0.0,
173
+ }
128
174
 
129
175
 
130
- # Registry mapping metric names to (function, target_value)
176
+ # Registry mapping metric names to (function, target_value).
177
+ # Add custom implementations
131
178
  METRIC_REGISTRY: dict[str, tuple] = {
132
179
  "nse": (nse, 1.0),
133
180
  "nse_log": (nse_log, 1.0),
134
181
  "pbias": (pbias, 0.0),
135
182
  "peak_error": (peak_error, 0.0),
136
- "rmse": (rmse, 0.0),
137
- "kge": (kge, 1.0),
183
+ "kge": (he.kge_2012, 1.0),
138
184
  }
139
185
 
186
+ # Add HydroErr metrics
187
+ for _name, _target in _HYDROERR_TARGETS.items():
188
+ METRIC_REGISTRY.setdefault(_name, (getattr(he, _name), _target))
189
+
140
190
 
141
191
  def compute_metrics(
142
192
  simulated: np.ndarray,
@@ -445,6 +445,14 @@ class OutputStates(BaseModel):
445
445
  evapotranspiration: Optional[bool] = Field(
446
446
  False, description="Option to save states of evapotranspiration for results analysis"
447
447
  )
448
+ surface_runoff: Optional[bool] = Field(
449
+ True,
450
+ description=("Option to save per-cell surface runoff rate (flr)."),
451
+ )
452
+ hypodermic_flux: Optional[bool] = Field(
453
+ True,
454
+ description=("Option to save per-cell hypodermic (lateral subsurface) flow rate (fld)."),
455
+ )
448
456
 
449
457
 
450
458
  class OutputStatesSettings(BaseModel):
@@ -98,16 +98,20 @@ def hillslope_routing(
98
98
  Each cell contains ONLY flow from immediate upstream neighbors (NOT its own flow).
99
99
 
100
100
  Notes:
101
- Flow direction coding (D8) - MOBIDIC convention from MATLAB stack8point.m:
102
- MOBIDIC notation (1-8):
103
- 7 6 5
104
- 8 · 4
105
- 1 2 3
106
-
107
- Direction number -> (row_offset, col_offset) in matrix coordinates:
108
- 1: (-1, -1) northwest, 2: (-1, 0) north, 3: (-1, 1) northeast,
109
- 4: (0, 1) east, 5: (1, 1) southeast, 6: (1, 0) south,
110
- 7: (1, -1) southwest, 8: (0, -1) west
101
+ Flow direction coding (D8) - MOBIDIC convention from MATLAB stack8point.m.
102
+ Rasters are loaded with `np.flipud` (in `grid_to_matrix`) so that increasing
103
+ row index corresponds to moving NORTH; the codes/offsets below assume that
104
+ orientation.
105
+
106
+ MOBIDIC notation (1-8, CCW from SW; north up):
107
+ 7 6 5 (NW N NE)
108
+ 8 · 4 (W E)
109
+ 1 2 3 (SW S SE)
110
+
111
+ Direction number -> compass direction -> (row_offset, col_offset):
112
+ 1: SW (-1, -1), 2: S (-1, 0), 3: SE (-1, +1),
113
+ 4: E ( 0, +1), 5: NE (+1, +1), 6: N (+1, 0),
114
+ 7: NW (+1, -1), 8: W ( 0, -1)
111
115
 
112
116
  Special values:
113
117
  0: Outlet cell (no downstream neighbor)
@@ -76,6 +76,8 @@ class SimulationState:
76
76
  ts: np.ndarray | None = None,
77
77
  td: np.ndarray | None = None,
78
78
  et: np.ndarray | None = None,
79
+ flr: np.ndarray | None = None,
80
+ fld: np.ndarray | None = None,
79
81
  ):
80
82
  """Initialize simulation state.
81
83
 
@@ -91,6 +93,8 @@ class SimulationState:
91
93
  ts: Surface temperature [K] (None when energy balance is disabled)
92
94
  td: Deep-soil temperature [K] (None when energy balance is disabled)
93
95
  et: Actual evapotranspiration rate [m/s] (None when ET output is disabled)
96
+ flr: Surface runoff flux [m/s]
97
+ fld: Hypodermic (lateral subsurface) flux [m/s]
94
98
  """
95
99
  self.wc = wc
96
100
  self.wg = wg
@@ -103,6 +107,8 @@ class SimulationState:
103
107
  self.ts = ts
104
108
  self.td = td
105
109
  self.et = et
110
+ self.flr = flr
111
+ self.fld = fld
106
112
 
107
113
 
108
114
  class SimulationResults:
@@ -423,6 +429,10 @@ class Simulation:
423
429
  discharge = np.zeros(len(self.network))
424
430
  lateral_inflow = np.zeros(len(self.network))
425
431
 
432
+ # Initialize surface runoff (flr) and hypodermic flow (fld)
433
+ flr = np.zeros((self.nrows, self.ncols))
434
+ fld = np.zeros((self.nrows, self.ncols))
435
+
426
436
  # Initialize groundwater head when Linear groundwater model is active
427
437
  h = None
428
438
  if self.config.parameters.groundwater.model == "Linear":
@@ -465,7 +475,9 @@ class Simulation:
465
475
  log_msg += f", h={np.nanmean(h) * 1000:.1f} mm"
466
476
  logger.success(log_msg)
467
477
 
468
- return SimulationState(wc, wg, wp, ws, discharge, lateral_inflow, reservoir_states, h=h, ts=ts, td=td)
478
+ return SimulationState(
479
+ wc, wg, wp, ws, discharge, lateral_inflow, reservoir_states, h=h, ts=ts, td=td, flr=flr, fld=fld
480
+ )
469
481
 
470
482
  def set_initial_state(
471
483
  self,
@@ -1111,8 +1123,10 @@ class Simulation:
1111
1123
  # Get sorted reach indices by calc_order
1112
1124
  sorted_reach_idx = network.sort_values("calc_order").index.values.astype(np.int32)
1113
1125
 
1114
- # Extract K (lag time as storage coefficient)
1115
- K = network["lag_time_s"].values
1126
+ # Apply celerity multiplier:
1127
+ # wcel_effective = wcel * cel_factor, therefore K_effective = lag_time_s / cel_factor
1128
+ cel_factor = self.config.parameters.multipliers.cel_factor
1129
+ K = network["lag_time_s"].values / cel_factor
1116
1130
 
1117
1131
  topology = {
1118
1132
  "upstream_1_idx": upstream_1_idx,
@@ -1300,11 +1314,10 @@ class Simulation:
1300
1314
  ko = np.where(ko.ravel("F"))[0]
1301
1315
  logger.debug(f"Contributing pixels (ko): {len(ko)} of {self.nrows * self.ncols} total cells")
1302
1316
 
1303
- # Initialize flow variables for hillslope routing feedback (matching MATLAB mobidic_sid.m:1621-1625)
1304
- # flr_prev: surface runoff from previous timestep [m/s] - will be routed to create pir
1305
- # fld_prev: lateral flow from previous timestep [m/s] - will be routed to create pid
1306
- flr_prev = np.zeros((self.nrows, self.ncols))
1307
- fld_prev = np.zeros((self.nrows, self.ncols))
1317
+ if self.state.flr is None:
1318
+ self.state.flr = np.zeros((self.nrows, self.ncols))
1319
+ if self.state.fld is None:
1320
+ self.state.fld = np.zeros((self.nrows, self.ncols))
1308
1321
 
1309
1322
  # Energy balance preparation.
1310
1323
  # Skip energy balance when ET or PET is provided by the raster forcing.
@@ -1604,17 +1617,19 @@ class Simulation:
1604
1617
  )
1605
1618
  meteo_writer.append(current_time, **meteo_kwargs)
1606
1619
 
1607
- # 4. Hillslope routing of previous timestep's flows (matching MATLAB mobidic_sid.m:1621-1625)
1608
- # This must happen BEFORE soil mass balance to provide upstream contributions
1620
+ # 4. Hillslope routing of the previous timestep's flows.
1609
1621
  logger.debug("Routing previous timestep's flows through hillslope")
1610
1622
 
1623
+ flr_for_routing = self.state.flr.copy()
1624
+ flr_for_routing[self.hillslope_reach_map >= 0] = 0.0
1625
+
1611
1626
  # Convert to discharge for routing
1612
- flr_prev_discharge = flr_prev * cell_area
1613
- fld_prev_discharge = fld_prev * cell_area
1627
+ flr_in_discharge = flr_for_routing * cell_area
1628
+ fld_in_discharge = self.state.fld * cell_area
1614
1629
 
1615
1630
  # Route through hillslope
1616
- pir_discharge = hillslope_routing(flr_prev_discharge, self.flow_dir)
1617
- pid_discharge = hillslope_routing(fld_prev_discharge, self.flow_dir)
1631
+ pir_discharge = hillslope_routing(flr_in_discharge, self.flow_dir)
1632
+ pid_discharge = hillslope_routing(fld_in_discharge, self.flow_dir)
1618
1633
  logger.debug("Hillslope routing completed")
1619
1634
 
1620
1635
  # Convert back to rates
@@ -1876,6 +1891,10 @@ class Simulation:
1876
1891
  # Set upstream count to 0 (MATLAB: ram_fin(j) = 0)
1877
1892
  routing_network["n_upstream"][outlet_reach] = 0
1878
1893
 
1894
+ # Save surface runoff and lateral subsurface flow
1895
+ self.state.flr = flr.copy()
1896
+ self.state.fld = fld.copy()
1897
+
1879
1898
  # 7. Accumulate lateral inflow to reaches from surface runoff (matching MATLAB glob_route_day.m:26-35)
1880
1899
  # Basin cells have flr=0 from reservoir routing, so they correctly contribute nothing.
1881
1900
  flr_discharge = flr * cell_area
@@ -1892,15 +1911,6 @@ class Simulation:
1892
1911
  # Store lateral inflow in state
1893
1912
  self.state.lateral_inflow = lateral_inflow
1894
1913
 
1895
- # Zero out flr for ALL cells that contributed to reaches (matching MATLAB glob_route_day.m line 33)
1896
- # This prevents double-counting - flows from all contributing cells are consumed after accumulation
1897
- flr[self.hillslope_reach_map >= 0] = 0.0
1898
- # Note: fld is NOT zeroed - lateral flow continues to route between hillslope cells
1899
-
1900
- # Store flr and fld for next timestep's routing (at step 3)
1901
- flr_prev = flr.copy()
1902
- fld_prev = fld.copy()
1903
-
1904
1914
  # 8. Channel routing
1905
1915
  logger.debug("Computing channel routing")
1906
1916
  self.state.discharge, routing_state = linear_channel_routing(
@@ -255,6 +255,18 @@ def load_state(
255
255
  logger.warning("lateral_inflow not found in state file, initializing with zeros")
256
256
  lateral_inflow = np.zeros(network_size)
257
257
 
258
+ # Surface runoff (flr) and lateral subsurface flow (fld)
259
+ if "flr" in ds:
260
+ flr = ds["flr"].values
261
+ else:
262
+ logger.warning("flr not found in state file, initializing with zeros")
263
+ flr = np.zeros((nrows, ncols))
264
+ if "fld" in ds:
265
+ fld = ds["fld"].values
266
+ else:
267
+ logger.warning("fld not found in state file, initializing with zeros")
268
+ fld = np.zeros((nrows, ncols))
269
+
258
270
  # Extract time
259
271
  time = pd.Timestamp(ds["time"].values).to_pydatetime()
260
272
 
@@ -279,7 +291,7 @@ def load_state(
279
291
  # Import here to avoid circular import
280
292
  from mobidic.core.simulation import SimulationState
281
293
 
282
- state = SimulationState(wc, wg, wp, ws, discharge, lateral_inflow, h=h, ts=ts, td=td)
294
+ state = SimulationState(wc, wg, wp, ws, discharge, lateral_inflow, h=h, ts=ts, td=td, flr=flr, fld=fld)
283
295
 
284
296
  logger.success(f"State loaded: time={time.isoformat()}, grid={nrows}x{ncols}, reaches={len(discharge)}")
285
297
 
@@ -521,6 +533,8 @@ class StateWriter:
521
533
  ts=state.ts.copy() if state.ts is not None else None,
522
534
  td=state.td.copy() if state.td is not None else None,
523
535
  et=state.et.copy() if state.et is not None else None,
536
+ flr=state.flr.copy() if state.flr is not None else None,
537
+ fld=state.fld.copy() if state.fld is not None else None,
524
538
  )
525
539
 
526
540
  # Add to buffer
@@ -608,6 +622,22 @@ class StateWriter:
608
622
  )
609
623
  data_vars["ET"] = (["time", "y", "x"], et_data)
610
624
 
625
+ # Surface runoff (flr) and hypodermic (lateral subsurface) flow (fld)
626
+ if self.output_states.surface_runoff:
627
+ has_flr = any(s.flr is not None for s in self.buffer)
628
+ if has_flr:
629
+ flr_data = np.array(
630
+ [s.flr if s.flr is not None else np.full((self.nrows, self.ncols), np.nan) for s in self.buffer]
631
+ )
632
+ data_vars["flr"] = (["time", "y", "x"], flr_data)
633
+ if self.output_states.hypodermic_flux:
634
+ has_fld = any(s.fld is not None for s in self.buffer)
635
+ if has_fld:
636
+ fld_data = np.array(
637
+ [s.fld if s.fld is not None else np.full((self.nrows, self.ncols), np.nan) for s in self.buffer]
638
+ )
639
+ data_vars["fld"] = (["time", "y", "x"], fld_data)
640
+
611
641
  # Network variables
612
642
  if self.output_states.discharge:
613
643
  discharge_data = np.array([s.discharge for s in self.buffer])
@@ -714,6 +744,22 @@ class StateWriter:
714
744
  "grid_mapping": "crs",
715
745
  }
716
746
 
747
+ if "flr" in flush_ds:
748
+ flush_ds["flr"].attrs = {
749
+ "long_name": "Surface runoff flux",
750
+ "units": "m s-1",
751
+ "description": "Surface runoff flux",
752
+ "grid_mapping": "crs",
753
+ }
754
+
755
+ if "fld" in flush_ds:
756
+ flush_ds["fld"].attrs = {
757
+ "long_name": "Hypodermic flux",
758
+ "units": "m s-1",
759
+ "description": "Hypodermic (lateral subsurface) flux",
760
+ "grid_mapping": "crs",
761
+ }
762
+
717
763
  if "discharge" in flush_ds:
718
764
  flush_ds["discharge"].attrs = {
719
765
  "long_name": "River Discharge",
@@ -107,11 +107,12 @@ def decimate_flow_direction(
107
107
  Flow accumulation is normalized by factor **2 to account for cell size change.
108
108
 
109
109
  Notes:
110
- This function assumes flow_dir uses Grass 1-8 notation:
110
+ This function operates on flow_dir BEFORE conversion to MOBIDIC notation,
111
+ so input is expected in standard GRASS r.watershed 1-8 notation:
111
112
  1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE, 8=E
112
113
 
113
114
  Examples:
114
- >>> flow_dir = np.array([[2, 2], [2, 2]]) # All cells flow north
115
+ >>> flow_dir = np.array([[2, 2], [2, 2]]) # All cells flow north (Grass code 2)
115
116
  >>> flow_acc = np.array([[1, 1], [3, 4]]) # Different accumulation
116
117
  >>> dec_dir, dec_acc = decimate_flow_direction(flow_dir, flow_acc, factor=2)
117
118
  """
@@ -137,10 +138,11 @@ def decimate_flow_direction(
137
138
  flow_dir_decimated = np.full((nrv, ncv), np.nan, dtype=float)
138
139
  flow_acc_decimated = np.full((nrv, ncv), np.nan, dtype=float)
139
140
 
140
- # Direction offsets for Grass 1-8 notation to MOBIDIC notation
141
- # 1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE, 8=E
141
+ # Direction offsets indexed by code-1, in standard GRASS r.watershed notation
142
+ # (1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE, 8=E). Offsets are matrix-coord
143
+ # (row, col) where row+1 = down (image orientation, before any flipud).
142
144
  di = np.array([-1, -1, -1, 0, 1, 1, 1, 0]) # row offset
143
- dj = np.array([-1, 0, 1, 1, 1, 0, -1, -1]) # column offset
145
+ dj = np.array([1, 0, -1, -1, -1, 0, 1, 1]) # column offset
144
146
 
145
147
  # Minimum number of valid cells required
146
148
  min_valid_cells = int(factor * factor * min_valid_fraction)
@@ -204,17 +206,17 @@ def decimate_flow_direction(
204
206
  flow_dir_decimated[i, j] = -999
205
207
  continue
206
208
 
207
- # Map coarse cell offset to direction (1-8)
208
- # coarse_di, coarse_dj -> direction
209
+ # Map coarse cell offset to direction (1-8) in standard GRASS r.watershed
210
+ # convention (image orientation, row+1 = down).
209
211
  offset_to_dir = {
210
- (-1, -1): 1, # NE (IP=-1, JP=-1 -> -11 -> case 1)
211
- (-1, 0): 2, # N (IP=-1, JP=0 -> -10 -> case 2)
212
- (-1, 1): 3, # NW (IP=-1, JP=1 -> -9 -> case 3)
213
- (0, 1): 4, # W (IP=0, JP=1 -> 1 -> case 4)
214
- (1, 1): 5, # SW (IP=1, JP=1 -> 11 -> case 5)
215
- (1, 0): 6, # S (IP=1, JP=0 -> 10 -> case 6)
216
- (1, -1): 7, # SE (IP=1, JP=-1 -> 9 -> case 7)
217
- (0, -1): 8, # E (IP=0, JP=-1 -> -1 -> case 8)
212
+ (-1, 1): 1, # NE
213
+ (-1, 0): 2, # N
214
+ (-1, -1): 3, # NW
215
+ (0, -1): 4, # W
216
+ (1, -1): 5, # SW
217
+ (1, 0): 6, # S
218
+ (1, 1): 7, # SE
219
+ (0, 1): 8, # E
218
220
  }
219
221
 
220
222
  flow_dir_decimated[i, j] = offset_to_dir.get((coarse_di, coarse_dj), -999)
@@ -253,9 +255,13 @@ def convert_to_mobidic_notation(
253
255
  ) -> np.ndarray:
254
256
  """Convert flow direction from Grass or Arc notation to MOBIDIC notation.
255
257
 
256
- MOBIDIC uses a transformed version of the Grass notation with a 180-degree rotation.
257
- This transformation is applied in MATLAB's buildgis_mysql_include.m:
258
- AI=[1 2 3 4 5 6 7 8]; MD=[5 6 7 8 1 2 3 4];
258
+ Translates standard GRASS r.watershed (1-8) or ESRI ArcGIS (powers of 2) flow
259
+ direction codes to MOBIDIC's internal D8 encoding. The renumbering is
260
+ direction-preserving (each input code maps to the MOBIDIC code with the same
261
+ physical compass direction). The mapping matches MATLAB's
262
+ buildgis_mysql_include.m:
263
+ GRASS: AI=[1 2 3 4 5 6 7 8]; MD=[5 6 7 8 1 2 3 4];
264
+ ArcGIS: AI=[1 2 4 8 16 32 64 128]; MD=[4 3 2 1 8 7 6 5];
259
265
 
260
266
  Args:
261
267
  flow_dir: 2D numpy array with flow directions (NaN for nodata).
@@ -265,25 +271,36 @@ def convert_to_mobidic_notation(
265
271
  Flow direction array converted to MOBIDIC notation (1-8).
266
272
 
267
273
  Notes:
268
- Transformation mappings:
269
- - GRASS -> MOBIDIC: 1->5, 2->6, 3->7, 4->8, 5->1, 6->2, 7->3, 8->4
270
- - Arc values are first converted to Grass, then to MOBIDIC
271
-
272
- Notation comparison:
273
- GRASS: MOBIDIC:
274
- 7 6 5 3 2 1
275
- 8 4 4 8
276
- 1 2 3 5 6 7
277
-
278
- MOBIDIC directions:
279
- 1: up-right (row -1, col +1)
280
- 2: up (row -1, col 0)
281
- 3: up-left (row -1, col -1)
282
- 4: left (row 0, col -1)
283
- 5: down-left (row +1, col -1)
284
- 6: down (row +1, col 0)
285
- 7: down-right (row +1, col +1)
286
- 8: right (row 0, col +1)
274
+ Standard GRASS r.watershed convention (1-8, CCW from NE; north up):
275
+
276
+ 3 2 1 1 = NE 5 = SW
277
+ 4 . 8 2 = N 6 = S
278
+ 5 6 7 3 = NW 7 = SE
279
+ 4 = W 8 = E
280
+
281
+ Standard ESRI ArcGIS convention (powers of 2, CW from E; north up):
282
+
283
+ 32 64 128 1 = E 16 = W
284
+ 16 . 1 2 = SE 32 = NW
285
+ 8 4 2 4 = S 64 = N
286
+ 8 = SW 128 = NE
287
+
288
+ MOBIDIC convention (1-8, CCW from SW; north up):
289
+
290
+ 7 6 5 1 = SW 5 = NE
291
+ 8 . 4 2 = S 6 = N
292
+ 1 2 3 3 = SE 7 = NW
293
+ 4 = E 8 = W
294
+
295
+ Direction-preserving mapping:
296
+ GRASS -> MOBIDIC: 1->5, 2->6, 3->7, 4->8, 5->1, 6->2, 7->3, 8->4
297
+ ArcGIS -> MOBIDIC: 1->4, 2->3, 4->2, 8->1, 16->8, 32->7, 64->6, 128->5
298
+
299
+ Array orientation: rasters are loaded by `grid_to_matrix()` with `np.flipud`
300
+ so that increasing row index corresponds to moving NORTH. With that
301
+ orientation, MOBIDIC code k drains to the neighbor at offset
302
+ (di, dj) where di = `[-1,-1,-1,0,1,1,1,0][k-1]` and
303
+ dj = `[-1,0,1,1,1,0,-1,-1][k-1]`. For example, code 5 (NE) -> (+1, +1).
287
304
 
288
305
  Examples:
289
306
  >>> flow_dir_grass = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 1]])
@@ -298,7 +315,7 @@ def convert_to_mobidic_notation(
298
315
  grass_to_mobidic = {1: 5, 2: 6, 3: 7, 4: 8, 5: 1, 6: 2, 7: 3, 8: 4}
299
316
 
300
317
  # Arc to GRASS mapping
301
- arc_to_grass = {1: 8, 2: 1, 4: 2, 8: 3, 16: 4, 32: 5, 64: 6, 128: 7}
318
+ arc_to_grass = {1: 8, 2: 7, 4: 6, 8: 5, 16: 4, 32: 3, 64: 2, 128: 1}
302
319
 
303
320
  # Create output array
304
321
  converted = flow_dir.copy()
@@ -229,7 +229,8 @@ def map_hillslope_to_reach(
229
229
 
230
230
  logger.debug(f"Lookup table built: {len(cell_to_reach)} reach cells")
231
231
 
232
- # Direction offsets for MOBIDIC notation (1-8)
232
+ # Direction offsets for MOBIDIC notation (1-8, CCW from SW; north up).
233
+ # Code k (1..8) -> (di[k-1], dj[k-1]); e.g. 1=SW -> (-1,-1), 5=NE -> (+1,+1).
233
234
  di = np.array([-1, -1, -1, 0, 1, 1, 1, 0]) # row offset (matches i8)
234
235
  dj = np.array([-1, 0, 1, 1, 1, 0, -1, -1]) # column offset (matches j8)
235
236
 
@@ -114,7 +114,7 @@ def save_gisdata(gisdata: "GISData", output_path: str | Path) -> None:
114
114
  "long_name": "Flow Direction",
115
115
  "units": "1",
116
116
  "description": "Flow direction in MOBIDIC notation (1-8)",
117
- "notation": "MOBIDIC: 1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE, 8=E",
117
+ "notation": "MOBIDIC: 1=SW, 2=S, 3=SE, 4=E, 5=NE, 6=N, 7=NW, 8=W (north up; row+1=N)",
118
118
  "grid_mapping": "crs",
119
119
  }
120
120
  ds["flow_acc"].attrs = {
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mobidicpy
3
- Version: 0.2.0
3
+ Version: 0.2.2
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
@@ -38,7 +38,7 @@ Requires-Dist: pytest>=7.0; extra == "dev"
38
38
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
39
39
  Requires-Dist: coverage>=7.0; extra == "dev"
40
40
  Requires-Dist: genbadge[coverage]>=1.1.3; extra == "dev"
41
- Requires-Dist: ruff>=0.2.0; extra == "dev"
41
+ Requires-Dist: ruff>=0.2.1; extra == "dev"
42
42
  Requires-Dist: bump-my-version>=1.0; extra == "dev"
43
43
  Provides-Extra: calibration
44
44
  Requires-Dist: pyemu>=1.4.0; extra == "calibration"
@@ -21,7 +21,7 @@ pytest>=7.0
21
21
  pytest-cov>=4.0
22
22
  coverage>=7.0
23
23
  genbadge[coverage]>=1.1.3
24
- ruff>=0.2.0
24
+ ruff>=0.2.1
25
25
  bump-my-version>=1.0
26
26
 
27
27
  [doc]
@@ -40,7 +40,7 @@ license = "Apache-2.0"
40
40
  name = "mobidicpy"
41
41
  readme = {file = "README.md", content-type = "text/markdown"}
42
42
  requires-python = ">=3.11"
43
- version = "0.2.0"
43
+ version = "0.2.2"
44
44
 
45
45
 
46
46
  [project.optional-dependencies]
@@ -49,7 +49,7 @@ dev = [
49
49
  "pytest-cov>=4.0",
50
50
  "coverage>=7.0",
51
51
  "genbadge[coverage]>=1.1.3",
52
- "ruff>=0.2.0",
52
+ "ruff>=0.2.1",
53
53
  "bump-my-version>=1.0",
54
54
  ]
55
55
  calibration = [
@@ -136,7 +136,7 @@ force-single-line = true
136
136
  no-lines-before = ["future","standard-library","third-party","first-party","local-folder"]
137
137
 
138
138
  [tool.bumpversion]
139
- current_version = "0.2.0"
139
+ current_version = "0.2.2"
140
140
 
141
141
  [[tool.bumpversion.files]]
142
142
  filename = "mobidic/__init__.py"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes