zoomy-jax 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. zoomy_jax-0.1.0/PKG-INFO +53 -0
  2. zoomy_jax-0.1.0/README.md +18 -0
  3. zoomy_jax-0.1.0/pyproject.toml +78 -0
  4. zoomy_jax-0.1.0/setup.cfg +4 -0
  5. zoomy_jax-0.1.0/tests/test_chorin_algebraic_aux_jax.py +100 -0
  6. zoomy_jax-0.1.0/tests/test_dt_max_wave_free_jax_req190.py +124 -0
  7. zoomy_jax-0.1.0/tests/test_elliptic_bc_jax_req174.py +142 -0
  8. zoomy_jax-0.1.0/tests/test_stage_list_jax_req173.py +111 -0
  9. zoomy_jax-0.1.0/tests/test_swe_2d_jax.py +110 -0
  10. zoomy_jax-0.1.0/tests/test_swe_dambreak_jax.py +314 -0
  11. zoomy_jax-0.1.0/tests/test_time_position_operators_jax_req185.py +218 -0
  12. zoomy_jax-0.1.0/tests/test_uniform_rank_malpasset_req84.py +81 -0
  13. zoomy_jax-0.1.0/tests/test_userfunctions_jax.py +115 -0
  14. zoomy_jax-0.1.0/zoomy_jax/LICENSE +165 -0
  15. zoomy_jax-0.1.0/zoomy_jax/README.md +153 -0
  16. zoomy_jax-0.1.0/zoomy_jax/__init__.py +49 -0
  17. zoomy_jax-0.1.0/zoomy_jax/fvm/__init__.py +30 -0
  18. zoomy_jax-0.1.0/zoomy_jax/fvm/eigvals.py +427 -0
  19. zoomy_jax-0.1.0/zoomy_jax/fvm/flux.py +95 -0
  20. zoomy_jax-0.1.0/zoomy_jax/fvm/halo_exchange_jax.py +138 -0
  21. zoomy_jax-0.1.0/zoomy_jax/fvm/implicit_ad.py +157 -0
  22. zoomy_jax-0.1.0/zoomy_jax/fvm/jvp_jax.py +31 -0
  23. zoomy_jax-0.1.0/zoomy_jax/fvm/march_emitted.py +337 -0
  24. zoomy_jax-0.1.0/zoomy_jax/fvm/nonconservative_flux.py +235 -0
  25. zoomy_jax-0.1.0/zoomy_jax/fvm/observers.py +95 -0
  26. zoomy_jax-0.1.0/zoomy_jax/fvm/ode.py +65 -0
  27. zoomy_jax-0.1.0/zoomy_jax/fvm/precice_solver.py +1287 -0
  28. zoomy_jax-0.1.0/zoomy_jax/fvm/reconstruction_jax.py +1766 -0
  29. zoomy_jax-0.1.0/zoomy_jax/fvm/solver2/__init__.py +72 -0
  30. zoomy_jax-0.1.0/zoomy_jax/fvm/solver2/blocks.py +367 -0
  31. zoomy_jax-0.1.0/zoomy_jax/fvm/solver2/context.py +215 -0
  32. zoomy_jax-0.1.0/zoomy_jax/fvm/solver2/march.py +281 -0
  33. zoomy_jax-0.1.0/zoomy_jax/fvm/solver2/state.py +49 -0
  34. zoomy_jax-0.1.0/zoomy_jax/fvm/solver_chorin_vam_jax.py +1115 -0
  35. zoomy_jax-0.1.0/zoomy_jax/fvm/solver_imex_jax.py +204 -0
  36. zoomy_jax-0.1.0/zoomy_jax/fvm/solver_jax.py +2384 -0
  37. zoomy_jax-0.1.0/zoomy_jax/fvm/spmd_jax.py +251 -0
  38. zoomy_jax-0.1.0/zoomy_jax/fvm/userfunctions.py +227 -0
  39. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/README.md +241 -0
  40. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/__init__.py +1 -0
  41. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/benchmark_gmres_guess.py +60 -0
  42. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/benchmark_poisson_iterations.py +250 -0
  43. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/benchmark_spectral_mesh_suite.py +200 -0
  44. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/cases_gn_topo.py +103 -0
  45. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/common.py +94 -0
  46. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/customize_from_collect.py +63 -0
  47. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/dataset_2d_mg_multibranch.py +129 -0
  48. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/dataset_deltaq.py +114 -0
  49. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/demo_fft_gnn_1d.py +30 -0
  50. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/demo_local_experts_transient.py +202 -0
  51. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/demo_local_gnn.py +244 -0
  52. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/demo_local_gnn_timeseries.py +149 -0
  53. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/eval_standalone_predictor.py +50 -0
  54. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/fourier_1d.py +45 -0
  55. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/global_coupling.py +55 -0
  56. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/graph_laplacian_spectral.py +110 -0
  57. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/graph_mp_multibranch.py +112 -0
  58. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/mesh_1d_poisson.py +46 -0
  59. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/mesh_2d_poisson.py +92 -0
  60. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/mesh_spectral_geometry.py +91 -0
  61. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/mg_structured_hierarchy.py +128 -0
  62. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/mg_structured_hierarchy_1d.py +104 -0
  63. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/models_deltaq.py +41 -0
  64. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/multigrid_gnn_toy.py +79 -0
  65. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/nonuniform_spectral.py +156 -0
  66. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/poisson_1d.py +20 -0
  67. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/predictor_learned_multilevel.py +216 -0
  68. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/run_2d_mg_quick_results.py +74 -0
  69. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/run_full_loop.sh +15 -0
  70. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/smooth_1d.py +21 -0
  71. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_2d_mg_benchmark.py +423 -0
  72. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_autosearch_deltaq.py +85 -0
  73. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_deltaq.py +264 -0
  74. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_hybrid_pressure_residual.py +193 -0
  75. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_multilevel_fft1d.py +268 -0
  76. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_poisson_arch_benchmark.py +424 -0
  77. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_residual_target_deltaq.py +141 -0
  78. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_spectral_mesh_suite.py +599 -0
  79. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_vcycle_structured_poisson.py +434 -0
  80. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/train_vcycle_structured_poisson_1d.py +508 -0
  81. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/vcycle_imex_bridge.py +232 -0
  82. zoomy_jax-0.1.0/zoomy_jax/gnn_blueprint/vcycle_structured_gnn.py +275 -0
  83. zoomy_jax-0.1.0/zoomy_jax/gpurank.py +52 -0
  84. zoomy_jax-0.1.0/zoomy_jax/mesh/__init__.py +24 -0
  85. zoomy_jax-0.1.0/zoomy_jax/mesh/mesh.py +356 -0
  86. zoomy_jax-0.1.0/zoomy_jax/mesh/partition.py +541 -0
  87. zoomy_jax-0.1.0/zoomy_jax/mesh/partition_jax.py +564 -0
  88. zoomy_jax-0.1.0/zoomy_jax/misc/__init__.py +1 -0
  89. zoomy_jax-0.1.0/zoomy_jax/misc/io.py +81 -0
  90. zoomy_jax-0.1.0/zoomy_jax/symsolver/__init__.py +10 -0
  91. zoomy_jax-0.1.0/zoomy_jax/symsolver/compile_cache.py +117 -0
  92. zoomy_jax-0.1.0/zoomy_jax/symsolver/coupling.py +40 -0
  93. zoomy_jax-0.1.0/zoomy_jax/symsolver/hypre.py +334 -0
  94. zoomy_jax-0.1.0/zoomy_jax/symsolver/parallel.py +211 -0
  95. zoomy_jax-0.1.0/zoomy_jax/symsolver/runtime.py +1630 -0
  96. zoomy_jax-0.1.0/zoomy_jax/symsolver/solver.py +516 -0
  97. zoomy_jax-0.1.0/zoomy_jax/template/__init__.py +7 -0
  98. zoomy_jax-0.1.0/zoomy_jax/template/backend.py +353 -0
  99. zoomy_jax-0.1.0/zoomy_jax/template/linalg.py +258 -0
  100. zoomy_jax-0.1.0/zoomy_jax/transformation/__init__.py +0 -0
  101. zoomy_jax-0.1.0/zoomy_jax/transformation/jax_runtime.py +1158 -0
  102. zoomy_jax-0.1.0/zoomy_jax/transformation/to_jax.py +73 -0
  103. zoomy_jax-0.1.0/zoomy_jax.egg-info/PKG-INFO +53 -0
  104. zoomy_jax-0.1.0/zoomy_jax.egg-info/SOURCES.txt +105 -0
  105. zoomy_jax-0.1.0/zoomy_jax.egg-info/dependency_links.txt +1 -0
  106. zoomy_jax-0.1.0/zoomy_jax.egg-info/requires.txt +16 -0
  107. zoomy_jax-0.1.0/zoomy_jax.egg-info/top_level.txt +1 -0
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: zoomy-jax
3
+ Version: 0.1.0
4
+ Summary: JAX solver backend for the Zoomy simulation framework.
5
+ Author-email: Ingo Steldermann <steldermann@mbd.rwth-aachen.de>
6
+ License: LGPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/ZoomyLab/Zoomy
8
+ Project-URL: Documentation, https://zoomylab.github.io/Zoomy
9
+ Project-URL: Source, https://github.com/ZoomyLab/Zoomy
10
+ Project-URL: Issues, https://github.com/ZoomyLab/Zoomy/issues
11
+ Keywords: jax,simulation,zoomy,shallow flow,physics,autodiff
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Topic :: Scientific/Engineering :: Physics
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: jax>=0.7.0
23
+ Requires-Dist: h5py
24
+ Requires-Dist: equinox>=0.13
25
+ Requires-Dist: attrs
26
+ Requires-Dist: zoomy-core>=0.2.17
27
+ Provides-Extra: cuda
28
+ Requires-Dist: jax[cuda12]>=0.7.0; extra == "cuda"
29
+ Provides-Extra: server
30
+ Requires-Dist: zoomy-server; extra == "server"
31
+ Provides-Extra: gnn
32
+ Requires-Dist: equinox>=0.13; extra == "gnn"
33
+ Requires-Dist: optax; extra == "gnn"
34
+ Requires-Dist: jraph; extra == "gnn"
35
+
36
+ # zoomy-jax
37
+
38
+ JAX solver backend for [Zoomy](https://github.com/ZoomyLab/Zoomy), a simulation
39
+ software for dimensionally-reduced free surface flows. It runs the models derived
40
+ in [`zoomy-core`](https://pypi.org/project/zoomy-core/) on CPU, GPU and multiple
41
+ devices (finite volume, adaptive time stepping, automatic differentiation).
42
+
43
+ ```bash
44
+ pip install zoomy-jax # CPU
45
+ pip install "zoomy-jax[cuda]" # NVIDIA GPU (CUDA 12)
46
+ ```
47
+
48
+ Documentation: <https://zoomylab.github.io/Zoomy>
49
+
50
+ Optional extras: `ad` (reverse-mode AD through the time loop), `gnn` (learned
51
+ multigrid experiments), `server`.
52
+
53
+ License: LGPL-3.0-or-later.
@@ -0,0 +1,18 @@
1
+ # zoomy-jax
2
+
3
+ JAX solver backend for [Zoomy](https://github.com/ZoomyLab/Zoomy), a simulation
4
+ software for dimensionally-reduced free surface flows. It runs the models derived
5
+ in [`zoomy-core`](https://pypi.org/project/zoomy-core/) on CPU, GPU and multiple
6
+ devices (finite volume, adaptive time stepping, automatic differentiation).
7
+
8
+ ```bash
9
+ pip install zoomy-jax # CPU
10
+ pip install "zoomy-jax[cuda]" # NVIDIA GPU (CUDA 12)
11
+ ```
12
+
13
+ Documentation: <https://zoomylab.github.io/Zoomy>
14
+
15
+ Optional extras: `ad` (reverse-mode AD through the time loop), `gnn` (learned
16
+ multigrid experiments), `server`.
17
+
18
+ License: LGPL-3.0-or-later.
@@ -0,0 +1,78 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+
6
+ [project]
7
+ name = "zoomy-jax"
8
+ version = "0.1.0"
9
+ description = "JAX solver backend for the Zoomy simulation framework."
10
+ readme = "README.md"
11
+ requires-python = ">=3.11"
12
+ license = { text = "LGPL-3.0-or-later" }
13
+ authors = [
14
+ { name = "Ingo Steldermann", email = "steldermann@mbd.rwth-aachen.de" }
15
+ ]
16
+ keywords = ["jax", "simulation", "zoomy", "shallow flow", "physics", "autodiff"]
17
+
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Science/Research",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
25
+ "Operating System :: OS Independent",
26
+ "Topic :: Scientific/Engineering :: Physics",
27
+ ]
28
+
29
+
30
+ dependencies = [
31
+ # JAX ecosystem (CPU build; the GPU build is the optional extra `cuda`)
32
+ "jax>=0.7.0",
33
+ "h5py", # HDF5 output / mesh input (fvm/solver_jax.py, misc/io.py)
34
+ "equinox>=0.13", # reverse-mode AD: checkpointed time loop (ad_mode=AdMode.reverse)
35
+ "attrs", # fvm/precice_solver.py
36
+
37
+ # the pure-Python core: models, symbolic derivation, mesh, NumPy solvers
38
+ "zoomy-core>=0.2.17",
39
+ ]
40
+
41
+ [project.optional-dependencies]
42
+ # Example: pip install "zoomy-jax[cuda]"
43
+ cuda = ["jax[cuda12]>=0.7.0"]
44
+ server = ["zoomy-server"]
45
+ # Learned multigrid / GNN preconditioner experiments (zoomy_jax.gnn_blueprint).
46
+ gnn = ["equinox>=0.13", "optax", "jraph"]
47
+
48
+ [project.urls]
49
+ Homepage = "https://github.com/ZoomyLab/Zoomy"
50
+ Documentation = "https://zoomylab.github.io/Zoomy"
51
+ Source = "https://github.com/ZoomyLab/Zoomy"
52
+ Issues = "https://github.com/ZoomyLab/Zoomy/issues"
53
+
54
+
55
+ [tool.setuptools.packages.find]
56
+ include = ["zoomy_jax*"]
57
+
58
+ [tool.setuptools.package-data]
59
+ zoomy_jax = ["LICENSE", "README.md"]
60
+ "zoomy_jax.gnn_blueprint" = ["*.sh", "README.md"]
61
+
62
+ # Standalone runs (rootdir = zoomy_jax, where the superrepo pytest.ini and
63
+ # root conftest are invisible). Marker names follow the SUPERREPO
64
+ # conventions (small/medium/large/regression + the jax stack tag) — never
65
+ # zoomy_core's pyproject-local gate/rederive/area names, which superrepo-root
66
+ # runs cannot see. Under the superrepo, its pytest.ini owns configuration
67
+ # and auto-marks these tests jax + small; the explicit in-file markers keep
68
+ # standalone runs warning-free and addressable.
69
+ [tool.pytest.ini_options]
70
+ testpaths = ["tests"]
71
+ addopts = "--import-mode=importlib"
72
+ markers = [
73
+ "small: fast default-tier test (superrepo convention)",
74
+ "medium: mid-cost test (superrepo convention)",
75
+ "large: real time-march / simulation test; deselected by default, enable with --run-large (>5 min individually is large)",
76
+ "regression: end-state march asserted against blessed baselines in tests/goldens",
77
+ "jax: requires the jax stack (auto-applied by the superrepo conftest)",
78
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,100 @@
1
+ """REQ-151 DEFECT D (jax half): the Chorin solver must EVALUATE a plain-Symbol
2
+ aux rule, not only derivative-kind aux.
3
+
4
+ `hinv = KP(h)` is a plain `Symbol`, and every velocity scales by it
5
+ (`u = hu*hinv`). `_refresh_aux_for_sm` historically walked only
6
+ `kinds=("derivative","limited_derivative")`, so `hinv` was never evaluated: it
7
+ sat at its init value 0 and silently zeroed every velocity — a WRONG-ANSWER
8
+ bug, not a crash. This test pins the fix: in the predictor aux pool of the setup state,
9
+ `hinv` must equal `1/h` (to KP desingularisation), not 0.
10
+
11
+ ⚠ Requires the CORE half too: `_pad_to_square`
12
+ (`zoomy_core/fvm/solver_chorin_vam_numpy.py`) must carry `update_aux_variables`
13
+ onto the padded predictor SystemModel, else the predictor runtime never
14
+ lowers the rule and there is nothing for this solver to apply. While that is
15
+ outstanding the test SKIPS with a pointer rather than reporting a false pass —
16
+ it flips to a real assertion the moment core lands it.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ os.environ.setdefault("JAX_PLATFORMS", "cpu")
22
+
23
+ import numpy as np
24
+ import pytest
25
+
26
+ pytest.importorskip("jax")
27
+ import sympy as sp
28
+ from loguru import logger
29
+ logger.remove()
30
+
31
+ import zoomy_core.model.initial_conditions as IC
32
+ from zoomy_core.mesh import LSQMesh
33
+ from zoomy_core.systemmodel import SystemModel
34
+ from zoomy_core.systemmodel.operations import desingularize_hinv
35
+ from zoomy_core.model.boundary_conditions import BoundaryConditions, Wall, Dirichlet
36
+ from zoomy_core.model.models import VAM
37
+ from zoomy_core.model.models.closures import Newtonian, StressFree
38
+ from zoomy_jax.fvm.solver_chorin_vam_jax import ChorinSplitVAMSolverJax
39
+
40
+
41
+ def _build():
42
+ """2-D VAM(1,3) that ACTUALLY emits `hinv` (a plain VAM does not)."""
43
+ m = VAM(level=1, dimension=3, closures=[Newtonian(), StressFree()])
44
+ sm = SystemModel.from_model(m)
45
+ sm.apply(desingularize_hinv()) # registers the `hinv` aux
46
+ names = [str(s) for s in sm.state]
47
+ aux = [str(a) for a in sm.aux_state]
48
+ assert "hinv" in aux, "fixture no longer emits hinv — test would be vacuous"
49
+ ih, ihinv = names.index("h"), aux.index("hinv")
50
+ # Wall(tag) claims EVERY field and would conflict with the P pin -> on=momentum
51
+ sm.attach_boundary_conditions(BoundaryConditions([
52
+ Wall("left", on="momentum"), Wall("right", on="momentum"),
53
+ Wall("bottom", on="momentum"), Wall("top", on="momentum"),
54
+ # ⚠ These pins are NOT a rank fix — that comment was my misconception.
55
+ # REQ-172 v3 measured the elliptic operator FULL-RANK with no pin at
56
+ # all (sigma_min ~3e-5 and RISING under refinement; LU solves to 1e-14).
57
+ # They're here only to fix P's otherwise-arbitrary additive constant.
58
+ # Pre-REQ-174 they were silently ignored anyway (hardcoded Neumann);
59
+ # they are now genuinely consumed — see test_elliptic_bc_jax_req174.py.
60
+ Dirichlet("top", on="P_0", value=0.0),
61
+ Dirichlet("top", on="P_1", value=0.0),
62
+ ]))
63
+
64
+ def ic(xv):
65
+ o = np.zeros(len(names))
66
+ o[ih] = 0.12 if float(xv[0]) < 0.5 else 0.061
67
+ return o
68
+
69
+ sm.initial_conditions = IC.UserFunction(function=ic)
70
+ sm.aux_initial_conditions = IC.Constant(constants=lambda n: np.zeros(n))
71
+ split = m.chorin_split(sp.Symbol("dt", positive=True), system_model=sm)
72
+ mesh = LSQMesh.create_2d(domain=(0.0, 1.0, 0.0, 0.25), nx=16, ny=4)
73
+ solver = ChorinSplitVAMSolverJax(split.SM_pred, split.SM_press, split.SM_corr,
74
+ pressure_tol=1e-9, pressure_maxit=60)
75
+ Q0 = solver.setup_simulation(mesh)
76
+ return solver, Q0, ih, ihinv
77
+
78
+
79
+ @pytest.mark.jax
80
+ def test_chorin_recomputes_plain_symbol_aux_hinv():
81
+ solver, Q0, ih, ihinv = _build()
82
+
83
+ rt = solver._runtime_for_sm(solver.sm_pred)
84
+ if getattr(rt, "update_aux_variables", None) is None:
85
+ pytest.skip(
86
+ "core half outstanding (REQ-151 DEFECT D): _pad_to_square drops "
87
+ "update_aux_variables, so the predictor runtime never lowers the "
88
+ "rule. jax applies it as soon as core carries it across.")
89
+
90
+ nc = solver.nc
91
+ qaux = np.asarray(solver._qaux_from_q(Q0, solver.parameters))
92
+ h = np.asarray(Q0)[ih, :nc]
93
+ hinv = qaux[ihinv, :nc]
94
+
95
+ assert hinv.max() > 0, (
96
+ "DEFECT D: hinv still 0 — every velocity u=hu*hinv silently vanishes")
97
+ # KP-desingularised inverse depth == 1/h for these (well-wet) depths
98
+ assert np.allclose(hinv, 1.0 / h, rtol=1e-6), (
99
+ f"hinv != 1/h: got [{hinv.min():.6g},{hinv.max():.6g}], "
100
+ f"expected [{(1.0/h).min():.6g},{(1.0/h).max():.6g}]")
@@ -0,0 +1,124 @@
1
+ """REQ-190 (jax adoption): the NSM's ``dt_max`` reaches the jax solver's
2
+ ``compute_dt``, and a WAVE-FREE domain steps at ``dt_max`` (not ``inf``, not a
3
+ magic floor).
4
+
5
+ Core (zoomy_core@93e9e2e) added ``dt_max`` as a standard ``NumericalSystemModel``
6
+ parameter (default 5.0 s) and made the shared ``timestepping.adaptive`` fill its
7
+ cap from ``nsm.dt_max`` via ``apply_default_dt_max`` — a wave-free domain (every
8
+ gated ``|λ| = 0`` → local CFL limits ``+inf``) then collapses to ``dt_max``. The
9
+ jax solver shares that ``timestepping.adaptive``; this test covers the jax
10
+ CALL-SITE fill: ``HyperbolicSolver.setup_simulation`` now calls
11
+ ``timestepping.apply_default_dt_max(self.compute_dt, nsm.dt_max)``.
12
+
13
+ Uses a scalar advection model ``∂_t c + a·∂_x c = 0`` (``flux = a·c``,
14
+ ``eigenvalue = a``) — no ``h``, so a wave-free case (``a = 0``) has NO 0/0, and
15
+ the dt behaviour is isolated from wet/dry desingularization.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ os.environ.setdefault("JAX_PLATFORMS", "cpu")
21
+
22
+ import numpy as np
23
+ import pytest
24
+
25
+ pytest.importorskip("jax")
26
+
27
+ import sympy as sp
28
+
29
+ import zoomy_core.fvm.timestepping as timestepping
30
+ import zoomy_core.model.boundary_conditions as BC
31
+ import zoomy_core.model.initial_conditions as IC
32
+ from zoomy_core.mesh import LSQMesh
33
+ from zoomy_core.misc.misc import ZArray
34
+ from zoomy_core.model.derivative_workflow import StructuredDerivativeModel
35
+ from zoomy_core.numerics import NumericalSystemModel, ReconstructionSpec
36
+
37
+ from zoomy_jax.fvm.solver_jax import HyperbolicSolver
38
+
39
+ from loguru import logger
40
+ logger.remove()
41
+
42
+
43
+ class Advect(StructuredDerivativeModel):
44
+ """``∂_t c + a·∂_x c = 0`` — advection speed ``a`` is the only wave speed, so
45
+ ``a = 0`` gives a wave-free domain (``max|λ| = 0``)."""
46
+
47
+ dimension = 1
48
+ variables = ["c"]
49
+ parameters = {"a": (1.0, "real")}
50
+
51
+ def _build_function_groups(self):
52
+ return {}
53
+
54
+ def flux(self):
55
+ F = sp.Matrix.zeros(1, 1)
56
+ F[0, 0] = self.parameters.a * self.Q.c
57
+ return ZArray(F)
58
+
59
+ def eigenvalues(self):
60
+ return ZArray([self.parameters.a])
61
+
62
+
63
+ def _setup(a, dt_max, *, compute_dt=None, nc=20):
64
+ bcs = BC.BoundaryConditions([
65
+ BC.Periodic(tag="left", periodic_to_physical_tag="right"),
66
+ BC.Periodic(tag="right", periodic_to_physical_tag="left"),
67
+ ])
68
+ model = Advect(
69
+ parameters={"a": (a, "real")},
70
+ boundary_conditions=bcs,
71
+ initial_conditions=IC.UserFunction(function=lambda x: np.array([1.0])),
72
+ )
73
+ mesh = LSQMesh.create_1d(domain=(0.0, 1.0), n_inner_cells=nc)
74
+ kw = {} if dt_max is None else {"dt_max": dt_max}
75
+ nsm = NumericalSystemModel.from_system_model(
76
+ model, reconstruction=ReconstructionSpec(order=1), **kw)
77
+ solver = HyperbolicSolver(
78
+ time_end=1.0,
79
+ **({"compute_dt": compute_dt} if compute_dt is not None
80
+ else {"compute_dt": timestepping.adaptive(CFL=0.9, dimension=1)}))
81
+ Q, Qaux = solver.setup_simulation(mesh, nsm)
82
+ return solver, Q, Qaux
83
+
84
+
85
+ @pytest.mark.jax
86
+ def test_wave_free_steps_at_dt_max_jax():
87
+ """``a = 0`` → every ``|λ| = 0`` → wave-free → dt is exactly ``dt_max``
88
+ (not ``inf``, not a floor). Proves the NSM ``dt_max`` reaches jax's
89
+ ``compute_dt`` AND the wave-free branch collapses to it."""
90
+ DTMAX = 0.5
91
+ solver, Q, Qaux = _setup(a=0.0, dt_max=DTMAX)
92
+ dt = float(solver.compute_timestep(Q, Qaux))
93
+ assert np.isfinite(dt), "wave-free dt is inf — dt_max not wired into jax compute_dt"
94
+ assert dt == pytest.approx(DTMAX), (
95
+ f"wave-free dt {dt} != dt_max {DTMAX} — the NSM dt_max did not reach "
96
+ "the jax solver's compute_dt (apply_default_dt_max not called at setup)")
97
+
98
+
99
+ @pytest.mark.jax
100
+ def test_nsm_dt_max_clamps_wet_dt_jax():
101
+ """A wet (``a = 2``) case has a finite CFL dt; a tiny NSM ``dt_max`` below it
102
+ clamps the step to ``dt_max`` — the direct proof that ``nsm.dt_max`` is wired
103
+ into the jax ``compute_dt``. With the default 5.0 s cap the same case is
104
+ unaffected (dt well below 5)."""
105
+ solver_big, Qb, Qab = _setup(a=2.0, dt_max=5.0)
106
+ dt_big = float(solver_big.compute_timestep(Qb, Qab))
107
+ assert np.isfinite(dt_big) and dt_big < 5.0, "wet CFL dt should be < dt_max=5"
108
+
109
+ TINY = 1e-4
110
+ solver_tiny, Qt, Qat = _setup(a=2.0, dt_max=TINY)
111
+ dt_tiny = float(solver_tiny.compute_timestep(Qt, Qat))
112
+ assert dt_tiny == pytest.approx(TINY), (
113
+ f"dt {dt_tiny} != tiny dt_max {TINY} — nsm.dt_max not wired into jax compute_dt")
114
+
115
+
116
+ @pytest.mark.jax
117
+ def test_explicit_dt_max_wins_over_nsm_jax():
118
+ """An explicit ``adaptive(dt_max=...)`` from the caller is never overwritten
119
+ by the NSM default at setup — explicit wins (mirrors the numpy contract)."""
120
+ explicit = timestepping.adaptive(CFL=0.9, dimension=1, dt_max=0.1)
121
+ solver, Q, Qaux = _setup(a=0.0, dt_max=5.0, compute_dt=explicit)
122
+ dt = float(solver.compute_timestep(Q, Qaux))
123
+ assert dt == pytest.approx(0.1), (
124
+ f"dt {dt} != explicit 0.1 — NSM dt_max wrongly overrode the caller's cap")
@@ -0,0 +1,142 @@
1
+ """REQ-174 (jax half): the elliptic stage must CONSUME ``SM_press``'s declared
2
+ P boundary conditions.
3
+
4
+ The defect core fixed in `6ac880a` and this mirrors: the pressure solve
5
+ hardcoded homogeneous Neumann at every boundary face and never read
6
+ ``SM_press.boundary_conditions``, so a user-declared Dirichlet P pin was
7
+ silently replaced by ``zeroGradient`` — **a well-posed solve of the WRONG
8
+ problem**. Not a singularity: the operator is full-rank without any pin
9
+ (measured, REQ-172 v3), which is why nothing ever crashed and the bug was
10
+ invisible.
11
+
12
+ ⚠ THE JAX-SPECIFIC HAZARD core's equivalent test cannot catch — the two
13
+ backends' boundary arguments mean DIFFERENT THINGS:
14
+
15
+ * numpy ``compute_derivatives(..., u_boundary_face=<FACE values>)`` converts
16
+ internally — ``_resolve_u_boundary_face``: ``ghost = 2·u_face − u_cell``.
17
+ * jax ``lsq_gradient_per_field(..., u_bf=<GHOST values>)`` uses the value
18
+ DIRECTLY (``u_bf_delta = u_bf_i − u_i``). **No conversion.**
19
+
20
+ So the ``2·u_face − u_cell`` lift is the jax caller's job. Passing the bare face
21
+ value puts a face-valued sample at the ghost position and silently caps the
22
+ boundary gradient at 1st order — it does not raise, it just quietly degrades
23
+ (see ``tests/unit/zoomy_jax/test_mesh_derivatives_recent.py``, 4.16 vs 0.024).
24
+ ``test_pin_is_exact_not_merely_close`` is what actually pins this: a bare-face
25
+ bug still moves P toward the pin, so only an exact-to-round-off check separates
26
+ "honoured" from "approximately nudged".
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ os.environ.setdefault("JAX_PLATFORMS", "cpu")
32
+
33
+ import numpy as np
34
+ import pytest
35
+
36
+ pytest.importorskip("jax")
37
+ import sympy as sp
38
+ from loguru import logger
39
+ logger.remove()
40
+
41
+ import zoomy_core.model.initial_conditions as IC
42
+ from zoomy_core.mesh import LSQMesh
43
+ from zoomy_core.systemmodel import SystemModel
44
+ from zoomy_core.systemmodel.operations import desingularize_hinv
45
+ from zoomy_core.model.boundary_conditions import BoundaryConditions, Wall, Dirichlet
46
+ from zoomy_core.model.models import VAM
47
+ from zoomy_core.model.models.closures import Newtonian, StressFree
48
+ from zoomy_jax.fvm.solver_chorin_vam_jax import ChorinSplitVAMSolverJax
49
+
50
+ PIN_P0 = 0.037
51
+ PIN_P1 = 0.0
52
+
53
+
54
+ def _build(with_pin):
55
+ m = VAM(level=1, dimension=3, closures=[Newtonian(), StressFree()])
56
+ sm = SystemModel.from_model(m)
57
+ sm.apply(desingularize_hinv())
58
+ names = [str(s) for s in sm.state]
59
+ ih, iq = names.index("h"), names.index("q_x_0")
60
+ bcs = [Wall("left", on="momentum"), Wall("right", on="momentum"),
61
+ Wall("bottom", on="momentum"), Wall("top", on="momentum")]
62
+ if with_pin:
63
+ bcs += [Dirichlet("right", on="P_0", value=PIN_P0),
64
+ Dirichlet("right", on="P_1", value=PIN_P1)]
65
+ sm.attach_boundary_conditions(BoundaryConditions(bcs))
66
+
67
+ def ic(xv):
68
+ o = np.zeros(len(names))
69
+ x = float(xv[0])
70
+ o[ih] = 0.10 + 0.02 * np.cos(np.pi * x)
71
+ o[iq] = 0.05 * np.sin(2 * np.pi * x)
72
+ return o
73
+
74
+ sm.initial_conditions = IC.UserFunction(function=ic)
75
+ sm.aux_initial_conditions = IC.Constant(constants=lambda n: np.zeros(n))
76
+ split = m.chorin_split(sp.Symbol("dt", positive=True), system_model=sm)
77
+ mesh = LSQMesh.create_2d(domain=(0.0, 1.0, 0.0, 0.25), nx=16, ny=4)
78
+ s = ChorinSplitVAMSolverJax(split.SM_pred, split.SM_press, split.SM_corr,
79
+ pressure_tol=1e-12, pressure_maxit=20000)
80
+ s.Q0 = s.setup_simulation(mesh)
81
+ return s
82
+
83
+
84
+ def _solve(s, dt=1e-3):
85
+ p = s._sub_parameters(s._press_param_src, s.parameters, dt)
86
+ Qaux = s._refresh_aux_for_sm(s._qaux_press0, s.sm_press, s.Q0, p)
87
+ Q_new = s._step_pressure_pure(s.Q0, Qaux, dt, 0.0, p)
88
+ return np.array(Q_new[s._press_state_idx, :], dtype=float)
89
+
90
+
91
+ # `setup_simulation` (symbolic lowering + jit) dominates at ~3 min a build, and
92
+ # every test wants one of only TWO solvers. Module-scoped, which is safe here
93
+ # because `_step_pressure_pure` is pure — it returns new arrays and mutates
94
+ # nothing on the solver. Naive per-test builds cost 5 lowerings / ~15 min.
95
+ @pytest.fixture(scope="module")
96
+ def solver_free():
97
+ return _build(with_pin=False)
98
+
99
+
100
+ @pytest.fixture(scope="module")
101
+ def solver_pinned():
102
+ return _build(with_pin=True)
103
+
104
+
105
+ @pytest.mark.jax
106
+ def test_no_declared_dirichlet_keeps_the_neumann_path(solver_free):
107
+ """core: "default Neumann unchanged". jax must mean it literally — the
108
+ no-BC case must take the *same* `u_bf=None` call as before REQ-174, not an
109
+ equivalent-looking ghost array, so the old path cannot drift."""
110
+ assert solver_free._press_dir is None
111
+ assert solver_free._press_dir_j is None
112
+
113
+
114
+ @pytest.mark.jax
115
+ def test_declared_dirichlet_is_seen_by_the_elliptic_stage(solver_pinned):
116
+ d = solver_pinned._press_dir
117
+ assert d is not None, "declared P Dirichlet never reached the elliptic stage"
118
+ # 16x4 grid, pin on "right" => 4 boundary faces, 4 cells, on BOTH modes.
119
+ assert list(np.asarray(d["face_mask"]).sum(axis=1)) == [4, 4]
120
+ assert list(np.asarray(d["cell_mask"]).sum(axis=1)) == [4, 4]
121
+
122
+
123
+ @pytest.mark.jax
124
+ def test_pin_is_exact_not_merely_close(solver_pinned):
125
+ """THE gate. A bare-face/ghost mix-up still drags P toward the pin, so
126
+ "close" proves nothing — only exactness separates a consumed BC from a
127
+ coincidentally-nearby one."""
128
+ P = _solve(solver_pinned)
129
+ cm = np.asarray(solver_pinned._press_dir["cell_mask"])
130
+ cv = np.asarray(solver_pinned._press_dir["cell_value"])
131
+ err = np.abs(P[cm] - cv[cm])
132
+ assert err.max() < 1e-12, f"pinned cells off by {err.max():.3e}"
133
+
134
+
135
+ @pytest.mark.jax
136
+ def test_pin_actually_changes_the_answer(solver_free, solver_pinned):
137
+ """Guards the test above from passing vacuously: if P were ~the pin value
138
+ at that boundary anyway, exactness would be meaningless."""
139
+ P_free = _solve(solver_free)
140
+ P_pin = _solve(solver_pinned)
141
+ assert np.abs(P_pin - P_free).max() > 1e-3, \
142
+ "the declared pin does not move the solution — gate is vacuous"
@@ -0,0 +1,111 @@
1
+ """REQ-173 (jax half): ``stages=[...]`` construction ≡ the positional triple.
2
+
3
+ core landed the vocabulary in `zoomy_core@5e32610` (`SplitForPressureResult.stages`,
4
+ `Stage(label, kind, sm)`, binding BY KIND). This is the jax mirror's gate: the
5
+ stage-list constructor must select the SAME three sub-models as the legacy
6
+ positional call — same objects, same roles — so the refactor is a renaming of
7
+ the dispatch and not a change of numerics.
8
+
9
+ ⚠ What this test canNOT catch, and core's equivalent can't either: a silently
10
+ unconverged `elliptic` stage. Both construction paths call the same pressure
11
+ primitive, so both reproduce each other bit-for-bit whether or not that solve
12
+ converged. Bit-for-bit proves the refactor is clean; it says nothing about
13
+ convergence. That is why the `elliptic` contract carries a residual (jax
14
+ surfaces it via `jax.debug.print` from inside jit — see `_step_pressure_pure`).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ os.environ.setdefault("JAX_PLATFORMS", "cpu")
20
+
21
+ import numpy as np
22
+ import pytest
23
+
24
+ pytest.importorskip("jax")
25
+ import sympy as sp
26
+ from loguru import logger
27
+ logger.remove()
28
+
29
+ import zoomy_core.model.initial_conditions as IC
30
+ from zoomy_core.mesh import LSQMesh
31
+ from zoomy_core.systemmodel import SystemModel
32
+ from zoomy_core.model.boundary_conditions import BoundaryConditions, Wall, Dirichlet
33
+ from zoomy_core.model.models import VAM
34
+ from zoomy_core.model.models.closures import Newtonian, StressFree
35
+ from zoomy_jax.fvm.solver_chorin_vam_jax import ChorinSplitVAMSolverJax
36
+
37
+
38
+ def _split():
39
+ m = VAM(level=1, dimension=3, closures=[Newtonian(), StressFree()])
40
+ sm = SystemModel.from_model(m)
41
+ names = [str(s) for s in sm.state]
42
+ ih = names.index("h")
43
+ sm.attach_boundary_conditions(BoundaryConditions([
44
+ Wall("left", on="momentum"), Wall("right", on="momentum"),
45
+ Wall("bottom", on="momentum"), Wall("top", on="momentum"),
46
+ Dirichlet("top", on="P_0", value=0.0),
47
+ Dirichlet("top", on="P_1", value=0.0),
48
+ ]))
49
+
50
+ def ic(xv):
51
+ o = np.zeros(len(names))
52
+ o[ih] = 0.12 if float(xv[0]) < 0.5 else 0.061
53
+ return o
54
+
55
+ sm.initial_conditions = IC.UserFunction(function=ic)
56
+ sm.aux_initial_conditions = IC.Constant(constants=lambda n: np.zeros(n))
57
+ return m.chorin_split(sp.Symbol("dt", positive=True), system_model=sm)
58
+
59
+
60
+ @pytest.mark.jax
61
+ def test_stages_construction_selects_the_same_submodels():
62
+ split = _split()
63
+ positional = ChorinSplitVAMSolverJax(split.SM_pred, split.SM_press, split.SM_corr)
64
+ staged = ChorinSplitVAMSolverJax(stages=split.stages)
65
+ # same OBJECTS, not merely equal ones — the stage list is a view of the
66
+ # same three sub-models.
67
+ assert staged.sm_pred is positional.sm_pred is split.SM_pred
68
+ assert staged.sm_press is positional.sm_press is split.SM_press
69
+ assert staged.sm_corr is positional.sm_corr is split.SM_corr
70
+
71
+
72
+ @pytest.mark.jax
73
+ def test_stages_bind_by_kind_not_position():
74
+ """core binds by `kind`; a shuffled list must still bind correctly.
75
+ If this ever passes by position, a reordered list would silently swap the
76
+ predictor and the corrector."""
77
+ split = _split()
78
+ shuffled = [split.stages[2], split.stages[0], split.stages[1]]
79
+ s = ChorinSplitVAMSolverJax(stages=shuffled)
80
+ assert s.sm_pred is split.SM_pred
81
+ assert s.sm_press is split.SM_press
82
+ assert s.sm_corr is split.SM_corr
83
+
84
+
85
+ @pytest.mark.jax
86
+ def test_stage_list_rejects_malformed_input():
87
+ split = _split()
88
+ with pytest.raises(TypeError): # both forms at once
89
+ ChorinSplitVAMSolverJax(split.SM_pred, split.SM_press, split.SM_corr,
90
+ stages=split.stages)
91
+ with pytest.raises(TypeError): # neither form
92
+ ChorinSplitVAMSolverJax()
93
+ with pytest.raises(ValueError): # duplicate kind
94
+ ChorinSplitVAMSolverJax(stages=[split.stages[0], split.stages[0],
95
+ split.stages[1], split.stages[2]])
96
+ with pytest.raises(ValueError): # missing a kind
97
+ ChorinSplitVAMSolverJax(stages=split.stages[:2])
98
+ with pytest.raises(ValueError): # unknown kind
99
+ bad = [("predictor", "parabolic", split.SM_pred)] + list(split.stages[1:])
100
+ ChorinSplitVAMSolverJax(stages=bad)
101
+
102
+
103
+ @pytest.mark.jax
104
+ def test_stages_accepts_bare_triples_not_only_namedtuples():
105
+ """core's `_bind_stages` documents bare `(label, kind, sm)` tuples as
106
+ acceptable; a backend that only took the NamedTuple would silently diverge
107
+ from the documented vocabulary."""
108
+ split = _split()
109
+ bare = [(s.label, s.kind, s.sm) for s in split.stages]
110
+ s = ChorinSplitVAMSolverJax(stages=bare)
111
+ assert s.sm_press is split.SM_press