drbx 2.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. drbx/__init__.py +20 -0
  2. drbx/__main__.py +5 -0
  3. drbx/cli.py +586 -0
  4. drbx/config/__init__.py +20 -0
  5. drbx/config/boutinp.py +556 -0
  6. drbx/config/model.py +34 -0
  7. drbx/config/normalization.py +66 -0
  8. drbx/data/atomic_rates/__init__.py +1 -0
  9. drbx/data/atomic_rates/iz_AMJUEL_H.x_2.1.5.json +213 -0
  10. drbx/data/atomic_rates/iz_AMJUEL_H.x_2.3.9a.json +213 -0
  11. drbx/data/atomic_rates/rec_AMJUEL_H.x_2.1.8.json +213 -0
  12. drbx/data/atomic_rates/rec_AMJUEL_H.x_2.3.13a.json +213 -0
  13. drbx/geometry/__init__.py +207 -0
  14. drbx/geometry/embedding.py +56 -0
  15. drbx/geometry/essos_import.py +1385 -0
  16. drbx/geometry/fci_geometry.py +4622 -0
  17. drbx/geometry/fci_maps.py +85 -0
  18. drbx/geometry/island_divertor.py +291 -0
  19. drbx/geometry/metric_tensor.py +99 -0
  20. drbx/geometry/open_slab.py +150 -0
  21. drbx/geometry/rotating_ellipse.py +253 -0
  22. drbx/geometry/shifted_torus.py +225 -0
  23. drbx/geometry/stellarator.py +287 -0
  24. drbx/geometry/vmec_extender_import.py +499 -0
  25. drbx/geometry/vmec_jax_import.py +306 -0
  26. drbx/linear/__init__.py +37 -0
  27. drbx/linear/dispersion.py +138 -0
  28. drbx/linear/eigen.py +91 -0
  29. drbx/native/__init__.py +224 -0
  30. drbx/native/array_backend.py +64 -0
  31. drbx/native/deck_runner.py +779 -0
  32. drbx/native/electromagnetic.py +250 -0
  33. drbx/native/expression.py +173 -0
  34. drbx/native/fci.py +295 -0
  35. drbx/native/fci_2_field_rhs.py +182 -0
  36. drbx/native/fci_4_field_rhs.py +1267 -0
  37. drbx/native/fci_boundaries.py +2494 -0
  38. drbx/native/fci_differentiable_case.py +304 -0
  39. drbx/native/fci_drb_EB_rhs.py +1243 -0
  40. drbx/native/fci_drb_rhs.py +190 -0
  41. drbx/native/fci_halo.py +1575 -0
  42. drbx/native/fci_helpers.py +350 -0
  43. drbx/native/fci_model.py +294 -0
  44. drbx/native/fci_neutral.py +139 -0
  45. drbx/native/fci_operators.py +4081 -0
  46. drbx/native/fci_sharding.py +597 -0
  47. drbx/native/fci_sheath_recycling.py +206 -0
  48. drbx/native/fci_time_integrator.py +96 -0
  49. drbx/native/fci_vorticity.py +198 -0
  50. drbx/native/fluid_1d.py +330 -0
  51. drbx/native/hasegawa_wakatani.py +196 -0
  52. drbx/native/limiters.py +57 -0
  53. drbx/native/mesh.py +238 -0
  54. drbx/native/metrics.py +234 -0
  55. drbx/native/neutrals/__init__.py +58 -0
  56. drbx/native/neutrals/atomic_rates.py +134 -0
  57. drbx/native/neutrals/detachment_sol_model.py +221 -0
  58. drbx/native/neutrals/reactions.py +164 -0
  59. drbx/native/neutrals/recycling_sol_model.py +197 -0
  60. drbx/native/sol_flux_tube.py +133 -0
  61. drbx/native/stellarator_turbulence.py +343 -0
  62. drbx/native/transport.py +134 -0
  63. drbx/native/units.py +32 -0
  64. drbx/native/vorticity.py +252 -0
  65. drbx/runtime/__init__.py +53 -0
  66. drbx/runtime/artifacts.py +161 -0
  67. drbx/runtime/memory.py +144 -0
  68. drbx/runtime/output.py +374 -0
  69. drbx/runtime/paths.py +9 -0
  70. drbx/runtime/performance.py +161 -0
  71. drbx/runtime/run_config.py +184 -0
  72. drbx/runtime/scheduler.py +99 -0
  73. drbx/runtime/state.py +40 -0
  74. drbx/validation/__init__.py +424 -0
  75. drbx/validation/autodiff_diffusion.py +329 -0
  76. drbx/validation/autodiff_diffusion_uncertainty.py +235 -0
  77. drbx/validation/diverted_tokamak_movie.py +558 -0
  78. drbx/validation/essos_fieldline_import_campaign.py +181 -0
  79. drbx/validation/essos_imported_artifact_audit.py +535 -0
  80. drbx/validation/essos_imported_drb_movie_campaign.py +2826 -0
  81. drbx/validation/essos_imported_fci_campaign.py +5241 -0
  82. drbx/validation/essos_imported_pytree_campaign.py +406 -0
  83. drbx/validation/essos_vmec_closed_field_campaign.py +314 -0
  84. drbx/validation/essos_vmec_closed_field_transient_campaign.py +629 -0
  85. drbx/validation/essos_vmec_fieldline_surface_campaign.py +620 -0
  86. drbx/validation/fluid_1d_mms_convergence.py +250 -0
  87. drbx/validation/geometry_lineouts.py +136 -0
  88. drbx/validation/geometry_slices.py +178 -0
  89. drbx/validation/publication_plotting.py +91 -0
  90. drbx/validation/stellarator_drb_pytree_campaign.py +621 -0
  91. drbx/validation/stellarator_fci_geometry_campaign.py +200 -0
  92. drbx/validation/stellarator_fci_operator_campaign.py +304 -0
  93. drbx/validation/stellarator_fci_suite_campaign.py +264 -0
  94. drbx/validation/stellarator_metric_mms_campaign.py +289 -0
  95. drbx/validation/stellarator_neutral_physics_campaign.py +255 -0
  96. drbx/validation/stellarator_sheath_recycling_campaign.py +331 -0
  97. drbx/validation/stellarator_sol_showcase.py +628 -0
  98. drbx/validation/stellarator_vorticity_campaign.py +304 -0
  99. drbx/validation/vmec_extender_edge_field_campaign.py +260 -0
  100. drbx/validation/vmec_extender_sol_smoke_campaign.py +365 -0
  101. drbx-2.0.0.dev0.dist-info/METADATA +380 -0
  102. drbx-2.0.0.dev0.dist-info/RECORD +106 -0
  103. drbx-2.0.0.dev0.dist-info/WHEEL +5 -0
  104. drbx-2.0.0.dev0.dist-info/entry_points.txt +2 -0
  105. drbx-2.0.0.dev0.dist-info/licenses/LICENSE +21 -0
  106. drbx-2.0.0.dev0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,621 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from dataclasses import dataclass, replace
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import jax
10
+ import jax.numpy as jnp
11
+ from matplotlib import pyplot as plt
12
+ import numpy as np
13
+
14
+ from ..geometry import SyntheticStellaratorGeometry, build_synthetic_stellarator_geometry
15
+ from ..native.fci_drb_rhs import FciDrbRhsParameters, FciDrbState, compute_fci_drb_rhs
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class StellaratorDrbPytreeCampaignArtifacts:
20
+ report_json_path: Path
21
+ arrays_npz_path: Path
22
+ plot_png_path: Path
23
+
24
+
25
+ def create_stellarator_drb_pytree_campaign_package(
26
+ *,
27
+ output_root: str | Path,
28
+ case_label: str = "stellarator_drb_pytree_campaign",
29
+ nx: int = 18,
30
+ ny: int = 16,
31
+ nz: int = 32,
32
+ steps: int = 8,
33
+ ) -> StellaratorDrbPytreeCampaignArtifacts:
34
+ root = Path(output_root)
35
+ data_dir = root / "data"
36
+ images_dir = root / "images"
37
+ data_dir.mkdir(parents=True, exist_ok=True)
38
+ images_dir.mkdir(parents=True, exist_ok=True)
39
+ report, arrays = build_stellarator_drb_pytree_campaign(nx=nx, ny=ny, nz=nz, steps=steps)
40
+ report_json_path = data_dir / f"{case_label}.json"
41
+ report_json_path.write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")
42
+ arrays_npz_path = data_dir / f"{case_label}.npz"
43
+ np.savez_compressed(arrays_npz_path, **arrays)
44
+ plot_png_path = images_dir / f"{case_label}.png"
45
+ save_stellarator_drb_pytree_plot(report, arrays, plot_png_path)
46
+ return StellaratorDrbPytreeCampaignArtifacts(
47
+ report_json_path=report_json_path,
48
+ arrays_npz_path=arrays_npz_path,
49
+ plot_png_path=plot_png_path,
50
+ )
51
+
52
+
53
+ def build_stellarator_drb_pytree_campaign(
54
+ *,
55
+ nx: int = 18,
56
+ ny: int = 16,
57
+ nz: int = 32,
58
+ steps: int = 8,
59
+ ) -> tuple[dict[str, Any], dict[str, np.ndarray]]:
60
+ geometry = build_synthetic_stellarator_geometry(nx=nx, ny=ny, nz=nz)
61
+ parameters = FciDrbRhsParameters(potential_iterations=32, potential_boussinesq=True)
62
+ non_boussinesq_parameters = replace(parameters, potential_boussinesq=False)
63
+ dt = 1.5e-5
64
+ run_transient = _build_jitted_transient(geometry, parameters=parameters, dt=dt, steps=steps)
65
+ initial = initial_fci_drb_state(geometry, drive_scale=1.0)
66
+ model_switch_report, model_switch_arrays = _build_boussinesq_model_switch_gate(
67
+ geometry,
68
+ initial=initial,
69
+ boussinesq_parameters=parameters,
70
+ non_boussinesq_parameters=non_boussinesq_parameters,
71
+ dt=dt,
72
+ steps=steps,
73
+ )
74
+
75
+ t0 = time.perf_counter()
76
+ final_state, history = run_transient(initial)
77
+ _block_until_ready((final_state, history))
78
+ compile_and_first_execute_seconds = time.perf_counter() - t0
79
+
80
+ t1 = time.perf_counter()
81
+ final_state, history = run_transient(initial)
82
+ _block_until_ready((final_state, history))
83
+ warm_execute_seconds = time.perf_counter() - t1
84
+
85
+ objective = _build_objective(geometry, parameters=parameters, dt=dt, steps=steps)
86
+ value, jvp_derivative = jax.jvp(objective, (jnp.asarray(1.0, dtype=jnp.float64),), (jnp.asarray(1.0, dtype=jnp.float64),))
87
+ _block_until_ready((value, jvp_derivative))
88
+ eps = 1.0e-3
89
+ finite_difference = (objective(1.0 + eps) - objective(1.0 - eps)) / (2.0 * eps)
90
+ _block_until_ready(finite_difference)
91
+ jvp_relative_error = float(
92
+ jnp.abs(jvp_derivative - finite_difference) / jnp.maximum(jnp.abs(finite_difference), 1.0e-14)
93
+ )
94
+
95
+ batch_sizes = np.asarray([1, 2, 4, 8], dtype=np.int64)
96
+ batch_times = []
97
+ batch_values: list[np.ndarray] = []
98
+ batched_objective = jax.jit(jax.vmap(objective))
99
+ for batch_size in batch_sizes:
100
+ scales = jnp.linspace(0.85, 1.15, int(batch_size), dtype=jnp.float64)
101
+ values = batched_objective(scales)
102
+ _block_until_ready(values)
103
+ t_batch = time.perf_counter()
104
+ values = batched_objective(scales)
105
+ _block_until_ready(values)
106
+ batch_times.append(time.perf_counter() - t_batch)
107
+ batch_values.append(np.asarray(values, dtype=np.float64))
108
+
109
+ serial_scales = np.linspace(0.85, 1.15, 4)
110
+ serial_values = np.asarray([float(objective(scale)) for scale in serial_scales], dtype=np.float64)
111
+ vmap_values = np.asarray(batched_objective(jnp.asarray(serial_scales, dtype=jnp.float64)), dtype=np.float64)
112
+ vmap_serial_linf = float(np.max(np.abs(serial_values - vmap_values)))
113
+
114
+ pmap_seconds = None
115
+ pmap_values = None
116
+ local_device_count = len(jax.local_devices())
117
+ if local_device_count > 1:
118
+ pmap_objective = jax.pmap(objective)
119
+ device_scales = jnp.linspace(0.90, 1.10, local_device_count, dtype=jnp.float64)
120
+ pmap_objective(device_scales).block_until_ready()
121
+ t_pmap = time.perf_counter()
122
+ pmap_values_array = pmap_objective(device_scales)
123
+ pmap_values_array.block_until_ready()
124
+ pmap_seconds = time.perf_counter() - t_pmap
125
+ pmap_values = np.asarray(pmap_values_array, dtype=np.float64)
126
+
127
+ history_np = np.asarray(history, dtype=np.float64)
128
+ final_ion = np.asarray(final_state.ion_density, dtype=np.float64)
129
+ final_neutral = np.asarray(final_state.neutral_density, dtype=np.float64)
130
+ final_vorticity = np.asarray(final_state.vorticity, dtype=np.float64)
131
+ min_density = float(min(np.min(final_ion), np.min(final_neutral)))
132
+ report: dict[str, Any] = {
133
+ "case": "non_axisymmetric_fci_drb_pytree_transient",
134
+ "geometry": geometry.metadata,
135
+ "steps": int(steps),
136
+ "dt": float(dt),
137
+ "potential_boussinesq": bool(parameters.potential_boussinesq),
138
+ "compile_and_first_execute_seconds": float(compile_and_first_execute_seconds),
139
+ "warm_execute_seconds": float(warm_execute_seconds),
140
+ "jvp_objective_value": float(value),
141
+ "jvp_derivative": float(jvp_derivative),
142
+ "finite_difference_derivative": float(finite_difference),
143
+ "jvp_relative_error": jvp_relative_error,
144
+ "vmap_serial_linf": vmap_serial_linf,
145
+ "batch_sizes": batch_sizes.tolist(),
146
+ "batch_execute_seconds": [float(item) for item in batch_times],
147
+ "batch_throughput_cases_per_second": [float(size / max(seconds, 1.0e-30)) for size, seconds in zip(batch_sizes, batch_times, strict=True)],
148
+ "local_devices": [str(device) for device in jax.local_devices()],
149
+ "local_device_count": int(local_device_count),
150
+ "pmap_execute_seconds": None if pmap_seconds is None else float(pmap_seconds),
151
+ "final_min_density": min_density,
152
+ "final_ion_density_mean": float(np.mean(final_ion)),
153
+ "final_neutral_density_mean": float(np.mean(final_neutral)),
154
+ "final_vorticity_rms": float(np.sqrt(np.mean(final_vorticity * final_vorticity))),
155
+ "final_potential_residual_l2": float(history_np[-1, 4]),
156
+ **model_switch_report,
157
+ }
158
+ report["passed"] = (
159
+ np.all(np.isfinite(history_np))
160
+ and min_density > 0.0
161
+ and report["final_vorticity_rms"] > 0.0
162
+ and report["final_potential_residual_l2"] < 2.0
163
+ and jvp_relative_error < 5.0e-3
164
+ and report["non_boussinesq_jvp_relative_error"] < 5.0e-3
165
+ and report["boussinesq_non_boussinesq_potential_relative_l2"] > 1.0e-4
166
+ and report["boussinesq_non_boussinesq_rhs_state_linf"] < 1.0e-12
167
+ and report["potential_feedback_plasma_rhs_linf"] > 1.0e-8
168
+ and report["potential_feedback_neutral_rhs_linf"] < 1.0e-12
169
+ and report["potential_feedback_jvp_relative_error"] < 5.0e-3
170
+ and vmap_serial_linf < 1.0e-8
171
+ and report["warm_execute_seconds"] > 0.0
172
+ )
173
+ arrays = {
174
+ "time_index": np.arange(history_np.shape[0], dtype=np.int64),
175
+ "history": history_np.astype(np.float32),
176
+ "final_ion_density_slice": final_ion[:, 0, :].astype(np.float32),
177
+ "final_neutral_density_slice": final_neutral[:, 0, :].astype(np.float32),
178
+ "final_vorticity_slice": final_vorticity[:, 0, :].astype(np.float32),
179
+ "batch_sizes": batch_sizes.astype(np.float32),
180
+ "batch_execute_seconds": np.asarray(batch_times, dtype=np.float32),
181
+ "batch_values_4": vmap_values.astype(np.float32),
182
+ "serial_values_4": serial_values.astype(np.float32),
183
+ "serial_scales_4": serial_scales.astype(np.float32),
184
+ "pmap_values": np.asarray([] if pmap_values is None else pmap_values, dtype=np.float32),
185
+ "jvp_summary": np.asarray([float(jvp_derivative), float(finite_difference), jvp_relative_error], dtype=np.float32),
186
+ **model_switch_arrays,
187
+ }
188
+ return report, arrays
189
+
190
+
191
+ def initial_fci_drb_state(geometry: SyntheticStellaratorGeometry, *, drive_scale: float = 1.0) -> FciDrbState:
192
+ radial = geometry.radial
193
+ theta = geometry.poloidal_angle
194
+ phi = geometry.toroidal_angle
195
+ helical = jnp.cos(2.0 * theta - 5.0 * phi)
196
+ sideband = jnp.sin(3.0 * theta + 2.0 * phi)
197
+ ion_density = 0.60 + drive_scale * 0.78 * jnp.exp(-jnp.square((radial - 0.67) / 0.18)) * (1.0 + 0.06 * helical)
198
+ neutral_density = 0.10 + drive_scale * 0.28 * jnp.exp(-jnp.square((radial - 0.92) / 0.08)) * (1.0 + 0.12 * helical)
199
+ electron_density = ion_density * (1.0 + 0.006 * sideband)
200
+ ion_temperature = 0.065 + 0.10 * (1.0 - radial)
201
+ electron_temperature = 0.080 + 0.15 * (1.0 - radial)
202
+ neutral_temperature = 0.018 + 0.018 * radial
203
+ return FciDrbState(
204
+ ion_density=ion_density,
205
+ electron_density=electron_density,
206
+ neutral_density=neutral_density,
207
+ ion_pressure=ion_density * ion_temperature,
208
+ electron_pressure=electron_density * electron_temperature,
209
+ neutral_pressure=neutral_density * neutral_temperature,
210
+ ion_momentum=0.020 * ion_density * helical,
211
+ neutral_momentum=0.012 * neutral_density * jnp.sin(theta - 5.0 * phi),
212
+ vorticity=0.035 * jnp.sin(2.0 * theta - 5.0 * phi) + 0.012 * sideband,
213
+ )
214
+
215
+
216
+ def _build_boussinesq_model_switch_gate(
217
+ geometry: SyntheticStellaratorGeometry,
218
+ *,
219
+ initial: FciDrbState,
220
+ boussinesq_parameters: FciDrbRhsParameters,
221
+ non_boussinesq_parameters: FciDrbRhsParameters,
222
+ dt: float,
223
+ steps: int,
224
+ ) -> tuple[dict[str, Any], dict[str, np.ndarray]]:
225
+ boussinesq_result = compute_fci_drb_rhs(
226
+ initial,
227
+ maps=geometry.maps,
228
+ metric=geometry.metric,
229
+ parameters=boussinesq_parameters,
230
+ )
231
+ non_boussinesq_result = compute_fci_drb_rhs(
232
+ initial,
233
+ maps=geometry.maps,
234
+ metric=geometry.metric,
235
+ parameters=non_boussinesq_parameters,
236
+ )
237
+ _block_until_ready((boussinesq_result, non_boussinesq_result))
238
+ boussinesq_potential = np.asarray(boussinesq_result.potential, dtype=np.float64)
239
+ non_boussinesq_potential = np.asarray(non_boussinesq_result.potential, dtype=np.float64)
240
+ potential_difference = non_boussinesq_potential - boussinesq_potential
241
+ potential_relative_l2 = float(
242
+ np.sqrt(np.mean(potential_difference * potential_difference))
243
+ / max(np.sqrt(np.mean(boussinesq_potential * boussinesq_potential)), 1.0e-30)
244
+ )
245
+ rhs_state_linf = _state_linf_difference(
246
+ boussinesq_result.rhs,
247
+ non_boussinesq_result.rhs,
248
+ )
249
+ feedback_strength = 4.0e-2
250
+ boussinesq_feedback_parameters = replace(
251
+ boussinesq_parameters,
252
+ plasma_exb_advection_strength=feedback_strength,
253
+ )
254
+ non_boussinesq_feedback_parameters = replace(
255
+ non_boussinesq_parameters,
256
+ plasma_exb_advection_strength=feedback_strength,
257
+ )
258
+ boussinesq_feedback_result = compute_fci_drb_rhs(
259
+ initial,
260
+ maps=geometry.maps,
261
+ metric=geometry.metric,
262
+ parameters=boussinesq_feedback_parameters,
263
+ )
264
+ non_boussinesq_feedback_result = compute_fci_drb_rhs(
265
+ initial,
266
+ maps=geometry.maps,
267
+ metric=geometry.metric,
268
+ parameters=non_boussinesq_feedback_parameters,
269
+ )
270
+ _block_until_ready((boussinesq_feedback_result, non_boussinesq_feedback_result))
271
+ feedback_plasma_linf = _plasma_linf_difference(
272
+ boussinesq_feedback_result.rhs,
273
+ non_boussinesq_feedback_result.rhs,
274
+ )
275
+ feedback_neutral_linf = _neutral_linf_difference(
276
+ boussinesq_feedback_result.rhs,
277
+ non_boussinesq_feedback_result.rhs,
278
+ )
279
+ coefficient = np.asarray(
280
+ initial.ion_density / jnp.maximum(jnp.square(geometry.metric.Bxy), 1.0e-30),
281
+ dtype=np.float64,
282
+ )
283
+ coefficient_contrast = float(np.max(coefficient) / max(float(np.min(coefficient)), 1.0e-30))
284
+ non_boussinesq_objective = _build_objective(
285
+ geometry,
286
+ parameters=non_boussinesq_parameters,
287
+ dt=dt,
288
+ steps=steps,
289
+ )
290
+ value, derivative = jax.jvp(
291
+ non_boussinesq_objective,
292
+ (jnp.asarray(1.0, dtype=jnp.float64),),
293
+ (jnp.asarray(1.0, dtype=jnp.float64),),
294
+ )
295
+ _block_until_ready((value, derivative))
296
+ eps = 1.0e-3
297
+ finite_difference = (
298
+ non_boussinesq_objective(1.0 + eps)
299
+ - non_boussinesq_objective(1.0 - eps)
300
+ ) / (2.0 * eps)
301
+ _block_until_ready(finite_difference)
302
+ jvp_relative_error = float(
303
+ jnp.abs(derivative - finite_difference)
304
+ / jnp.maximum(jnp.abs(finite_difference), 1.0e-14)
305
+ )
306
+ feedback_objective = _build_objective(
307
+ geometry,
308
+ parameters=non_boussinesq_feedback_parameters,
309
+ dt=dt,
310
+ steps=steps,
311
+ )
312
+ feedback_value, feedback_derivative = jax.jvp(
313
+ feedback_objective,
314
+ (jnp.asarray(1.0, dtype=jnp.float64),),
315
+ (jnp.asarray(1.0, dtype=jnp.float64),),
316
+ )
317
+ _block_until_ready((feedback_value, feedback_derivative))
318
+ feedback_finite_difference = (
319
+ feedback_objective(1.0 + eps)
320
+ - feedback_objective(1.0 - eps)
321
+ ) / (2.0 * eps)
322
+ _block_until_ready(feedback_finite_difference)
323
+ feedback_jvp_relative_error = float(
324
+ jnp.abs(feedback_derivative - feedback_finite_difference)
325
+ / jnp.maximum(jnp.abs(feedback_finite_difference), 1.0e-14)
326
+ )
327
+ report = {
328
+ "boussinesq_gate_potential_boussinesq": bool(boussinesq_parameters.potential_boussinesq),
329
+ "non_boussinesq_gate_potential_boussinesq": bool(
330
+ non_boussinesq_parameters.potential_boussinesq
331
+ ),
332
+ "boussinesq_potential_residual_l2": float(np.asarray(boussinesq_result.potential_residual_l2)),
333
+ "non_boussinesq_potential_residual_l2": float(np.asarray(non_boussinesq_result.potential_residual_l2)),
334
+ "boussinesq_non_boussinesq_potential_relative_l2": potential_relative_l2,
335
+ "boussinesq_non_boussinesq_rhs_state_linf": rhs_state_linf,
336
+ "density_over_b_squared_contrast": coefficient_contrast,
337
+ "non_boussinesq_jvp_objective_value": float(value),
338
+ "non_boussinesq_jvp_derivative": float(derivative),
339
+ "non_boussinesq_finite_difference_derivative": float(finite_difference),
340
+ "non_boussinesq_jvp_relative_error": jvp_relative_error,
341
+ "potential_feedback_strength": feedback_strength,
342
+ "potential_feedback_boussinesq_rhs_state_linf": _state_linf_difference(
343
+ boussinesq_result.rhs,
344
+ boussinesq_feedback_result.rhs,
345
+ ),
346
+ "potential_feedback_non_boussinesq_rhs_state_linf": _state_linf_difference(
347
+ non_boussinesq_result.rhs,
348
+ non_boussinesq_feedback_result.rhs,
349
+ ),
350
+ "potential_feedback_plasma_rhs_linf": feedback_plasma_linf,
351
+ "potential_feedback_neutral_rhs_linf": feedback_neutral_linf,
352
+ "potential_feedback_jvp_objective_value": float(feedback_value),
353
+ "potential_feedback_jvp_derivative": float(feedback_derivative),
354
+ "potential_feedback_finite_difference_derivative": float(feedback_finite_difference),
355
+ "potential_feedback_jvp_relative_error": feedback_jvp_relative_error,
356
+ }
357
+ arrays = {
358
+ "boussinesq_potential_slice": boussinesq_potential[:, 0, :].astype(np.float32),
359
+ "non_boussinesq_potential_slice": non_boussinesq_potential[:, 0, :].astype(np.float32),
360
+ "potential_model_difference_slice": potential_difference[:, 0, :].astype(np.float32),
361
+ "potential_feedback_plasma_rhs_difference_slice": np.asarray(
362
+ non_boussinesq_feedback_result.rhs.ion_density
363
+ - boussinesq_feedback_result.rhs.ion_density,
364
+ dtype=np.float64,
365
+ )[:, 0, :].astype(np.float32),
366
+ "density_over_b_squared_slice": coefficient[:, 0, :].astype(np.float32),
367
+ "model_switch_summary": np.asarray(
368
+ [
369
+ potential_relative_l2,
370
+ report["boussinesq_potential_residual_l2"],
371
+ report["non_boussinesq_potential_residual_l2"],
372
+ rhs_state_linf,
373
+ jvp_relative_error,
374
+ coefficient_contrast,
375
+ feedback_plasma_linf,
376
+ feedback_neutral_linf,
377
+ feedback_jvp_relative_error,
378
+ ],
379
+ dtype=np.float32,
380
+ ),
381
+ }
382
+ return report, arrays
383
+
384
+
385
+ def save_stellarator_drb_pytree_plot(
386
+ report: dict[str, Any],
387
+ arrays: dict[str, np.ndarray],
388
+ path: str | Path,
389
+ ) -> Path:
390
+ resolved = Path(path)
391
+ resolved.parent.mkdir(parents=True, exist_ok=True)
392
+ fig, axes = plt.subplots(3, 3, figsize=(16.2, 12.6), constrained_layout=True)
393
+ history = arrays["history"]
394
+ for column, label in ((0, "mean ion density"), (1, "mean neutral density"), (3, "vorticity RMS")):
395
+ reference = max(abs(float(history[0, column])), 1.0e-30)
396
+ axes[0, 0].plot(
397
+ arrays["time_index"],
398
+ 1.0e6 * (history[:, column] - history[0, column]) / reference,
399
+ lw=2.0,
400
+ label=label,
401
+ )
402
+ axes[0, 0].set_title("short 3D PyTree transient")
403
+ axes[0, 0].set_xlabel("step")
404
+ axes[0, 0].set_ylabel("change from step 0 [ppm]")
405
+ axes[0, 0].grid(alpha=0.25)
406
+ axes[0, 0].legend(frameon=False, fontsize=8)
407
+
408
+ image1 = axes[0, 1].imshow(arrays["final_ion_density_slice"], origin="lower", aspect="auto", cmap="viridis")
409
+ axes[0, 1].set_title("final ion density")
410
+ fig.colorbar(image1, ax=axes[0, 1])
411
+
412
+ image2 = axes[0, 2].imshow(arrays["final_neutral_density_slice"], origin="lower", aspect="auto", cmap="magma")
413
+ axes[0, 2].set_title("final neutral density")
414
+ fig.colorbar(image2, ax=axes[0, 2])
415
+
416
+ axes[1, 0].plot(arrays["serial_scales_4"], arrays["serial_values_4"], "o-", lw=2.0, label="serial")
417
+ axes[1, 0].plot(arrays["serial_scales_4"], arrays["batch_values_4"], "s--", lw=2.0, label="vmap")
418
+ axes[1, 0].set_title("batched objective matches serial")
419
+ axes[1, 0].set_xlabel("drive scale")
420
+ axes[1, 0].grid(alpha=0.25)
421
+ axes[1, 0].legend(frameon=False)
422
+
423
+ throughput = arrays["batch_sizes"] / np.maximum(arrays["batch_execute_seconds"], 1.0e-30)
424
+ axes[1, 1].plot(arrays["batch_sizes"], throughput, "o-", lw=2.2, color="#0a9396")
425
+ axes[1, 1].set_title("single-device batched throughput")
426
+ axes[1, 1].set_xlabel("batch size")
427
+ axes[1, 1].set_ylabel("cases / second")
428
+ axes[1, 1].grid(alpha=0.25)
429
+
430
+ labels = ["JVP", "finite diff", "rel. error"]
431
+ axes[1, 2].bar(np.arange(3), np.abs(arrays["jvp_summary"]), color=["#005f73", "#9b2226", "#ee9b00"])
432
+ axes[1, 2].set_xticks(np.arange(3), labels, rotation=18, ha="right")
433
+ axes[1, 2].set_yscale("log")
434
+ axes[1, 2].grid(axis="y", alpha=0.25)
435
+ axes[1, 2].set_title("JVP derivative gate")
436
+ axes[1, 2].text(
437
+ 0.03,
438
+ 0.96,
439
+ "\n".join(
440
+ [
441
+ f"warm run = {report['warm_execute_seconds']:.3f} s",
442
+ f"JVP rel. err = {report['jvp_relative_error']:.1e}",
443
+ f"devices = {report['local_device_count']}",
444
+ ]
445
+ ),
446
+ transform=axes[1, 2].transAxes,
447
+ va="top",
448
+ ha="left",
449
+ fontsize=8,
450
+ bbox={"facecolor": "white", "alpha": 0.82, "edgecolor": "0.8"},
451
+ )
452
+
453
+ image6 = axes[2, 0].imshow(
454
+ arrays["boussinesq_potential_slice"],
455
+ origin="lower",
456
+ aspect="auto",
457
+ cmap="viridis",
458
+ )
459
+ axes[2, 0].set_title("Boussinesq potential solve")
460
+ fig.colorbar(image6, ax=axes[2, 0])
461
+
462
+ image7 = axes[2, 1].imshow(
463
+ arrays["non_boussinesq_potential_slice"],
464
+ origin="lower",
465
+ aspect="auto",
466
+ cmap="viridis",
467
+ )
468
+ axes[2, 1].set_title("non-Boussinesq potential solve")
469
+ fig.colorbar(image7, ax=axes[2, 1])
470
+
471
+ vmax = float(np.max(np.abs(arrays["potential_model_difference_slice"])))
472
+ image8 = axes[2, 2].imshow(
473
+ arrays["potential_model_difference_slice"],
474
+ origin="lower",
475
+ aspect="auto",
476
+ cmap="coolwarm",
477
+ vmin=-vmax,
478
+ vmax=vmax,
479
+ )
480
+ axes[2, 2].set_title("non-Boussinesq minus Boussinesq")
481
+ fig.colorbar(image8, ax=axes[2, 2])
482
+ axes[2, 2].text(
483
+ 0.03,
484
+ 0.96,
485
+ "\n".join(
486
+ [
487
+ f"rel. L2 = {report['boussinesq_non_boussinesq_potential_relative_l2']:.2e}",
488
+ f"non-Bq JVP err = {report['non_boussinesq_jvp_relative_error']:.1e}",
489
+ f"n/B^2 contrast = {report['density_over_b_squared_contrast']:.2f}",
490
+ f"ExB plasma RHS = {report['potential_feedback_plasma_rhs_linf']:.1e}",
491
+ f"ExB JVP err = {report['potential_feedback_jvp_relative_error']:.1e}",
492
+ ]
493
+ ),
494
+ transform=axes[2, 2].transAxes,
495
+ va="top",
496
+ ha="left",
497
+ fontsize=8,
498
+ bbox={"facecolor": "white", "alpha": 0.82, "edgecolor": "0.8"},
499
+ )
500
+ for axis in (axes[0, 1], axes[0, 2], axes[2, 0], axes[2, 1], axes[2, 2]):
501
+ axis.set_xlabel("poloidal index")
502
+ axis.set_ylabel("radial index")
503
+ fig.suptitle(
504
+ "True 3D non-axisymmetric PyTree lane: DRB RHS, model switch, JVP, and batched execution",
505
+ fontsize=14,
506
+ )
507
+ fig.savefig(resolved, dpi=190)
508
+ plt.close(fig)
509
+ return resolved
510
+
511
+
512
+ def _state_linf_difference(left: FciDrbState, right: FciDrbState) -> float:
513
+ differences = [
514
+ float(np.max(np.abs(np.asarray(left_leaf) - np.asarray(right_leaf))))
515
+ for left_leaf, right_leaf in zip(
516
+ jax.tree_util.tree_leaves(left),
517
+ jax.tree_util.tree_leaves(right),
518
+ strict=True,
519
+ )
520
+ ]
521
+ return max(differences, default=0.0)
522
+
523
+
524
+ def _plasma_linf_difference(left: FciDrbState, right: FciDrbState) -> float:
525
+ differences = [
526
+ float(np.max(np.abs(np.asarray(left_leaf) - np.asarray(right_leaf))))
527
+ for left_leaf, right_leaf in (
528
+ (left.ion_density, right.ion_density),
529
+ (left.electron_density, right.electron_density),
530
+ (left.ion_pressure, right.ion_pressure),
531
+ (left.electron_pressure, right.electron_pressure),
532
+ (left.ion_momentum, right.ion_momentum),
533
+ (left.vorticity, right.vorticity),
534
+ )
535
+ ]
536
+ return max(differences, default=0.0)
537
+
538
+
539
+ def _neutral_linf_difference(left: FciDrbState, right: FciDrbState) -> float:
540
+ differences = [
541
+ float(np.max(np.abs(np.asarray(left_leaf) - np.asarray(right_leaf))))
542
+ for left_leaf, right_leaf in (
543
+ (left.neutral_density, right.neutral_density),
544
+ (left.neutral_pressure, right.neutral_pressure),
545
+ (left.neutral_momentum, right.neutral_momentum),
546
+ )
547
+ ]
548
+ return max(differences, default=0.0)
549
+
550
+
551
+ def _build_jitted_transient(
552
+ geometry: SyntheticStellaratorGeometry,
553
+ *,
554
+ parameters: FciDrbRhsParameters,
555
+ dt: float,
556
+ steps: int,
557
+ ):
558
+ def run(initial_state: FciDrbState) -> tuple[FciDrbState, jax.Array]:
559
+ def step(state: FciDrbState, _unused: None) -> tuple[FciDrbState, jax.Array]:
560
+ result = compute_fci_drb_rhs(state, maps=geometry.maps, metric=geometry.metric, parameters=parameters)
561
+ next_state = _clip_state(_add_scaled_state(state, result.rhs, dt))
562
+ diagnostics = jnp.asarray(
563
+ [
564
+ jnp.mean(next_state.ion_density),
565
+ jnp.mean(next_state.neutral_density),
566
+ jnp.mean(next_state.electron_pressure),
567
+ jnp.sqrt(jnp.mean(jnp.square(next_state.vorticity))),
568
+ result.potential_residual_l2,
569
+ ],
570
+ dtype=jnp.float64,
571
+ )
572
+ return next_state, diagnostics
573
+
574
+ return jax.lax.scan(step, initial_state, None, length=int(steps))
575
+
576
+ return jax.jit(run)
577
+
578
+
579
+ def _build_objective(
580
+ geometry: SyntheticStellaratorGeometry,
581
+ *,
582
+ parameters: FciDrbRhsParameters,
583
+ dt: float,
584
+ steps: int,
585
+ ):
586
+ run_transient = _build_jitted_transient(geometry, parameters=parameters, dt=dt, steps=steps)
587
+
588
+ def objective(drive_scale: jax.Array) -> jax.Array:
589
+ final_state, history = run_transient(initial_fci_drb_state(geometry, drive_scale=drive_scale))
590
+ return (
591
+ jnp.mean(final_state.ion_density)
592
+ + 0.25 * jnp.mean(final_state.neutral_density)
593
+ + 0.05 * jnp.sqrt(jnp.mean(jnp.square(final_state.vorticity)))
594
+ + 0.01 * history[-1, 4]
595
+ )
596
+
597
+ return objective
598
+
599
+
600
+ def _add_scaled_state(state: FciDrbState, rhs: FciDrbState, scale: float) -> FciDrbState:
601
+ return jax.tree_util.tree_map(lambda value, increment: value + float(scale) * increment, state, rhs)
602
+
603
+
604
+ def _clip_state(state: FciDrbState) -> FciDrbState:
605
+ return FciDrbState(
606
+ ion_density=jnp.maximum(state.ion_density, 1.0e-6),
607
+ electron_density=jnp.maximum(state.electron_density, 1.0e-6),
608
+ neutral_density=jnp.maximum(state.neutral_density, 1.0e-8),
609
+ ion_pressure=jnp.maximum(state.ion_pressure, 1.0e-8),
610
+ electron_pressure=jnp.maximum(state.electron_pressure, 1.0e-8),
611
+ neutral_pressure=jnp.maximum(state.neutral_pressure, 1.0e-10),
612
+ ion_momentum=state.ion_momentum,
613
+ neutral_momentum=state.neutral_momentum,
614
+ vorticity=state.vorticity,
615
+ )
616
+
617
+
618
+ def _block_until_ready(value: object) -> None:
619
+ for leaf in jax.tree_util.tree_leaves(value):
620
+ if hasattr(leaf, "block_until_ready"):
621
+ leaf.block_until_ready()