flopyarcade 0.7.3__tar.gz → 0.7.4__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 (91) hide show
  1. {flopyarcade-0.7.3/flopyarcade.egg-info → flopyarcade-0.7.4}/PKG-INFO +1 -1
  2. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/__init__.py +5 -1
  3. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/agent.py +7 -5
  4. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/benchmark.py +21 -1
  5. flopyarcade-0.7.4/flopyarcade/direct_solver.py +379 -0
  6. flopyarcade-0.7.4/flopyarcade/numba_solver.py +399 -0
  7. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/play.py +21 -0
  8. flopyarcade-0.7.4/flopyarcade/play_split.py +247 -0
  9. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/render.py +23 -2
  10. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/conftest.py +5 -0
  11. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_agent_dqn.py +182 -16
  12. flopyarcade-0.7.4/flopyarcade/tests/test_split_screen.py +225 -0
  13. {flopyarcade-0.7.3 → flopyarcade-0.7.4/flopyarcade.egg-info}/PKG-INFO +1 -1
  14. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade.egg-info/SOURCES.txt +5 -1
  15. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/pyproject.toml +1 -1
  16. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/LICENSE +0 -0
  17. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/MANIFEST.in +0 -0
  18. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/README.md +0 -0
  19. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/actions.py +0 -0
  20. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/arcade.py +0 -0
  21. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/archive_hdf5.py +0 -0
  22. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/env_base.py +0 -0
  23. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/env_config.py +0 -0
  24. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/__init__.py +0 -0
  25. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/1s-d/1s-d +0 -0
  26. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/1s-d/1s-d.tune_metadata +0 -0
  27. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/2s-d/2s-d +0 -0
  28. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/2s-d/2s-d.tune_metadata +0 -0
  29. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/3s-d/3s-d +0 -0
  30. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/3s-d/3s-d.tune_metadata +0 -0
  31. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_dqn.py +0 -0
  32. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_neuroevolution.py +0 -0
  33. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_apexdqn.py +0 -0
  34. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_appo.py +0 -0
  35. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_impala.py +0 -0
  36. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_ppo.py +0 -0
  37. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/flopyarcade.py +0 -0
  38. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/mf6_mp7_runner.py +0 -0
  39. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/mf6_prt_runner.py +0 -0
  40. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/modflow_runner.py +0 -0
  41. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/modpath_runner.py +0 -0
  42. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/observations.py +0 -0
  43. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/play3d.py +0 -0
  44. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/play_againstai.py +0 -0
  45. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/render3d.py +0 -0
  46. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/reward.py +0 -0
  47. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/simulators/simulators_linux.zip +0 -0
  48. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/simulators/simulators_mac.zip +0 -0
  49. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/simulators/simulators_win32.zip +0 -0
  50. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/simulators/simulators_win64.zip +0 -0
  51. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_a10_overlap.py +0 -0
  52. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_agent_neuroevolution.py +0 -0
  53. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_archive_hdf5.py +0 -0
  54. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_blit.py +0 -0
  55. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_c2_novelty_length.py +0 -0
  56. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_c7_action_space.py +0 -0
  57. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_agent2.py +0 -0
  58. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_agent_bench.py +0 -0
  59. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_big.py +0 -0
  60. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_envbase.py +0 -0
  61. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_final_push.py +0 -0
  62. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_final_push2.py +0 -0
  63. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_modflow_deep.py +0 -0
  64. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_actions_obs.py +0 -0
  65. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_archive.py +0 -0
  66. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_rl.py +0 -0
  67. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_push2.py +0 -0
  68. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_render.py +0 -0
  69. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_runners_actions.py +0 -0
  70. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_90.py +0 -0
  71. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_deep.py +0 -0
  72. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_final.py +0 -0
  73. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_gaps.py +0 -0
  74. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_gaps2.py +0 -0
  75. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_max.py +0 -0
  76. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_push.py +0 -0
  77. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_fps.py +0 -0
  78. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_mf6_runners.py +0 -0
  79. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_mock_rllib.py +0 -0
  80. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_play.py +0 -0
  81. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_regression.py +0 -0
  82. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_regression_ci.py +0 -0
  83. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_render3d.py +0 -0
  84. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_reward_reset.py +0 -0
  85. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_rllib_cpu.py +0 -0
  86. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade/tests/test_smooth_trajectory.py +0 -0
  87. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade.egg-info/dependency_links.txt +0 -0
  88. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade.egg-info/entry_points.txt +0 -0
  89. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade.egg-info/requires.txt +0 -0
  90. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/flopyarcade.egg-info/top_level.txt +0 -0
  91. {flopyarcade-0.7.3 → flopyarcade-0.7.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flopyarcade
3
- Version: 0.7.3
3
+ Version: 0.7.4
4
4
  Summary: Simulated groundwater flow environments for reinforcement learning.
5
5
  Author-email: Philipp Hoehn <philipp.hoehn@yahoo.com>
6
6
  License: GNU GPLv3
@@ -42,7 +42,11 @@ if not exists(join(wrkspc, 'simulators', 'win64')):
42
42
 
43
43
 
44
44
  from .flopyarcade import FloPyEnv
45
- from .arcade import FloPyArcade
45
+
46
+ try:
47
+ from .arcade import FloPyArcade
48
+ except ImportError:
49
+ FloPyArcade = None
46
50
 
47
51
  # Solvers are optional — require tensorflow (pip install flopyarcade[solvers])
48
52
  try:
@@ -954,11 +954,12 @@ class FloPyAgent:
954
954
  current_qs_list = self.mainModel.predict(current_states)
955
955
 
956
956
  # retrieving future states from minibatch
957
- # then querying NN model for Q values
958
- # when using target network, query it, otherwise main network should be
959
- # queried
957
+ # then querying target network for Q values (evaluation)
958
+ # and online network for best action selection (Double-DQN)
960
959
  new_current_states = array([transition[3] for transition in minibatch])
961
960
  future_qs_list = self.targetModel.predict(new_current_states)
961
+ # Double-DQN: online network selects argmax action for next state
962
+ next_qs_online = self.mainModel.predict(new_current_states)
962
963
 
963
964
  X, y = [], []
964
965
  # enumerating batches
@@ -967,9 +968,10 @@ class FloPyAgent:
967
968
 
968
969
  # If not a terminal state, get new q from future states,
969
970
  # otherwise set it to 0
970
- # almost like with Q Learning, but we use just part of equation
971
+ # Double-DQN: argmax from online network, Q-value from target network
971
972
  if not done:
972
- max_future_q = max(future_qs_list[index])
973
+ best_action_next = argmax(next_qs_online[index])
974
+ max_future_q = future_qs_list[index][best_action_next]
973
975
  new_q = reward + self.hyParams['DISCOUNT'] * max_future_q
974
976
  else:
975
977
  new_q = reward
@@ -48,6 +48,25 @@ def _try_layer_get(policy: dict, prefix: str, name: str) -> tuple:
48
48
  return k, b
49
49
 
50
50
 
51
+ def _resolve_model_path(model_path: str) -> str:
52
+ """Resolve model path, falling back to package-relative location if CWD-relative fails."""
53
+ if os.path.exists(model_path):
54
+ return model_path
55
+ # Try relative to the package root (handles CI CWD mismatches)
56
+ try:
57
+ pkg_dir = os.path.dirname(os.path.abspath(__file__))
58
+ fallback = os.path.join(pkg_dir, 'examples', 'policymodels', os.path.basename(model_path))
59
+ if os.path.exists(fallback):
60
+ return fallback
61
+ # Also try the full relative path from package root
62
+ fallback2 = os.path.join(os.path.dirname(pkg_dir), model_path)
63
+ if os.path.exists(fallback2):
64
+ return fallback2
65
+ except (NameError, AttributeError):
66
+ pass
67
+ return model_path
68
+
69
+
51
70
  def load_keras_agent(model_path: str):
52
71
  """Load a policy model from various formats.
53
72
 
@@ -58,6 +77,7 @@ def load_keras_agent(model_path: str):
58
77
 
59
78
  Returns a Keras model (or RLlib policy object with predict_on_batch).
60
79
  """
80
+ model_path = _resolve_model_path(model_path)
61
81
  from tensorflow.keras.models import load_model, Sequential
62
82
  from tensorflow.keras.layers import Dense, Activation
63
83
  import numpy as np
@@ -381,7 +401,7 @@ def main():
381
401
  # Print final JSON summary to stdout (for CI capture)
382
402
  print('\n=== RESULTS JSON ===')
383
403
  print(json.dumps(results, indent=2))
384
- return results
404
+ return 0
385
405
 
386
406
 
387
407
  if __name__ == '__main__':
@@ -0,0 +1,379 @@
1
+ """Direct pre-factorized groundwater flow solver.
2
+
3
+ Replaces MODFLOW subprocess with in-process SciPy sparse LU solve.
4
+ Valid for: single-layer, uniform-K, CHD-boundary environments (1s-d, 1s-c, 1r-d, 1r-c).
5
+
6
+ Physics: Backward-Euler finite-difference discretization of
7
+ Sy/dt * (h_new - h_old) = -div(K * grad(h_new)) + q
8
+ which gives the linear system:
9
+ A @ h_new = (Sy/dt) * h_old + b_chd + b_well
10
+
11
+ A is constant (depends only on grid + K + Sy/dt), so we factorize once.
12
+ """
13
+
14
+ import numpy as np
15
+ from scipy.sparse import lil_matrix
16
+ from scipy.sparse.linalg import splu
17
+ from time import time
18
+ from copy import copy
19
+
20
+
21
+ class DirectSolverMixin:
22
+ """Mixin providing `run_direct_solver()` as a drop-in for `runMODFLOW()`.
23
+
24
+ Expected attributes on self (set by env_base / modflow_runner):
25
+ nLay, nRow, nCol – grid dimensions
26
+ dRow, dCol – cell sizes (delr, delc)
27
+ hk – hydraulic conductivity (uniform)
28
+ Sy – specific yield (0.15)
29
+ dt – timestep (periodLength, 1.0)
30
+ periodSteps – timesteps per episode (11)
31
+ headSpecWest, headSpecEast – CHD values
32
+ actionValueSouth, actionValueNorth – CHD values
33
+ wellCellLayer, wellCellColumn, wellCellRow – 0-based well cell
34
+ wellQ – well flow rate (negative = pumping)
35
+ extentX, extentY – domain extent
36
+ minX, minY – domain origin
37
+ zBot, zTop – vertical extent
38
+ particleX, particleY, particleZ – particle position
39
+ trajectories – dict of position lists
40
+ timeStep – current step index (0-based)
41
+ ENVTYPE – environment type string
42
+ """
43
+
44
+ def _direct_build_matrix(self):
45
+ """Build and factorize the constant coefficient matrix A.
46
+
47
+ For 1s-d: all 4 boundaries are CHD (ibound=-1).
48
+ Interior cells: rows 1..nRow-2, cols 1..nCol-2.
49
+ """
50
+ nrow, ncol = self.nRow, self.nCol
51
+ K = self.hk
52
+ Sy = 0.15 # specific yield (from LPF package)
53
+ dt = self.dt if hasattr(self, 'dt') and self.dt else 1.0
54
+ dRow = self.dRow # delr
55
+ dCol = self.dCol # delc
56
+
57
+ # Transmissivities (uniform grid, single layer)
58
+ # T for x-direction flow: K * dRow (perpendicular distance)
59
+ # T for y-direction flow: K * dCol
60
+ Tx = K * dRow # flow in x (col) direction, thickness = dRow
61
+ Ty = K * dCol # flow in y (row) direction, thickness = dCol
62
+
63
+ # Interior mask: exclude all boundary cells
64
+ N = nrow * ncol
65
+ int_mask = np.ones(N, dtype=bool)
66
+ # Row boundaries (top and bottom)
67
+ int_mask[0 * ncol:(0 + 1) * ncol] = False # row 0
68
+ int_mask[(nrow - 1) * ncol:(nrow) * ncol] = False # row nrow-1
69
+ # Col boundaries (left and right)
70
+ for r in range(nrow):
71
+ int_mask[r * ncol + 0] = False
72
+ int_mask[r * ncol + (ncol - 1)] = False
73
+
74
+ int_idx = np.where(int_mask)[0]
75
+ Nint = len(int_idx)
76
+
77
+ # Mapping: flat index → interior index
78
+ flat_to_int = np.full(N, -1, dtype=np.int32)
79
+ for i, f in enumerate(int_idx):
80
+ flat_to_int[f] = i
81
+
82
+ # Build A (LIL for easy construction)
83
+ A = lil_matrix((Nint, Nint))
84
+ self._b_chd = np.zeros(Nint) # constant CHD contribution (values change per episode)
85
+
86
+ # FIXED: Diagonal is ALWAYS 4*K/dx² + Sy/dt for 2D (4-neighbor stencil)
87
+ # CHD neighbors do NOT reduce the diagonal; their contribution goes to RHS.
88
+ diag_val = 4.0 * (K / (dRow * dCol) if dRow != dCol else K / (dRow ** 2)) + Sy / dt
89
+ # For uniform grid (dRow == dCol == dx): diag = 4K/dx² + Sy/dt
90
+ if dRow == dCol:
91
+ beta_x = K / (dRow ** 2)
92
+ beta_y = beta_x
93
+ else:
94
+ beta_x = K / (dRow ** 2) # x-direction (col)
95
+ beta_y = K / (dCol ** 2) # y-direction (row)
96
+ diag_val = 2.0 * beta_x + 2.0 * beta_y + Sy / dt
97
+
98
+ for ii, flat in enumerate(int_idx):
99
+ r = flat // ncol
100
+ c = flat % ncol
101
+
102
+ # West neighbor (c-1)
103
+ if c - 1 == 0:
104
+ pass # CHD: no off-diagonal, contribution in RHS
105
+ else:
106
+ j = flat_to_int[r * ncol + (c - 1)]
107
+ if j >= 0:
108
+ A[ii, j] = -beta_x
109
+
110
+ # East neighbor (c+1)
111
+ if c + 1 == ncol - 1:
112
+ pass # CHD
113
+ else:
114
+ j = flat_to_int[r * ncol + (c + 1)]
115
+ if j >= 0:
116
+ A[ii, j] = -beta_x
117
+
118
+ # North neighbor (r-1)
119
+ if r - 1 == 0:
120
+ pass # CHD
121
+ else:
122
+ j = flat_to_int[(r - 1) * ncol + c]
123
+ if j >= 0:
124
+ A[ii, j] = -beta_y
125
+
126
+ # South neighbor (r+1)
127
+ if r + 1 == nrow - 1:
128
+ pass # CHD
129
+ else:
130
+ j = flat_to_int[(r + 1) * ncol + c]
131
+ if j >= 0:
132
+ A[ii, j] = -beta_y
133
+
134
+ # Diagonal: ALWAYS 4*beta + alpha (unchanged by CHD neighbors)
135
+ A[ii, ii] = diag_val
136
+
137
+ A = A.tocsr()
138
+
139
+ # Factorize (one-time cost ~20ms for 9604x9604)
140
+ self._direct_lu = splu(A.tocsc())
141
+
142
+ # Store metadata
143
+ self._direct_Nint = Nint
144
+ self._direct_flat_to_int = flat_to_int
145
+ self._direct_int_idx = int_idx
146
+ self._direct_int_mask = int_mask
147
+ self._direct_K = K
148
+ self._direct_Sy = Sy
149
+ self._direct_dt = dt
150
+ self._direct_Tx = Tx
151
+ self._direct_Ty = Ty
152
+ self._direct_nrow = nrow
153
+ self._direct_ncol = ncol
154
+ self._direct_head_field = None # will be set after first solve
155
+
156
+ # Store which interior cells are adjacent to each CHD boundary
157
+ # for efficient RHS computation
158
+ self._chd_west_cells = [] # (ii, head_value_slot)
159
+ self._chd_east_cells = []
160
+ self._chd_north_cells = []
161
+ self._chd_south_cells = []
162
+
163
+ for ii, flat in enumerate(int_idx):
164
+ r = flat // ncol
165
+ c = flat % ncol
166
+ if c == 1: # adjacent to west boundary (col 0)
167
+ self._chd_west_cells.append(ii)
168
+ if c == ncol - 2: # adjacent to east boundary (col ncol-1)
169
+ self._chd_east_cells.append(ii)
170
+ if r == 1: # adjacent to north boundary (row 0)
171
+ self._chd_north_cells.append(ii)
172
+ if r == nrow - 2: # adjacent to south boundary (row nrow-1)
173
+ self._chd_south_cells.append(ii)
174
+
175
+ # Convert to arrays for vectorized RHS
176
+ self._chd_west_cells = np.array(self._chd_west_cells, dtype=np.int32)
177
+ self._chd_east_cells = np.array(self._chd_east_cells, dtype=np.int32)
178
+ self._chd_north_cells = np.array(self._chd_north_cells, dtype=np.int32)
179
+ self._chd_south_cells = np.array(self._chd_south_cells, dtype=np.int32)
180
+
181
+ self._direct_built = True
182
+
183
+ def _direct_solve_step(self, h_old_flat, well_flat, well_q,
184
+ chd_west, chd_east, chd_north, chd_south):
185
+ """Solve one timestep: A @ h_new = Sy/dt * h_old + b_chd + b_well.
186
+
187
+ Args:
188
+ h_old_flat: (Nint,) previous heads (interior cells only)
189
+ well_flat: flat index of well cell (full grid), or -1 if none
190
+ well_q: well flow rate (negative = pumping)
191
+ chd_west, chd_east, chd_north, chd_south: boundary head values
192
+
193
+ Returns:
194
+ h_new: (Nint,) new heads (interior cells only)
195
+ """
196
+ Sy = self._direct_Sy
197
+ dt = self._direct_dt
198
+ Tx = self._direct_Tx
199
+ Ty = self._direct_Ty
200
+
201
+ # RHS = Sy/dt * h_old
202
+ b = (Sy / dt) * h_old_flat
203
+
204
+ # Add CHD contributions (vectorized)
205
+ b[self._chd_west_cells] += Tx * chd_west
206
+ b[self._chd_east_cells] += Tx * chd_east
207
+ b[self._chd_north_cells] += Ty * chd_north
208
+ b[self._chd_south_cells] += Ty * chd_south
209
+
210
+ # Add well source (if well is interior)
211
+ if well_flat >= 0:
212
+ wi = self._direct_flat_to_int[well_flat]
213
+ if wi >= 0:
214
+ b[wi] += well_q # Q is already in the right units (L^3/T)
215
+
216
+ # Solve
217
+ h_new = self._direct_lu.solve(b)
218
+ return h_new
219
+
220
+ def _direct_advect_particle(self, h_int, particle_x, particle_y, dt):
221
+ """Euler advection of particle using head gradient.
222
+
223
+ v = -K * grad(h)
224
+ x_new = x + vx * dt
225
+ y_new = y + vy * dt
226
+
227
+ Args:
228
+ h_int: (Nint,) interior heads
229
+ particle_x, particle_y: current position (model coordinates)
230
+ dt: timestep
231
+
232
+ Returns:
233
+ (x_new, y_new)
234
+ """
235
+ nrow = self._direct_nrow
236
+ ncol = self._direct_ncol
237
+ K = self._direct_K
238
+ dRow = self.dRow # delr (row size in y-direction)
239
+ dCol = self.dCol # delc (col size in x-direction)
240
+
241
+ # Convert particle position to cell indices
242
+ # Model coords: x in [0, extentX), y in [0, extentY)
243
+ # Grid: col = x/dCol, row = y/dRow (0-based)
244
+ col_f = particle_x / dCol
245
+ row_f = particle_y / dRow
246
+
247
+ col = int(col_f)
248
+ row = int(row_f)
249
+
250
+ # Clamp to interior
251
+ col = max(1, min(col, ncol - 2))
252
+ row = max(1, min(row, nrow - 2))
253
+
254
+ # Get head at 4 neighbors for central difference
255
+ def get_head(r, c):
256
+ flat = r * ncol + c
257
+ idx = self._direct_flat_to_int[flat]
258
+ if idx >= 0:
259
+ return h_int[idx]
260
+ # Boundary cell: use CHD value
261
+ # For our purposes, clamp to nearest interior
262
+ r_c = max(1, min(r, nrow - 2))
263
+ c_c = max(1, min(c, ncol - 2))
264
+ return h_int[self._direct_flat_to_int[r_c * ncol + c_c]]
265
+
266
+ # Central difference gradient
267
+ h_c = get_head(row, col)
268
+ h_e = get_head(row, col + 1)
269
+ h_w = get_head(row, col - 1)
270
+ h_n = get_head(row - 1, col)
271
+ h_s = get_head(row + 1, col)
272
+
273
+ dh_dx = (h_e - h_w) / (2.0 * dCol)
274
+ dh_dy = (h_n - h_s) / (2.0 * dRow)
275
+
276
+ # Darcy velocity
277
+ vx = -K * dh_dx
278
+ vy = -K * dh_dy
279
+
280
+ # Euler step
281
+ x_new = particle_x + vx * dt
282
+ y_new = particle_y + vy * dt
283
+
284
+ return x_new, y_new
285
+
286
+ def run_direct_solver(self):
287
+ """Drop-in replacement for runMODFLOW() + runMODPATH() + evaluateParticleTracking().
288
+
289
+ Solves the flow equation using pre-factorized matrix and advects
290
+ the particle using Euler method.
291
+ """
292
+ t_start = time()
293
+
294
+ # Build matrix on first call
295
+ if not hasattr(self, '_direct_built') or not self._direct_built:
296
+ self._direct_build_matrix()
297
+
298
+ # Get CHD boundary values
299
+ chd_west = self.headSpecWest
300
+ chd_east = self.headSpecEast
301
+ chd_north = self.actionValueNorth
302
+ chd_south = self.actionValueSouth
303
+
304
+ # Get well position (flat index)
305
+ wl = self.wellCellLayer
306
+ wr = self.wellCellRow
307
+ wc = self.wellCellColumn
308
+ well_flat = wl * self.nRow * self.nCol + wr * self.nCol + wc
309
+ well_q = self.wellQ
310
+
311
+ # Get previous heads (interior)
312
+ if not hasattr(self, '_direct_h_prev') or self._direct_h_prev is None:
313
+ # First step: use starting head (strt)
314
+ h_full = self.strt if hasattr(self, 'strt') else np.ones((1, self.nRow, self.nCol), dtype=np.float64)
315
+ h_flat = h_full.flatten()
316
+ h_prev_int = h_flat[self._direct_int_idx]
317
+ else:
318
+ h_prev_int = self._direct_h_prev
319
+
320
+ # Solve
321
+ h_new_int = self._direct_solve_step(
322
+ h_prev_int, well_flat, well_q,
323
+ chd_west, chd_east, chd_north, chd_south
324
+ )
325
+
326
+ # Reconstruct full head field (1, nRow, nCol)
327
+ h_full = np.zeros(1 * self.nRow * self.nCol, dtype=np.float64)
328
+ h_full[self._direct_int_idx] = h_new_int
329
+
330
+ # Fill boundary cells with CHD values
331
+ for r in range(self.nRow):
332
+ # West (col 0)
333
+ h_full[r * self.nCol + 0] = chd_west
334
+ # East (col nCol-1)
335
+ h_full[r * self.nCol + (self.nCol - 1)] = chd_east
336
+ for c in range(self.nCol):
337
+ # North (row 0)
338
+ h_full[0 * self.nCol + c] = chd_north
339
+ # South (row nRow-1)
340
+ h_full[(self.nRow - 1) * self.nCol + c] = chd_south
341
+
342
+ h_3d = h_full.reshape(1, self.nRow, self.nCol)
343
+
344
+ # Advect particle
345
+ px, py = self.particleX, self.particleY
346
+ dt = self._direct_dt
347
+ px_new, py_new = self._direct_advect_particle(h_new_int, px, py, dt)
348
+
349
+ # Clip to domain
350
+ px_new = max(0.0, min(self.extentX, px_new))
351
+ py_new = max(0.0, min(self.extentY, py_new))
352
+
353
+ # Update state (match what modpath_runner sets)
354
+ self.particleX = px_new
355
+ self.particleY = py_new
356
+ self.particleZ = self.particleZ # unchanged (single layer)
357
+ self.particleCoords = [px_new, py_new, self.particleZ]
358
+
359
+ # Update trajectories
360
+ self.trajectories['x'].append(np.array([px_new]))
361
+ self.trajectories['y'].append(np.array([py_new]))
362
+ self.trajectories['z'].append(np.array([self.particleZ]))
363
+
364
+ # Set outputs expected by the rest of the code
365
+ self.heads = h_3d
366
+ self.times = [1.0] # dummy (MF2005 reads from .hds)
367
+ self.success_modflow = True
368
+ self.buff = ''
369
+ self.t_simulate = time() - t_start
370
+
371
+ # Store for next step
372
+ self._direct_h_prev = h_new_int.copy()
373
+
374
+ def direct_reset(self):
375
+ """Reset solver state for new episode."""
376
+ self._direct_h_prev = None
377
+ self._direct_built = False
378
+ if hasattr(self, '_direct_lu'):
379
+ del self._direct_lu