flopyarcade 0.7.2__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 (93) hide show
  1. {flopyarcade-0.7.2/flopyarcade.egg-info → flopyarcade-0.7.4}/PKG-INFO +7 -4
  2. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/README.md +5 -2
  3. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/__init__.py +6 -2
  4. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/agent.py +62 -5
  5. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/arcade.py +9 -3
  6. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/benchmark.py +21 -1
  7. flopyarcade-0.7.4/flopyarcade/direct_solver.py +379 -0
  8. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/env_base.py +9 -0
  9. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_dqn.py +12 -1
  10. flopyarcade-0.7.4/flopyarcade/numba_solver.py +399 -0
  11. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/play.py +31 -0
  12. flopyarcade-0.7.4/flopyarcade/play_split.py +247 -0
  13. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/render.py +160 -13
  14. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/render3d.py +12 -6
  15. flopyarcade-0.7.4/flopyarcade/simulators/simulators_linux.zip +0 -0
  16. flopyarcade-0.7.4/flopyarcade/simulators/simulators_mac.zip +0 -0
  17. flopyarcade-0.7.4/flopyarcade/simulators/simulators_win32.zip +0 -0
  18. flopyarcade-0.7.4/flopyarcade/simulators/simulators_win64.zip +0 -0
  19. flopyarcade-0.7.4/flopyarcade/tests/conftest.py +28 -0
  20. flopyarcade-0.7.4/flopyarcade/tests/test_agent_dqn.py +455 -0
  21. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_final_push.py +1 -0
  22. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_actions_obs.py +1 -1
  23. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_render.py +2 -2
  24. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_mock_rllib.py +11 -4
  25. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_reward_reset.py +12 -7
  26. flopyarcade-0.7.4/flopyarcade/tests/test_smooth_trajectory.py +161 -0
  27. flopyarcade-0.7.4/flopyarcade/tests/test_split_screen.py +225 -0
  28. {flopyarcade-0.7.2 → flopyarcade-0.7.4/flopyarcade.egg-info}/PKG-INFO +7 -4
  29. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade.egg-info/SOURCES.txt +10 -1
  30. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/pyproject.toml +2 -2
  31. flopyarcade-0.7.2/flopyarcade/tests/conftest.py +0 -18
  32. flopyarcade-0.7.2/flopyarcade/tests/test_agent_dqn.py +0 -187
  33. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/LICENSE +0 -0
  34. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/MANIFEST.in +0 -0
  35. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/actions.py +0 -0
  36. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/archive_hdf5.py +0 -0
  37. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/env_config.py +0 -0
  38. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/__init__.py +0 -0
  39. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/1s-d/1s-d +0 -0
  40. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/1s-d/1s-d.tune_metadata +0 -0
  41. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/2s-d/2s-d +0 -0
  42. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/2s-d/2s-d.tune_metadata +0 -0
  43. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/3s-d/3s-d +0 -0
  44. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/policymodels/3s-d/3s-d.tune_metadata +0 -0
  45. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_neuroevolution.py +0 -0
  46. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_apexdqn.py +0 -0
  47. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_appo.py +0 -0
  48. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_impala.py +0 -0
  49. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/examples/train_rllib_ppo.py +0 -0
  50. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/flopyarcade.py +0 -0
  51. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/mf6_mp7_runner.py +0 -0
  52. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/mf6_prt_runner.py +0 -0
  53. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/modflow_runner.py +0 -0
  54. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/modpath_runner.py +0 -0
  55. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/observations.py +0 -0
  56. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/play3d.py +0 -0
  57. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/play_againstai.py +0 -0
  58. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/reward.py +0 -0
  59. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_a10_overlap.py +0 -0
  60. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_agent_neuroevolution.py +0 -0
  61. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_archive_hdf5.py +0 -0
  62. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_blit.py +0 -0
  63. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_c2_novelty_length.py +0 -0
  64. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_c7_action_space.py +0 -0
  65. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_agent2.py +0 -0
  66. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_agent_bench.py +0 -0
  67. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_big.py +0 -0
  68. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_envbase.py +0 -0
  69. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_final_push2.py +0 -0
  70. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_modflow_deep.py +0 -0
  71. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_archive.py +0 -0
  72. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_play_rl.py +0 -0
  73. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_push2.py +0 -0
  74. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_cov_runners_actions.py +0 -0
  75. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_90.py +0 -0
  76. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_deep.py +0 -0
  77. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_final.py +0 -0
  78. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_gaps.py +0 -0
  79. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_gaps2.py +0 -0
  80. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_max.py +0 -0
  81. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_coverage_push.py +0 -0
  82. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_fps.py +0 -0
  83. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_mf6_runners.py +0 -0
  84. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_play.py +0 -0
  85. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_regression.py +0 -0
  86. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_regression_ci.py +0 -0
  87. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_render3d.py +0 -0
  88. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade/tests/test_rllib_cpu.py +0 -0
  89. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade.egg-info/dependency_links.txt +0 -0
  90. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade.egg-info/entry_points.txt +0 -0
  91. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade.egg-info/requires.txt +0 -0
  92. {flopyarcade-0.7.2 → flopyarcade-0.7.4}/flopyarcade.egg-info/top_level.txt +0 -0
  93. {flopyarcade-0.7.2 → 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.2
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
@@ -20,7 +20,7 @@ Classifier: Topic :: Scientific/Engineering
20
20
  Classifier: Topic :: Scientific/Engineering :: Hydrology
21
21
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
22
  Classifier: Topic :: Education
23
- Requires-Python: <3.13,>=3.7
23
+ Requires-Python: <3.13,>=3.10
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: flopy>=3.9.2
@@ -195,7 +195,7 @@ flopyarcade/ # CORE — Gymnasium environments
195
195
  ### Install
196
196
 
197
197
  ```bash
198
- # Python 3.9–3.12
198
+ # Python >= 3.10 (numpy 2.x requirement)
199
199
  # Environments only (lightweight, ~200 MB):
200
200
  python -m pip install flopyarcade
201
201
 
@@ -220,10 +220,13 @@ from numpy.random import choice
220
220
 
221
221
  env = FloPyEnv(ENVTYPE='3s-d')
222
222
  reward_total = 0.0
223
+
223
224
  while not env.done:
224
225
  action = choice(env.actionSpace)
225
- obs, reward, done, info = env.step(action)
226
+ obs, reward, *rest = env.step(action)
226
227
  reward_total += reward
228
+ env.render()
229
+
227
230
  print(f"Episode reward: {reward_total:.1f}")
228
231
  env.close()
229
232
  ```
@@ -139,7 +139,7 @@ flopyarcade/ # CORE — Gymnasium environments
139
139
  ### Install
140
140
 
141
141
  ```bash
142
- # Python 3.9–3.12
142
+ # Python >= 3.10 (numpy 2.x requirement)
143
143
  # Environments only (lightweight, ~200 MB):
144
144
  python -m pip install flopyarcade
145
145
 
@@ -164,10 +164,13 @@ from numpy.random import choice
164
164
 
165
165
  env = FloPyEnv(ENVTYPE='3s-d')
166
166
  reward_total = 0.0
167
+
167
168
  while not env.done:
168
169
  action = choice(env.actionSpace)
169
- obs, reward, done, info = env.step(action)
170
+ obs, reward, *rest = env.step(action)
170
171
  reward_total += reward
172
+ env.render()
173
+
171
174
  print(f"Episode reward: {reward_total:.1f}")
172
175
  env.close()
173
176
  ```
@@ -4,7 +4,7 @@ FloPyArcade.
4
4
  Simulated groundwater flow environments to test reinforcement learning algorithms.
5
5
  """
6
6
 
7
- __version__ = '0.7.0'
7
+ __version__ = '0.7.3'
8
8
  __author__ = 'Philipp Hoehn'
9
9
 
10
10
 
@@ -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:
@@ -256,6 +256,55 @@ class FloPyAgent:
256
256
  self.replayMemory = deque(maxlen=self.hyParams['REPLAYMEMORYSIZE'])
257
257
  self.epsilon = self.hyParams['EPSILONINITIAL']
258
258
  self.targetUpdateCount = 0
259
+ self.dqnGameCounter = 0
260
+
261
+ def save_dqn_checkpoint(self, checkpoint_dir=None):
262
+ """Save DQN training state to a checkpoint directory."""
263
+ if checkpoint_dir is None:
264
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
265
+ checkpoint_dir = join(self.wrkspc, 'dqn_checkpoint', timestamp)
266
+ self._create_folder(checkpoint_dir)
267
+
268
+ self.mainModel.save_weights(join(checkpoint_dir, 'mainModel.weights.h5'))
269
+
270
+ if hasattr(self, 'targetModel') and self.targetModel is not None:
271
+ self.targetModel.save_weights(join(checkpoint_dir, 'targetModel.weights.h5'))
272
+
273
+ self.pickleDump(join(checkpoint_dir, 'replayMemory.p'), list(self.replayMemory))
274
+
275
+ state = {
276
+ 'epsilon': self.epsilon,
277
+ 'gameCounter': self.dqnGameCounter,
278
+ 'targetUpdateCount': self.targetUpdateCount,
279
+ }
280
+ self.pickleDump(join(checkpoint_dir, 'state.p'), state)
281
+
282
+ print(f'DQN checkpoint saved to {checkpoint_dir}')
283
+ return checkpoint_dir
284
+
285
+ def load_dqn_checkpoint(self, checkpoint_dir):
286
+ """Load DQN training state from a checkpoint directory."""
287
+ if not exists(checkpoint_dir):
288
+ raise FileNotFoundError(f'Checkpoint directory not found: {checkpoint_dir}')
289
+
290
+ self.mainModel.load_weights(join(checkpoint_dir, 'mainModel.weights.h5'))
291
+
292
+ target_weights_path = join(checkpoint_dir, 'targetModel.weights.h5')
293
+ if exists(target_weights_path):
294
+ self.targetModel.load_weights(target_weights_path)
295
+ else:
296
+ self.targetModel.set_weights(self.mainModel.get_weights())
297
+
298
+ replay_list = self.pickleLoad(join(checkpoint_dir, 'replayMemory.p'))
299
+ self.replayMemory = deque(maxlen=self.hyParams['REPLAYMEMORYSIZE'])
300
+ self.replayMemory.extend(replay_list)
301
+
302
+ state = self.pickleLoad(join(checkpoint_dir, 'state.p'))
303
+ self.epsilon = state['epsilon']
304
+ self.dqnGameCounter = state['gameCounter']
305
+ self.targetUpdateCount = state['targetUpdateCount']
306
+
307
+ print(f'DQN checkpoint loaded from {checkpoint_dir}')
259
308
 
260
309
  def initializeGeneticAgents(self):
261
310
  if self.envSettings['KEEPMODELHISTORY']:
@@ -306,6 +355,12 @@ class FloPyAgent:
306
355
 
307
356
  self._decay_epsilon()
308
357
 
358
+ # periodic checkpointing
359
+ self.dqnGameCounter += 1
360
+ checkpoint_every = self.hyParams.get('CHECKPOINTEVERY', 0)
361
+ if checkpoint_every > 0 and self.dqnGameCounter % checkpoint_every == 0:
362
+ self.save_dqn_checkpoint()
363
+
309
364
  def runGenetic(self, env, searchNovelty=False):
310
365
  """Run main pipeline for genetic agent optimization."""
311
366
  self._validate_hyperparams()
@@ -899,11 +954,12 @@ class FloPyAgent:
899
954
  current_qs_list = self.mainModel.predict(current_states)
900
955
 
901
956
  # retrieving future states from minibatch
902
- # then querying NN model for Q values
903
- # when using target network, query it, otherwise main network should be
904
- # queried
957
+ # then querying target network for Q values (evaluation)
958
+ # and online network for best action selection (Double-DQN)
905
959
  new_current_states = array([transition[3] for transition in minibatch])
906
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)
907
963
 
908
964
  X, y = [], []
909
965
  # enumerating batches
@@ -912,9 +968,10 @@ class FloPyAgent:
912
968
 
913
969
  # If not a terminal state, get new q from future states,
914
970
  # otherwise set it to 0
915
- # almost like with Q Learning, but we use just part of equation
971
+ # Double-DQN: argmax from online network, Q-value from target network
916
972
  if not done:
917
- 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]
918
975
  new_q = reward + self.hyParams['DISCOUNT'] * max_future_q
919
976
  else:
920
977
  new_q = reward
@@ -156,7 +156,8 @@ class FloPyArcade:
156
156
  PATHMP6=None, surrogateSimulator=None, flagSavePlot=False,
157
157
  flagManualControl=False, actions=None, flagRender=False,
158
158
  keepTimeSeries=False, ENVTYPE='1s-d', nLay=1, nRow=100,
159
- nCol=100, OBSPREP='perceptron', flagBlit=True):
159
+ nCol=100, OBSPREP='perceptron', flagBlit=True,
160
+ smoothFrames=4, smoothSubdiv=10):
160
161
  """Constructor.
161
162
 
162
163
  Args:
@@ -185,14 +186,15 @@ class FloPyArcade:
185
186
  agent, modelNameLoad, modelName, animationFolder, NAGENTSTEPS,
186
187
  PATHMF2005, PATHMP6, surrogateSimulator, flagSavePlot,
187
188
  flagManualControl, actions, flagRender, keepTimeSeries,
188
- ENVTYPE, nLay, nRow, nCol, OBSPREP, flagBlit
189
+ ENVTYPE, nLay, nRow, nCol, OBSPREP, flagBlit,
190
+ smoothFrames, smoothSubdiv
189
191
  )
190
192
 
191
193
  def _init_config(self, agent, modelNameLoad, modelName, animationFolder,
192
194
  NAGENTSTEPS, PATHMF2005, PATHMP6, surrogateSimulator,
193
195
  flagSavePlot, flagManualControl, actions, flagRender,
194
196
  keepTimeSeries, ENVTYPE, nLay, nRow, nCol, OBSPREP,
195
- flagBlit=True):
197
+ flagBlit=True, smoothFrames=4, smoothSubdiv=10):
196
198
  """Initialize configuration for FloPyArcade.
197
199
 
198
200
  Args:
@@ -209,6 +211,8 @@ class FloPyArcade:
209
211
  self.MANUALCONTROL = flagManualControl
210
212
  self.RENDER = flagRender
211
213
  self.BLIT = flagBlit
214
+ self.SMOOTH_FRAMES = smoothFrames
215
+ self.SMOOTH_SUBDIV = smoothSubdiv
212
216
  self.MODELNAME = modelName or modelNameLoad or "untitled"
213
217
  self.ANIMATIONFOLDER = (
214
218
  animationFolder or modelName or modelNameLoad or "untitled"
@@ -276,6 +280,8 @@ class FloPyArcade:
276
280
  nCol=self.nCol, OBSPREP=self.OBSPREP, initWithSolution=True
277
281
  )
278
282
  self.env._blit_enabled = self.BLIT
283
+ self.env.SMOOTH_TRAJ_FRAMES = self.SMOOTH_FRAMES
284
+ self.env.SMOOTH_TRAJ_SUBDIV = self.SMOOTH_SUBDIV
279
285
  else:
280
286
  self.env = FloPyEnvSurrogate(
281
287
  self.SURROGATESIMULATOR, ENVTYPE, MODELNAME=self.MODELNAME,
@@ -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
@@ -277,6 +277,9 @@ class EnvBaseMixin:
277
277
  self._blit_enabled = False
278
278
  self._blit_artists = {}
279
279
  self._fps = 0.0
280
+ self.SMOOTH_TRAJ_FRAMES = 4
281
+ self.SMOOTH_TRAJ_SUBDIV = 10
282
+ self._prevParticleCoords = None
280
283
  from collections import deque as _deque
281
284
  self._frame_times = _deque(maxlen=60)
282
285
  self.renderFlag = self.RENDER
@@ -1913,6 +1916,12 @@ class EnvBaseMixin:
1913
1916
  self.render_blit_frame()
1914
1917
  else:
1915
1918
  self.fig.canvas.draw()
1919
+ # B1: smooth particle transition between steps
1920
+ if getattr(self, 'SMOOTH_TRAJ_FRAMES', 1) > 1:
1921
+ self.render_particle_transition(
1922
+ n_frames=self.SMOOTH_TRAJ_FRAMES,
1923
+ pause_sec=0.03
1924
+ )
1916
1925
  self.renderFPS()
1917
1926
  show(block=False)
1918
1927
  pause(self.MANUALCONTROLTIME)