flopy-surrogate 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.
@@ -0,0 +1,35 @@
1
+ """
2
+ FloPySurrogate
3
+ ==============
4
+
5
+ Surrogate simulators for MODFLOW-based groundwater models.
6
+
7
+ Core concept: train a fast neural-network surrogate to predict head-field
8
+ evolution over *N* time steps, then **rebase** against the real MODFLOW
9
+ solution to limit error accumulation. The user defines the surrogate
10
+ architecture, the rebase interval, and the data pipeline – all in a few
11
+ lines.
12
+
13
+ Quick start
14
+ -----------
15
+ >>> from flopy_surrogate import SurrogateSimulator, MLPHeadPredictor
16
+ >>> sim = SurrogateSimulator(
17
+ ... model=MLPHeadPredictor(in_dim=5, out_dim=100*100),
18
+ ... rebase_every=10,
19
+ ... )
20
+ >>> sim.train(X_train, Y_train, epochs=50)
21
+ >>> heads = sim.run(X_init, total_steps=200)
22
+ """
23
+
24
+ from flopy_surrogate.core.surrogate import SurrogateSimulator
25
+ from flopy_surrogate.core.dataset import SurrogateDataset
26
+ from flopy_surrogate.models.mlp import MLPHeadPredictor
27
+ from flopy_surrogate.models.base import BaseSurrogateModel
28
+
29
+ __version__ = "0.1.0"
30
+ __all__ = [
31
+ "SurrogateSimulator",
32
+ "SurrogateDataset",
33
+ "MLPHeadPredictor",
34
+ "BaseSurrogateModel",
35
+ ]
@@ -0,0 +1,4 @@
1
+ from flopy_surrogate.core.surrogate import SurrogateSimulator
2
+ from flopy_surrogate.core.dataset import SurrogateDataset
3
+
4
+ __all__ = ["SurrogateSimulator", "SurrogateDataset"]
@@ -0,0 +1,30 @@
1
+ """Dataset utilities for surrogate training."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+
10
+ class SurrogateDataset(Dataset):
11
+ """PyTorch Dataset wrapping numpy ``(X, Y)`` arrays.
12
+
13
+ Parameters
14
+ ----------
15
+ X : np.ndarray
16
+ Input states, shape ``(N, in_dim)``.
17
+ Y : np.ndarray
18
+ Target outputs (head fields), shape ``(N, out_dim)``.
19
+ """
20
+
21
+ def __init__(self, X: np.ndarray, Y: np.ndarray) -> None:
22
+ super().__init__()
23
+ self.X = torch.from_numpy(np.ascontiguousarray(X, dtype=np.float32))
24
+ self.Y = torch.from_numpy(np.ascontiguousarray(Y, dtype=np.float32))
25
+
26
+ def __len__(self) -> int:
27
+ return self.X.shape[0]
28
+
29
+ def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
30
+ return self.X[idx], self.Y[idx]
@@ -0,0 +1,201 @@
1
+ """SurrogateSimulator – the main user-facing class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import torch
11
+
12
+ from flopy_surrogate.core.dataset import SurrogateDataset
13
+ from flopy_surrogate.models.base import BaseSurrogateModel
14
+ from flopy_surrogate.train.trainer import Trainer
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class SurrogateSimulator:
20
+ """Train and run a surrogate for a MODFLOW-based groundwater model.
21
+
22
+ Parameters
23
+ ----------
24
+ model : BaseSurrogateModel
25
+ A user-defined (or built-in) PyTorch surrogate model.
26
+ env : FloPyGroundwaterEnv, optional
27
+ The real MODFLOW environment used for **rebase** during inference.
28
+ If ``None``, the surrogate runs without rebasing (pure prediction).
29
+ rebase_every : int
30
+ Number of surrogate steps between rebases. Default ``10``.
31
+ device : str
32
+ ``"cpu"``, ``"cuda"``, or let PyTorch decide (``None``).
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ model: BaseSurrogateModel,
38
+ env: Any | None = None,
39
+ rebase_every: int = 10,
40
+ device: str | None = None,
41
+ ) -> None:
42
+ self.model = model
43
+ self.env = env
44
+ self.rebase_every = rebase_every
45
+ self.device = torch.device(
46
+ device or ("cuda" if torch.cuda.is_available() else "cpu")
47
+ )
48
+ self.model.to(self.device)
49
+ self._trained = False
50
+
51
+ # ------------------------------------------------------------------ #
52
+ # training
53
+ # ------------------------------------------------------------------ #
54
+ def train(
55
+ self,
56
+ X_train: np.ndarray,
57
+ Y_train: np.ndarray,
58
+ X_val: np.ndarray | None = None,
59
+ Y_val: np.ndarray | None = None,
60
+ epochs: int = 100,
61
+ batch_size: int = 128,
62
+ lr: float = 3e-4,
63
+ patience: int = 15,
64
+ save_path: str | Path | None = None,
65
+ ) -> dict[str, list[float]]:
66
+ """Train the surrogate model.
67
+
68
+ Parameters
69
+ ----------
70
+ X_train, Y_train : np.ndarray
71
+ Training arrays.
72
+ X_val, Y_val : np.ndarray, optional
73
+ Validation arrays (for early stopping).
74
+ epochs : int
75
+ Maximum training epochs.
76
+ batch_size : int
77
+ lr : float
78
+ Learning rate for Adam.
79
+ patience : int
80
+ Early-stopping patience (epochs without val improvement).
81
+ save_path : str or Path, optional
82
+ If given, the best model is saved here (``.pt``).
83
+
84
+ Returns
85
+ -------
86
+ dict
87
+ History with ``"train_loss"`` and (if valid) ``"val_loss"`` lists.
88
+ """
89
+ ds_train = SurrogateDataset(X_train, Y_train)
90
+ ds_val = SurrogateDataset(X_val, Y_val) if X_val is not None else None
91
+
92
+ trainer = Trainer(
93
+ model=self.model,
94
+ train_ds=ds_train,
95
+ val_ds=ds_val,
96
+ device=self.device,
97
+ lr=lr,
98
+ patience=patience,
99
+ )
100
+ history = trainer.fit(epochs=epochs, batch_size=batch_size, save_path=save_path)
101
+ self._trained = True
102
+ return history
103
+
104
+ # ------------------------------------------------------------------ #
105
+ # inference
106
+ # ------------------------------------------------------------------ #
107
+ def predict(self, x: np.ndarray) -> np.ndarray:
108
+ """Single forward pass (no rebasing).
109
+
110
+ Parameters
111
+ ----------
112
+ x : np.ndarray
113
+ Input state, shape ``(in_dim,)`` or ``(1, in_dim)``.
114
+
115
+ Returns
116
+ -------
117
+ np.ndarray
118
+ Predicted state, shape ``(out_dim,)``.
119
+ """
120
+ self.model.eval()
121
+ with torch.no_grad():
122
+ t = torch.from_numpy(
123
+ np.ascontiguousarray(x, dtype=np.float32).flatten()
124
+ ).float().unsqueeze(0).to(self.device)
125
+ out = self.model(t)
126
+ return out.squeeze(0).cpu().numpy()
127
+
128
+ def run(
129
+ self,
130
+ x_init: np.ndarray,
131
+ total_steps: int,
132
+ param_schedule: list[np.ndarray] | None = None,
133
+ ) -> list[np.ndarray]:
134
+ """Run the surrogate for *total_steps* time steps with periodic rebasing.
135
+
136
+ At every :attr:`rebase_every`-th step the simulator calls the real
137
+ MODFLOW model (via :attr:`env`) to obtain ground-truth heads and
138
+ resets the internal state, limiting error drift.
139
+
140
+ Parameters
141
+ ----------
142
+ x_init : np.ndarray
143
+ Initial state vector.
144
+ total_steps : int
145
+ Total number of time steps to simulate.
146
+ param_schedule : list[np.ndarray], optional
147
+ Per-step parameter vectors (e.g. time-varying pumping rates).
148
+ If ``None``, the surrogate is applied to the current state only.
149
+
150
+ Returns
151
+ -------
152
+ list[np.ndarray]
153
+ State at every step (length ``total_steps + 1`` including initial).
154
+ """
155
+ self.model.eval()
156
+ state = np.asarray(x_init, dtype=np.float32).flatten()
157
+ trajectory = [state.copy()]
158
+
159
+ with torch.no_grad():
160
+ for step in range(total_steps):
161
+ if param_schedule is not None:
162
+ x_input = np.concatenate([state, param_schedule[step]])
163
+ else:
164
+ x_input = state
165
+
166
+ t = torch.from_numpy(
167
+ np.ascontiguousarray(x_input, dtype=np.float32)
168
+ ).float().unsqueeze(0).to(self.device)
169
+ state = self.model(t).squeeze(0).cpu().numpy()
170
+ trajectory.append(state.copy())
171
+
172
+ # ---- rebase: 1 MODFLOW step to reground ----
173
+ if self.env is not None and (step + 1) % self.rebase_every == 0:
174
+ gt_state = self.env.step(n=1)
175
+ state = gt_state
176
+ trajectory[-1] = state.copy()
177
+ logger.debug("rebase at step %d (1 MODFLOW step)", step + 1)
178
+
179
+ return trajectory
180
+
181
+ # ------------------------------------------------------------------ #
182
+ # persistence
183
+ # ------------------------------------------------------------------ #
184
+ def save(self, path: str | Path) -> None:
185
+ """Save model weights to *path* (``.pt``)."""
186
+ torch.save({
187
+ "model_state_dict": self.model.state_dict(),
188
+ "in_dim": self.model.in_dim,
189
+ "out_dim": self.model.out_dim,
190
+ "rebase_every": self.rebase_every,
191
+ }, path)
192
+ logger.info("model saved to %s", path)
193
+
194
+ def load(self, path: str | Path) -> None:
195
+ """Load model weights from *path*."""
196
+ ckpt = torch.load(path, map_location=self.device, weights_only=True)
197
+ self.model.load_state_dict(ckpt["model_state_dict"])
198
+ if "rebase_every" in ckpt:
199
+ self.rebase_every = ckpt["rebase_every"]
200
+ self._trained = True
201
+ logger.info("model loaded from %s", path)
@@ -0,0 +1,4 @@
1
+ from flopy_surrogate.env.flopy_env import FloPyGroundwaterEnv
2
+ from flopy_surrogate.env.mf6_env import MF6FileEnv
3
+
4
+ __all__ = ["FloPyGroundwaterEnv", "MF6FileEnv"]
@@ -0,0 +1,128 @@
1
+ """Wrapper around a flopy MODFLOW model for data generation and rebase."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class FloPyGroundwaterEnv:
14
+ """Thin wrapper that exposes a flopy model's state as a flat numpy vector.
15
+
16
+ Parameters
17
+ ----------
18
+ model : flopy.modflow.Modflow
19
+ A configured and (optionally) solved flopy model.
20
+ nsteps_per_rebase : int
21
+ Number of MODFLOW time steps to advance on each rebase call.
22
+ """
23
+
24
+ def __init__(self, model: Any, nsteps_per_rebase: int = 1) -> None:
25
+ self.model = model
26
+ self.nsteps_per_rebase = nsteps_per_rebase
27
+
28
+ # ------------------------------------------------------------------ #
29
+ # state extraction
30
+ # ------------------------------------------------------------------ #
31
+ def get_state(self) -> np.ndarray:
32
+ """Return the current head field as a flat float32 vector."""
33
+ heads = self.model.head.copy()
34
+ return np.asarray(heads, dtype=np.float32).flatten()
35
+
36
+ def set_state(self, state: np.ndarray) -> None:
37
+ """Overwrite the model's head array with *state*."""
38
+ arr = np.asarray(state, dtype=np.float32).reshape(self.model.head.shape)
39
+ self.model.head.array = arr
40
+
41
+ # ------------------------------------------------------------------ #
42
+ # stepping
43
+ # ------------------------------------------------------------------ #
44
+ def step(self, n: int | None = None) -> np.ndarray:
45
+ """Advance the MODFLOW model by *n* time steps and return the new state.
46
+
47
+ Parameters
48
+ ----------
49
+ n : int, optional
50
+ Number of steps. Defaults to :attr:`nsteps_per_rebase`.
51
+ """
52
+ n = n or self.nsteps_per_rebase
53
+ for _ in range(n):
54
+ self.model.solve(silent=True)
55
+ return self.get_state()
56
+
57
+ def reset(self) -> np.ndarray:
58
+ """Reset the model to its initial condition and return the state."""
59
+ self.model.reset()
60
+ self.model.solve(silent=True)
61
+ return self.get_state()
62
+
63
+ # ------------------------------------------------------------------ #
64
+ # data generation
65
+ # ------------------------------------------------------------------ #
66
+ def generate_dataset(
67
+ self,
68
+ param_ranges: dict[str, tuple[float, float]],
69
+ n_samples: int = 1000,
70
+ seed: int | None = None,
71
+ ) -> tuple[np.ndarray, np.ndarray]:
72
+ """Sweep parameter ranges and collect (input, head) pairs.
73
+
74
+ Parameters
75
+ ----------
76
+ param_ranges : dict
77
+ Mapping of model-parameter names to ``(min, max)`` ranges.
78
+ Example: ``{"Q_well": (-50, -5), "K": (1e-4, 1e-2)}``.
79
+ n_samples : int
80
+ Number of random draws.
81
+ seed : int, optional
82
+ RNG seed for reproducibility.
83
+
84
+ Returns
85
+ -------
86
+ X, Y : np.ndarray
87
+ Shape ``(n_samples, n_params)`` and ``(n_samples, n_cells)``.
88
+ """
89
+ rng = np.random.default_rng(seed)
90
+ keys = list(param_ranges.keys())
91
+ n_cells = self.model.nlay * self.model.nrow * self.model.ncol
92
+ X = np.empty((n_samples, len(keys)), dtype=np.float32)
93
+ Y = np.empty((n_samples, n_cells), dtype=np.float32)
94
+
95
+ for i in range(n_samples):
96
+ params = {}
97
+ for j, key in enumerate(keys):
98
+ lo, hi = param_ranges[key]
99
+ val = rng.uniform(lo, hi)
100
+ params[key] = val
101
+ X[i, j] = val
102
+ self._apply_params(params)
103
+ self.model.reset()
104
+ self.model.solve(silent=True)
105
+ Y[i] = self.get_state()
106
+ logger.debug("sample %d/%d done", i + 1, n_samples)
107
+
108
+ return X, Y
109
+
110
+ def _apply_params(self, params: dict[str, float]) -> None:
111
+ """Apply parameter values to the flopy model.
112
+
113
+ Override or extend for model-specific logic.
114
+ By default, tries to set ``model.wel[0].q`` for keys containing 'q'
115
+ and ``model.dis.horizontalhydraulicconductivity`` for keys containing 'k'.
116
+ """
117
+ for key, val in params.items():
118
+ kl = key.lower()
119
+ if "q" in kl:
120
+ try:
121
+ self.model.wel[0].q.array[0, 0, 0] = val
122
+ except (AttributeError, IndexError):
123
+ logger.warning("Could not set pumping rate for key '%s'", key)
124
+ elif "k" in kl:
125
+ try:
126
+ self.model.dis.horizontalhydraulicconductivity[0] = val
127
+ except (AttributeError, IndexError, TypeError):
128
+ logger.warning("Could not set K for key '%s'", key)