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,628 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import tempfile
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ import jax.numpy as jnp
9
+ from matplotlib import cm
10
+ from matplotlib import colors
11
+ from matplotlib import pyplot as plt
12
+ import numpy as np
13
+ from PIL import Image
14
+
15
+ from ..geometry import SyntheticStellaratorGeometry, build_synthetic_stellarator_geometry
16
+ from ..native.fci import laplace_parallel_fci, laplace_perp_xz
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class StellaratorSolShowcaseArtifacts:
21
+ report_json_path: Path
22
+ arrays_npz_path: Path
23
+ snapshot_png_path: Path
24
+ diagnostics_png_path: Path
25
+ poster_png_path: Path
26
+ movie_gif_path: Path
27
+
28
+
29
+ def create_stellarator_sol_showcase_package(
30
+ *,
31
+ output_root: str | Path,
32
+ case_label: str = "stellarator_sol_showcase",
33
+ nx: int = 30,
34
+ ny: int = 30,
35
+ nz: int = 56,
36
+ ) -> StellaratorSolShowcaseArtifacts:
37
+ root = Path(output_root)
38
+ data_dir = root / "data"
39
+ images_dir = root / "images"
40
+ movies_dir = root / "movies"
41
+ data_dir.mkdir(parents=True, exist_ok=True)
42
+ images_dir.mkdir(parents=True, exist_ok=True)
43
+ movies_dir.mkdir(parents=True, exist_ok=True)
44
+
45
+ geometry = build_synthetic_stellarator_geometry(nx=nx, ny=ny, nz=nz)
46
+ history, time = simulate_reduced_stellarator_sol_dynamics(geometry)
47
+ report = build_stellarator_sol_showcase_report(geometry, history, time)
48
+ report_json_path = data_dir / f"{case_label}.json"
49
+ report_json_path.write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")
50
+ arrays_npz_path = data_dir / f"{case_label}.npz"
51
+ _write_showcase_arrays(geometry, history, time, arrays_npz_path)
52
+ snapshot_png_path = images_dir / f"{case_label}_snapshots.png"
53
+ save_stellarator_sol_snapshot_panel(geometry, history, time, snapshot_png_path)
54
+ diagnostics_png_path = images_dir / f"{case_label}_diagnostics.png"
55
+ save_stellarator_sol_diagnostics_panel(geometry, history, time, diagnostics_png_path)
56
+ poster_png_path = images_dir / f"{case_label}_poster.png"
57
+ save_stellarator_sol_3d_frame(geometry, history[-1], float(time[-1]), poster_png_path)
58
+ movie_gif_path = movies_dir / f"{case_label}.gif"
59
+ save_stellarator_sol_3d_movie(geometry, history, time, movie_gif_path)
60
+ return StellaratorSolShowcaseArtifacts(
61
+ report_json_path=report_json_path,
62
+ arrays_npz_path=arrays_npz_path,
63
+ snapshot_png_path=snapshot_png_path,
64
+ diagnostics_png_path=diagnostics_png_path,
65
+ poster_png_path=poster_png_path,
66
+ movie_gif_path=movie_gif_path,
67
+ )
68
+
69
+
70
+ def simulate_reduced_stellarator_sol_dynamics(
71
+ geometry: SyntheticStellaratorGeometry,
72
+ *,
73
+ frames: int = 34,
74
+ substeps_per_frame: int = 3,
75
+ dt: float = 0.010,
76
+ ) -> tuple[np.ndarray, np.ndarray]:
77
+ """Run a compact reduced 3D SOL dynamics benchmark on the FCI geometry."""
78
+
79
+ radial = np.asarray(geometry.radial, dtype=np.float64)
80
+ phi = np.asarray(geometry.toroidal_angle, dtype=np.float64)
81
+ theta = np.asarray(geometry.poloidal_angle, dtype=np.float64)
82
+ curvature = np.asarray(geometry.curvature, dtype=np.float64)
83
+ curvature = curvature / max(float(np.max(np.abs(curvature))), 1.0e-12)
84
+ envelope = np.exp(-((radial - 0.73) / 0.17) ** 2)
85
+ source_envelope = np.exp(-((radial - 0.60) / 0.12) ** 2)
86
+ seed_modes = (
87
+ 0.18 * np.cos(2.0 * theta - 5.0 * phi)
88
+ + 0.13 * np.sin(4.0 * theta - 5.0 * phi + 0.7)
89
+ + 0.08 * np.cos(7.0 * theta - 10.0 * phi + 1.4)
90
+ + 0.05 * np.sin(11.0 * theta + 3.0 * phi)
91
+ )
92
+ state = jnp.asarray(envelope * seed_modes, dtype=jnp.float64)
93
+ dx = float(1.0 / (geometry.maps.shape[0] - 1))
94
+ dz = float(2.0 * np.pi / geometry.maps.shape[2])
95
+ curvature_jax = jnp.asarray(curvature, dtype=jnp.float64)
96
+ envelope_jax = jnp.asarray(envelope, dtype=jnp.float64)
97
+ source_pattern = jnp.asarray(
98
+ source_envelope
99
+ * (
100
+ 0.160 * np.cos(4.0 * theta - 5.0 * phi)
101
+ + 0.105 * np.sin(2.0 * theta + 5.0 * phi)
102
+ + 0.070 * np.cos(6.0 * theta - 10.0 * phi + 0.3)
103
+ ),
104
+ dtype=jnp.float64,
105
+ )
106
+ history = []
107
+ time = []
108
+ for frame in range(frames):
109
+ history.append(np.asarray(state, dtype=np.float64))
110
+ time.append(frame * substeps_per_frame * dt)
111
+ for substep in range(substeps_per_frame):
112
+ current_time = (frame * substeps_per_frame + substep) * dt
113
+ dz_adv = (jnp.roll(state, -1, axis=2) - jnp.roll(state, 1, axis=2)) / (2.0 * dz)
114
+ dy_adv = (jnp.roll(state, -1, axis=1) - jnp.roll(state, 1, axis=1)) / (2.0 * geometry.maps.dphi)
115
+ radial_gradient = (jnp.roll(state, -1, axis=0) - jnp.roll(state, 1, axis=0)) / (2.0 * dx)
116
+ nonlinear_transfer = -0.42 * state * dz_adv + 0.24 * jnp.roll(state, 2, axis=2) * dy_adv
117
+ interchange_drive = 0.28 * curvature_jax * envelope_jax * radial_gradient
118
+ source_drive = source_pattern * (1.0 + 0.35 * jnp.sin(7.5 * current_time))
119
+ coherent_drive = 0.18 * curvature_jax * envelope_jax * (state + source_drive)
120
+ saturation = -0.48 * envelope_jax * state * state * state
121
+ damping = -0.035 * (1.0 - 0.25 * envelope_jax) * state
122
+ diffusion = 0.010 * laplace_parallel_fci(state, geometry.maps) + 1.8e-5 * laplace_perp_xz(
123
+ state,
124
+ dx=dx,
125
+ dz=dz,
126
+ )
127
+ state = state + dt * (
128
+ diffusion
129
+ + interchange_drive
130
+ + coherent_drive
131
+ + nonlinear_transfer
132
+ + saturation
133
+ + damping
134
+ + source_drive
135
+ )
136
+ state = jnp.nan_to_num(state, nan=0.0, posinf=2.0, neginf=-2.0)
137
+ state = jnp.clip(state, -1.5, 1.5)
138
+ return np.asarray(history, dtype=np.float64), np.asarray(time, dtype=np.float64)
139
+
140
+
141
+ def build_stellarator_sol_showcase_report(
142
+ geometry: SyntheticStellaratorGeometry,
143
+ history: np.ndarray,
144
+ time: np.ndarray,
145
+ ) -> dict[str, object]:
146
+ energy = np.mean(history * history, axis=(1, 2, 3))
147
+ final = history[-1]
148
+ radial = np.asarray(geometry.radial, dtype=np.float64)
149
+ curvature = np.asarray(geometry.curvature, dtype=np.float64)
150
+ positive = np.maximum(final, 0.0)
151
+ radial_center = float(np.sum(radial * positive) / max(np.sum(positive), 1.0e-12))
152
+ potential_proxy = np.roll(final, 2, axis=2)
153
+ dtheta_phi = -(np.roll(potential_proxy, -1, axis=2) - np.roll(potential_proxy, 1, axis=2)) / (
154
+ 2.0 * 2.0 * np.pi / geometry.maps.shape[2]
155
+ )
156
+ radial_flux_proxy = float(np.mean(final * dtheta_phi * curvature))
157
+ spectrum = np.abs(np.fft.rfftn(final, axes=(1, 2))) ** 2
158
+ total_spectral_power = float(np.sum(spectrum))
159
+ low_mode_power = float(np.sum(spectrum[:, :4, :6]) / max(total_spectral_power, 1.0e-12))
160
+ mode_power = np.mean(np.abs(np.fft.rfftn(final, axes=(1, 2))) ** 2, axis=0)
161
+ mode_power[0, 0] = 0.0
162
+ peak_mode = np.unravel_index(int(np.argmax(mode_power)), mode_power.shape)
163
+ cell_rms = np.std(history, axis=0)
164
+ cell_skewness = _cell_moment(history, 3)
165
+ report = {
166
+ "case": "reduced_non_axisymmetric_stellarator_sol_dynamics",
167
+ "geometry": geometry.metadata,
168
+ "time_start": float(time[0]),
169
+ "time_end": float(time[-1]),
170
+ "frame_count": int(history.shape[0]),
171
+ "energy_initial": float(energy[0]),
172
+ "energy_final": float(energy[-1]),
173
+ "energy_peak": float(np.max(energy)),
174
+ "energy_growth_factor": float(energy[-1] / max(energy[0], 1.0e-12)),
175
+ "final_rms_fluctuation": float(np.sqrt(np.mean(final * final))),
176
+ "final_skewness": _moment(final, 3),
177
+ "final_kurtosis": _moment(final, 4),
178
+ "positive_fluctuation_radial_center": radial_center,
179
+ "radial_flux_proxy": radial_flux_proxy,
180
+ "low_mode_spectral_power_fraction": low_mode_power,
181
+ "dominant_poloidal_mode_index": int(peak_mode[1]),
182
+ "dominant_toroidal_mode_index": int(peak_mode[0]),
183
+ "mean_cell_rms_fluctuation": float(np.mean(cell_rms)),
184
+ "max_cell_rms_fluctuation": float(np.max(cell_rms)),
185
+ "skewness_linf": float(np.max(np.abs(cell_skewness))),
186
+ "connection_length_weighted_rms": float(
187
+ np.sqrt(
188
+ np.mean(
189
+ final
190
+ * final
191
+ * np.asarray(geometry.connection_length)
192
+ / np.mean(np.asarray(geometry.connection_length))
193
+ )
194
+ )
195
+ ),
196
+ }
197
+ report["passed"] = (
198
+ np.isfinite(report["energy_final"])
199
+ and report["energy_final"] > 0.0
200
+ and report["final_rms_fluctuation"] > 1.0e-3
201
+ and abs(report["radial_flux_proxy"]) > 1.0e-5
202
+ and 0.0 < report["low_mode_spectral_power_fraction"] < 1.0
203
+ )
204
+ return report
205
+
206
+
207
+ def save_stellarator_sol_snapshot_panel(
208
+ geometry: SyntheticStellaratorGeometry,
209
+ history: np.ndarray,
210
+ time: np.ndarray,
211
+ path: str | Path,
212
+ ) -> Path:
213
+ resolved = Path(path)
214
+ resolved.parent.mkdir(parents=True, exist_ok=True)
215
+ time_indices = np.asarray([0, history.shape[0] // 2, history.shape[0] - 1], dtype=int)
216
+ toroidal_indices = np.asarray(
217
+ [0, geometry.shape[1] // 4, geometry.shape[1] // 2, 3 * geometry.shape[1] // 4],
218
+ dtype=int,
219
+ )
220
+ x = np.asarray(geometry.coordinates_x, dtype=np.float64)
221
+ y = np.asarray(geometry.coordinates_y, dtype=np.float64)
222
+ major_radius = np.sqrt(x * x + y * y)
223
+ z = np.asarray(geometry.coordinates_z, dtype=np.float64)
224
+ vmax = float(np.percentile(np.abs(history), 99.0))
225
+ norm = colors.TwoSlopeNorm(vmin=-vmax, vcenter=0.0, vmax=vmax)
226
+ fig, axes = plt.subplots(3, 4, figsize=(16.0, 10.2), constrained_layout=True)
227
+ image = None
228
+ for row, time_index in enumerate(time_indices):
229
+ for col, toroidal_index in enumerate(toroidal_indices):
230
+ axis = axes[row, col]
231
+ image = axis.pcolormesh(
232
+ major_radius[:, toroidal_index, :],
233
+ z[:, toroidal_index, :],
234
+ history[time_index, :, toroidal_index, :],
235
+ shading="gouraud",
236
+ cmap="coolwarm",
237
+ norm=norm,
238
+ )
239
+ axis.plot(major_radius[0, toroidal_index, :], z[0, toroidal_index, :], color="white", lw=2.0)
240
+ axis.plot(major_radius[-1, toroidal_index, :], z[-1, toroidal_index, :], color="0.35", lw=1.4)
241
+ axis.set_aspect("equal", adjustable="box")
242
+ phi_value = 2.0 * np.pi * toroidal_index / geometry.shape[1]
243
+ axis.set_title(rf"$t={time[time_index]:.2f}$, $\phi={phi_value:.2f}$")
244
+ axis.set_xlabel("R")
245
+ axis.set_ylabel("Z")
246
+ if image is not None:
247
+ fig.colorbar(image, ax=axes, shrink=0.72, label="density fluctuation proxy")
248
+ fig.suptitle(
249
+ "Reduced 3D stellarator SOL dynamics: R-Z panels at four toroidal angles",
250
+ fontsize=15,
251
+ )
252
+ fig.savefig(resolved, dpi=180)
253
+ plt.close(fig)
254
+ return resolved
255
+
256
+
257
+ def save_stellarator_sol_diagnostics_panel(
258
+ geometry: SyntheticStellaratorGeometry,
259
+ history: np.ndarray,
260
+ time: np.ndarray,
261
+ path: str | Path,
262
+ ) -> Path:
263
+ resolved = Path(path)
264
+ resolved.parent.mkdir(parents=True, exist_ok=True)
265
+ toroidal_index = 0
266
+ x = np.asarray(geometry.coordinates_x, dtype=np.float64)
267
+ y = np.asarray(geometry.coordinates_y, dtype=np.float64)
268
+ major_radius = np.sqrt(x * x + y * y)
269
+ z = np.asarray(geometry.coordinates_z, dtype=np.float64)
270
+ final = history[-1]
271
+ rms = np.std(history, axis=0)
272
+ skewness = _cell_moment(history, 3)
273
+ potential_proxy = np.roll(history, 2, axis=3)
274
+ dtheta = 2.0 * np.pi / geometry.shape[2]
275
+ radial_velocity_proxy = -(
276
+ np.roll(potential_proxy, -1, axis=3) - np.roll(potential_proxy, 1, axis=3)
277
+ ) / (2.0 * dtheta)
278
+ flux_proxy = np.mean(history * radial_velocity_proxy * np.asarray(geometry.curvature)[None, :, :, :], axis=0)
279
+ spectrum = np.mean(np.abs(np.fft.rfftn(final, axes=(1, 2))) ** 2, axis=0)
280
+ spectrum[0, 0] = 0.0
281
+ energy = np.mean(history * history, axis=(1, 2, 3))
282
+
283
+ fig, axes = plt.subplots(2, 3, figsize=(14.2, 8.0), constrained_layout=True)
284
+ density_proxy = 1.0 + 0.35 * final
285
+ image0 = axes[0, 0].pcolormesh(
286
+ major_radius[:, toroidal_index, :],
287
+ z[:, toroidal_index, :],
288
+ density_proxy[:, toroidal_index, :],
289
+ shading="gouraud",
290
+ cmap="turbo",
291
+ )
292
+ axes[0, 0].set_title("final density proxy")
293
+ fig.colorbar(image0, ax=axes[0, 0], label="n / n0")
294
+
295
+ image1 = axes[0, 1].pcolormesh(
296
+ major_radius[:, toroidal_index, :],
297
+ z[:, toroidal_index, :],
298
+ rms[:, toroidal_index, :],
299
+ shading="gouraud",
300
+ cmap="magma",
301
+ )
302
+ axes[0, 1].set_title("fluctuation RMS")
303
+ fig.colorbar(image1, ax=axes[0, 1], label="std(n~)")
304
+
305
+ skew_vmax = float(np.nanpercentile(np.abs(skewness), 98.0))
306
+ image2 = axes[0, 2].pcolormesh(
307
+ major_radius[:, toroidal_index, :],
308
+ z[:, toroidal_index, :],
309
+ skewness[:, toroidal_index, :],
310
+ shading="gouraud",
311
+ cmap="coolwarm",
312
+ norm=colors.TwoSlopeNorm(vmin=-skew_vmax, vcenter=0.0, vmax=skew_vmax),
313
+ )
314
+ axes[0, 2].set_title("density skewness")
315
+ fig.colorbar(image2, ax=axes[0, 2], label="skew(n~)")
316
+
317
+ flux_vmax = float(np.nanpercentile(np.abs(flux_proxy), 98.0))
318
+ image3 = axes[1, 0].pcolormesh(
319
+ major_radius[:, toroidal_index, :],
320
+ z[:, toroidal_index, :],
321
+ flux_proxy[:, toroidal_index, :],
322
+ shading="gouraud",
323
+ cmap="coolwarm",
324
+ norm=colors.TwoSlopeNorm(vmin=-flux_vmax, vcenter=0.0, vmax=flux_vmax),
325
+ )
326
+ axes[1, 0].set_title("radial flux proxy")
327
+ fig.colorbar(image3, ax=axes[1, 0], label="<n~ vR~>")
328
+
329
+ mode_image = axes[1, 1].imshow(
330
+ np.log10(np.maximum(spectrum.T, 1.0e-16)),
331
+ origin="lower",
332
+ aspect="auto",
333
+ cmap="viridis",
334
+ )
335
+ axes[1, 1].set_title("final toroidal-poloidal spectrum")
336
+ axes[1, 1].set_xlabel("toroidal mode index")
337
+ axes[1, 1].set_ylabel("poloidal mode index")
338
+ fig.colorbar(mode_image, ax=axes[1, 1], label="log10 power")
339
+
340
+ axes[1, 2].plot(time, energy, color="#005f73", lw=2.4, label="energy")
341
+ axes[1, 2].plot(time, np.sqrt(energy), color="#9b2226", lw=2.0, label="RMS")
342
+ axes[1, 2].set_title("time traces")
343
+ axes[1, 2].set_xlabel("normalized time")
344
+ axes[1, 2].set_ylabel("global metric")
345
+ axes[1, 2].legend(frameon=False)
346
+ for axis in axes[:, :].flat:
347
+ if axis is not axes[1, 1] and axis is not axes[1, 2]:
348
+ axis.plot(major_radius[0, toroidal_index, :], z[0, toroidal_index, :], color="white", lw=1.6)
349
+ axis.plot(major_radius[-1, toroidal_index, :], z[-1, toroidal_index, :], color="0.25", lw=1.0)
350
+ axis.set_aspect("equal", adjustable="box")
351
+ axis.set_xlabel("R")
352
+ axis.set_ylabel("Z")
353
+ fig.suptitle("Reduced stellarator SOL diagnostics: fluctuations, flux proxy, and mode content", fontsize=15)
354
+ fig.savefig(resolved, dpi=180)
355
+ plt.close(fig)
356
+ return resolved
357
+
358
+
359
+ def save_stellarator_sol_3d_movie(
360
+ geometry: SyntheticStellaratorGeometry,
361
+ history: np.ndarray,
362
+ time: np.ndarray,
363
+ path: str | Path,
364
+ ) -> Path:
365
+ resolved = Path(path)
366
+ resolved.parent.mkdir(parents=True, exist_ok=True)
367
+ frame_indices = np.linspace(0, history.shape[0] - 1, min(24, history.shape[0]), dtype=int)
368
+ with tempfile.TemporaryDirectory(prefix="drbx_stellarator_movie_") as temp_dir:
369
+ frame_paths = []
370
+ for local_index, frame_index in enumerate(frame_indices):
371
+ frame_path = Path(temp_dir) / f"frame_{local_index:03d}.png"
372
+ save_stellarator_sol_3d_frame(geometry, history[frame_index], float(time[frame_index]), frame_path)
373
+ frame_paths.append(frame_path)
374
+ images = [Image.open(frame_path).convert("P", palette=Image.Palette.ADAPTIVE) for frame_path in frame_paths]
375
+ images[0].save(resolved, save_all=True, append_images=images[1:], duration=120, loop=0)
376
+ for image in images:
377
+ image.close()
378
+ return resolved
379
+
380
+
381
+ def save_stellarator_sol_3d_frame(
382
+ geometry: SyntheticStellaratorGeometry,
383
+ field: np.ndarray,
384
+ time_value: float,
385
+ path: str | Path,
386
+ ) -> Path:
387
+ if max(geometry.shape) >= 24:
388
+ try:
389
+ return _save_stellarator_sol_3d_frame_pyvista(geometry, field, time_value, path)
390
+ except Exception:
391
+ pass
392
+ resolved = Path(path)
393
+ resolved.parent.mkdir(parents=True, exist_ok=True)
394
+ x = np.asarray(geometry.coordinates_x)
395
+ y = np.asarray(geometry.coordinates_y)
396
+ z = np.asarray(geometry.coordinates_z)
397
+ values = np.asarray(field, dtype=np.float64)
398
+ vmax = float(np.percentile(np.abs(values), 99.0))
399
+ norm = colors.TwoSlopeNorm(vmin=-vmax, vcenter=0.0, vmax=vmax)
400
+ cmap = plt.get_cmap("coolwarm")
401
+ phi_indices = np.arange(2, geometry.shape[1] - 5, 2)
402
+ theta_indices = np.arange(0, geometry.shape[2], 2)
403
+ radial_indices = np.arange(2, geometry.shape[0] - 1, 2)
404
+ cut_j = 3
405
+ outer_i = max(geometry.shape[0] - 4, 1)
406
+
407
+ fig = plt.figure(figsize=(8.0, 7.2), constrained_layout=True)
408
+ ax = fig.add_subplot(111, projection="3d")
409
+ surface_values = values[np.ix_([outer_i], phi_indices, theta_indices)][0]
410
+ ax.plot_surface(
411
+ x[np.ix_([outer_i], phi_indices, theta_indices)][0],
412
+ y[np.ix_([outer_i], phi_indices, theta_indices)][0],
413
+ z[np.ix_([outer_i], phi_indices, theta_indices)][0],
414
+ facecolors=cmap(norm(surface_values)),
415
+ linewidth=0,
416
+ antialiased=False,
417
+ alpha=0.86,
418
+ shade=False,
419
+ )
420
+ cut_values = values[np.ix_(radial_indices, [cut_j], theta_indices)][:, 0, :]
421
+ ax.plot_surface(
422
+ x[np.ix_(radial_indices, [cut_j], theta_indices)][:, 0, :],
423
+ y[np.ix_(radial_indices, [cut_j], theta_indices)][:, 0, :],
424
+ z[np.ix_(radial_indices, [cut_j], theta_indices)][:, 0, :],
425
+ facecolors=cmap(norm(cut_values)),
426
+ linewidth=0,
427
+ antialiased=False,
428
+ alpha=0.96,
429
+ shade=False,
430
+ )
431
+ inner_i = max(geometry.shape[0] // 3, 1)
432
+ ax.plot_wireframe(
433
+ x[np.ix_([inner_i], phi_indices[::2], theta_indices[::3])][0],
434
+ y[np.ix_([inner_i], phi_indices[::2], theta_indices[::3])][0],
435
+ z[np.ix_([inner_i], phi_indices[::2], theta_indices[::3])][0],
436
+ color="0.25",
437
+ linewidth=0.35,
438
+ alpha=0.28,
439
+ )
440
+ scalar = cm.ScalarMappable(norm=norm, cmap=cmap)
441
+ scalar.set_array([])
442
+ fig.colorbar(scalar, ax=ax, shrink=0.72, pad=0.02, label="density fluctuation proxy")
443
+ ax.set_title(
444
+ "Native reduced FCI stellarator SOL dynamics\n"
445
+ f"opened toroidal/radial view, t = {time_value:.2f}",
446
+ fontsize=11,
447
+ )
448
+ ax.set_xlabel("X")
449
+ ax.set_ylabel("Y")
450
+ ax.set_zlabel("Z")
451
+ ax.view_init(elev=22.0, azim=-48.0 + 18.0 * np.sin(0.7 * time_value))
452
+ extent = float(np.max(np.sqrt(x * x + y * y)))
453
+ ax.set_xlim(-extent, extent)
454
+ ax.set_ylim(-extent, extent)
455
+ ax.set_zlim(float(np.min(z)) * 1.1, float(np.max(z)) * 1.1)
456
+ ax.set_box_aspect((1.0, 1.0, 0.42))
457
+ fig.savefig(resolved, dpi=160)
458
+ plt.close(fig)
459
+ return resolved
460
+
461
+
462
+ def _save_stellarator_sol_3d_frame_pyvista(
463
+ geometry: SyntheticStellaratorGeometry,
464
+ field: np.ndarray,
465
+ time_value: float,
466
+ path: str | Path,
467
+ ) -> Path:
468
+ import pyvista as pv
469
+
470
+ resolved = Path(path)
471
+ resolved.parent.mkdir(parents=True, exist_ok=True)
472
+ x = np.asarray(geometry.coordinates_x)
473
+ y = np.asarray(geometry.coordinates_y)
474
+ z = np.asarray(geometry.coordinates_z)
475
+ values = np.asarray(field, dtype=np.float64)
476
+ vmax = float(np.nanpercentile(np.abs(values), 99.2))
477
+ if not np.isfinite(vmax) or vmax <= 0.0:
478
+ vmax = 1.0
479
+ scalar_name = "density fluctuation proxy"
480
+ ny = geometry.shape[1]
481
+ phi_window = np.arange(max(2, ny // 10), max(3, ny - ny // 5), dtype=int)
482
+ theta_window = np.arange(0, geometry.shape[2], 1, dtype=int)
483
+ radial_window = np.arange(1, geometry.shape[0] - 1, 1, dtype=int)
484
+
485
+ plotter = pv.Plotter(off_screen=True, window_size=(1280, 900))
486
+ plotter.set_background("white")
487
+ plotter.enable_anti_aliasing("ssaa")
488
+
489
+ def add_surface(
490
+ x_surface: np.ndarray,
491
+ y_surface: np.ndarray,
492
+ z_surface: np.ndarray,
493
+ scalar_values: np.ndarray,
494
+ *,
495
+ opacity: float,
496
+ show_scalar_bar: bool,
497
+ ) -> None:
498
+ mesh = pv.StructuredGrid(x_surface, y_surface, z_surface)
499
+ mesh[scalar_name] = np.asarray(scalar_values, dtype=np.float64).ravel(order="F")
500
+ plotter.add_mesh(
501
+ mesh,
502
+ scalars=scalar_name,
503
+ cmap="coolwarm",
504
+ clim=(-vmax, vmax),
505
+ opacity=opacity,
506
+ smooth_shading=True,
507
+ show_edges=False,
508
+ show_scalar_bar=show_scalar_bar,
509
+ scalar_bar_args={
510
+ "title": scalar_name,
511
+ "title_font_size": 18,
512
+ "label_font_size": 14,
513
+ "shadow": False,
514
+ "fmt": "%.2f",
515
+ },
516
+ )
517
+
518
+ outer_i = max(geometry.shape[0] - 3, 1)
519
+ middle_i = max(int(0.72 * geometry.shape[0]), 1)
520
+ for radial_index, opacity, show_bar in ((outer_i, 0.78, True), (middle_i, 0.52, False)):
521
+ add_surface(
522
+ x[np.ix_([radial_index], phi_window, theta_window)][0],
523
+ y[np.ix_([radial_index], phi_window, theta_window)][0],
524
+ z[np.ix_([radial_index], phi_window, theta_window)][0],
525
+ values[np.ix_([radial_index], phi_window, theta_window)][0],
526
+ opacity=opacity,
527
+ show_scalar_bar=show_bar,
528
+ )
529
+
530
+ for cut_j in (max(1, ny // 12), max(2, 7 * ny // 12)):
531
+ add_surface(
532
+ x[np.ix_(radial_window, [cut_j], theta_window)][:, 0, :],
533
+ y[np.ix_(radial_window, [cut_j], theta_window)][:, 0, :],
534
+ z[np.ix_(radial_window, [cut_j], theta_window)][:, 0, :],
535
+ values[np.ix_(radial_window, [cut_j], theta_window)][:, 0, :],
536
+ opacity=0.94,
537
+ show_scalar_bar=False,
538
+ )
539
+
540
+ for theta_seed in (0.15, 1.55, 3.15):
541
+ line_points = _field_line_points(geometry, radial_index=outer_i, theta_seed=theta_seed)
542
+ line = pv.PolyData(line_points)
543
+ line.lines = np.hstack([[line_points.shape[0]], np.arange(line_points.shape[0])])
544
+ plotter.add_mesh(line, color="black", line_width=2.2, opacity=0.72)
545
+
546
+ plotter.add_text(
547
+ "Reduced 3D stellarator SOL dynamics\n"
548
+ f"opened toroidal/radial view, t = {time_value:.2f}",
549
+ position=(32, 835),
550
+ font_size=14,
551
+ color="black",
552
+ )
553
+ plotter.add_text(
554
+ "Outer and mid-radius traced surfaces plus two radial cuts show interior fluctuations",
555
+ position="lower_left",
556
+ font_size=11,
557
+ color="black",
558
+ )
559
+ center = (float(np.nanmean(x)), float(np.nanmean(y)), float(np.nanmean(z)))
560
+ radius = 1.75 * max(float(np.nanmax(x) - np.nanmin(x)), float(np.nanmax(y) - np.nanmin(y)))
561
+ angle = np.deg2rad(-38.0 + 26.0 * np.sin(1.35 * time_value))
562
+ camera = (
563
+ center[0] + radius * np.cos(angle),
564
+ center[1] + radius * np.sin(angle),
565
+ center[2] + 0.55 * radius,
566
+ )
567
+ plotter.camera_position = [camera, center, (0.0, 0.0, 1.0)]
568
+ plotter.screenshot(str(resolved))
569
+ plotter.close()
570
+ return resolved
571
+
572
+
573
+ def _field_line_points(
574
+ geometry: SyntheticStellaratorGeometry,
575
+ *,
576
+ radial_index: int,
577
+ theta_seed: float,
578
+ ) -> np.ndarray:
579
+ x = np.asarray(geometry.coordinates_x)
580
+ y = np.asarray(geometry.coordinates_y)
581
+ z = np.asarray(geometry.coordinates_z)
582
+ phi = np.linspace(0.0, 2.0 * np.pi, geometry.shape[1], endpoint=False)
583
+ iota = np.asarray(geometry.iota[radial_index, :, 0], dtype=np.float64)
584
+ theta = np.mod(theta_seed + np.cumsum(iota) * geometry.maps.dphi, 2.0 * np.pi)
585
+ theta_indices = np.mod(np.rint(theta * geometry.shape[2] / (2.0 * np.pi)).astype(int), geometry.shape[2])
586
+ return np.column_stack(
587
+ [
588
+ x[radial_index, np.arange(geometry.shape[1]), theta_indices],
589
+ y[radial_index, np.arange(geometry.shape[1]), theta_indices],
590
+ z[radial_index, np.arange(geometry.shape[1]), theta_indices],
591
+ ]
592
+ )
593
+
594
+
595
+ def _write_showcase_arrays(
596
+ geometry: SyntheticStellaratorGeometry,
597
+ history: np.ndarray,
598
+ time: np.ndarray,
599
+ path: Path,
600
+ ) -> Path:
601
+ np.savez_compressed(
602
+ path,
603
+ history=np.asarray(history, dtype=np.float16),
604
+ time=np.asarray(time, dtype=np.float32),
605
+ x=np.asarray(geometry.coordinates_x, dtype=np.float32),
606
+ y=np.asarray(geometry.coordinates_y, dtype=np.float32),
607
+ z=np.asarray(geometry.coordinates_z, dtype=np.float32),
608
+ curvature=np.asarray(geometry.curvature, dtype=np.float32),
609
+ connection_length=np.asarray(geometry.connection_length, dtype=np.float32),
610
+ Bxy=np.asarray(geometry.metric.Bxy, dtype=np.float32),
611
+ )
612
+ return path
613
+
614
+
615
+ def _moment(values: np.ndarray, order: int) -> float:
616
+ centered = values - np.mean(values)
617
+ sigma = float(np.std(centered))
618
+ if sigma <= 0.0:
619
+ return 0.0
620
+ return float(np.mean((centered / sigma) ** order))
621
+
622
+
623
+ def _cell_moment(history: np.ndarray, order: int) -> np.ndarray:
624
+ centered = history - np.mean(history, axis=0, keepdims=True)
625
+ sigma = np.std(centered, axis=0)
626
+ safe_sigma = np.where(sigma > 1.0e-12, sigma, 1.0)
627
+ moment = np.mean((centered / safe_sigma[None, :, :, :]) ** order, axis=0)
628
+ return np.where(sigma > 1.0e-12, moment, 0.0)