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,558 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import shutil
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any, Mapping
8
+
9
+ import numpy as np
10
+ from matplotlib import pyplot as plt
11
+ from matplotlib import animation
12
+ from netCDF4 import Dataset
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class DivertedTokamakGeometry:
17
+ rxy: np.ndarray
18
+ zxy: np.ndarray
19
+ psixy: np.ndarray
20
+ wall_r: np.ndarray
21
+ wall_z: np.ndarray
22
+ lower_target_r: np.ndarray
23
+ lower_target_z: np.ndarray
24
+ upper_target_r: np.ndarray
25
+ upper_target_z: np.ndarray
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class DivertedTokamakFieldHistory:
30
+ field_name: str
31
+ time_points: np.ndarray
32
+ history_4d: np.ndarray
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class DivertedTokamakMovieArtifacts:
37
+ arrays_npz_path: Path
38
+ analysis_json_path: Path
39
+ snapshots_png_path: Path
40
+ poster_png_path: Path
41
+ movie_gif_path: Path
42
+
43
+
44
+ def assemble_tokamak_rank_history(
45
+ workdir: str | Path, *, field_name: str
46
+ ) -> DivertedTokamakFieldHistory:
47
+ root = Path(workdir)
48
+ dump_paths = sorted(root.glob("BOUT.dmp.*.nc"))
49
+ if not dump_paths:
50
+ raise FileNotFoundError(f"No BOUT dumps found in {root}")
51
+
52
+ with Dataset(dump_paths[0]) as dataset:
53
+ mxsub = int(np.asarray(dataset.variables["MXSUB"][:]).item())
54
+ mysub = int(np.asarray(dataset.variables["MYSUB"][:]).item())
55
+ mxg = int(np.asarray(dataset.variables["MXG"][:]).item())
56
+ myg = int(np.asarray(dataset.variables["MYG"][:]).item())
57
+ nxpe = int(np.asarray(dataset.variables["NXPE"][:]).item())
58
+ nype = int(np.asarray(dataset.variables["NYPE"][:]).item())
59
+ time_points = np.asarray(dataset.variables["t_array"][:], dtype=np.float64)
60
+ nz = dataset.dimensions["z"].size
61
+
62
+ history = np.zeros((time_points.size, mxsub * nxpe, mysub * nype, nz), dtype=np.float64)
63
+ for dump_path in dump_paths:
64
+ with Dataset(dump_path) as dataset:
65
+ pe_xind = int(np.asarray(dataset.variables["PE_XIND"][:]).item())
66
+ pe_yind = int(np.asarray(dataset.variables["PE_YIND"][:]).item())
67
+ field = np.asarray(dataset.variables[field_name][:], dtype=np.float64)
68
+ active = field[:, mxg : mxg + mxsub, myg : myg + mysub, :]
69
+ x_slice = slice(pe_xind * mxsub, (pe_xind + 1) * mxsub)
70
+ y_slice = slice(pe_yind * mysub, (pe_yind + 1) * mysub)
71
+ history[:, x_slice, y_slice, :] = active
72
+
73
+ return DivertedTokamakFieldHistory(
74
+ field_name=field_name,
75
+ time_points=time_points,
76
+ history_4d=history,
77
+ )
78
+
79
+
80
+ def load_diverted_tokamak_geometry(
81
+ mesh_path: str | Path,
82
+ *,
83
+ active_nx: int,
84
+ ) -> DivertedTokamakGeometry:
85
+ mesh = Path(mesh_path)
86
+ with Dataset(mesh) as dataset:
87
+ rxy_full = np.asarray(dataset.variables["Rxy"][:], dtype=np.float64)
88
+ zxy_full = np.asarray(dataset.variables["Zxy"][:], dtype=np.float64)
89
+ psixy_full = np.asarray(dataset.variables["psixy"][:], dtype=np.float64)
90
+ if active_nx > rxy_full.shape[0]:
91
+ raise ValueError(
92
+ f"Active nx {active_nx} exceeds mesh x extent {rxy_full.shape[0]}"
93
+ )
94
+ mxg = (rxy_full.shape[0] - active_nx) // 2
95
+ x_slice = slice(mxg, mxg + active_nx)
96
+ rxy = rxy_full[x_slice, :]
97
+ zxy = zxy_full[x_slice, :]
98
+ psixy = psixy_full[x_slice, :]
99
+ return DivertedTokamakGeometry(
100
+ rxy=rxy,
101
+ zxy=zxy,
102
+ psixy=psixy,
103
+ wall_r=np.asarray(rxy[-1, :], dtype=np.float64),
104
+ wall_z=np.asarray(zxy[-1, :], dtype=np.float64),
105
+ lower_target_r=np.asarray(rxy[:, 0], dtype=np.float64),
106
+ lower_target_z=np.asarray(zxy[:, 0], dtype=np.float64),
107
+ upper_target_r=np.asarray(rxy[:, -1], dtype=np.float64),
108
+ upper_target_z=np.asarray(zxy[:, -1], dtype=np.float64),
109
+ )
110
+
111
+
112
+ def toroidal_mean_fluctuation(history: DivertedTokamakFieldHistory) -> np.ndarray:
113
+ mean_history = np.asarray(history.history_4d.mean(axis=-1), dtype=np.float64)
114
+ return mean_history - mean_history[0]
115
+
116
+
117
+ def build_diverted_tokamak_analysis(
118
+ geometry: DivertedTokamakGeometry,
119
+ history: DivertedTokamakFieldHistory,
120
+ *,
121
+ field_history_2d: np.ndarray,
122
+ ) -> dict[str, Any]:
123
+ return {
124
+ "field_name": history.field_name,
125
+ "time_points": [float(value) for value in history.time_points],
126
+ "frame_minima": [float(np.min(frame)) for frame in field_history_2d],
127
+ "frame_maxima": [float(np.max(frame)) for frame in field_history_2d],
128
+ "global_min": float(np.min(field_history_2d)),
129
+ "global_max": float(np.max(field_history_2d)),
130
+ "lcfs_level": 0.0,
131
+ "geometry_shape": {
132
+ "x": int(geometry.rxy.shape[0]),
133
+ "y": int(geometry.rxy.shape[1]),
134
+ },
135
+ }
136
+
137
+
138
+ def write_diverted_tokamak_analysis_json(
139
+ analysis: Mapping[str, Any], path: str | Path
140
+ ) -> Path:
141
+ target = Path(path)
142
+ target.parent.mkdir(parents=True, exist_ok=True)
143
+ target.write_text(
144
+ json.dumps(dict(analysis), indent=2, sort_keys=True), encoding="utf-8"
145
+ )
146
+ return target
147
+
148
+
149
+ def write_diverted_tokamak_arrays_npz(
150
+ geometry: DivertedTokamakGeometry,
151
+ history: DivertedTokamakFieldHistory,
152
+ *,
153
+ field_history_2d: np.ndarray,
154
+ path: str | Path,
155
+ ) -> Path:
156
+ target = Path(path)
157
+ target.parent.mkdir(parents=True, exist_ok=True)
158
+ np.savez_compressed(
159
+ target,
160
+ field_name=np.asarray(history.field_name),
161
+ time_points=np.asarray(history.time_points, dtype=np.float64),
162
+ field_history_2d=np.asarray(field_history_2d, dtype=np.float64),
163
+ rxy=np.asarray(geometry.rxy, dtype=np.float64),
164
+ zxy=np.asarray(geometry.zxy, dtype=np.float64),
165
+ psixy=np.asarray(geometry.psixy, dtype=np.float64),
166
+ )
167
+ return target
168
+
169
+
170
+ def load_diverted_tokamak_arrays_npz(
171
+ path: str | Path,
172
+ ) -> tuple[DivertedTokamakGeometry, str, np.ndarray, np.ndarray]:
173
+ source = Path(path)
174
+ with np.load(source) as payload:
175
+ field_name = str(np.asarray(payload["field_name"]).item())
176
+ time_points = np.asarray(payload["time_points"], dtype=np.float64)
177
+ field_history_2d = np.asarray(payload["field_history_2d"], dtype=np.float64)
178
+ rxy = np.asarray(payload["rxy"], dtype=np.float64)
179
+ zxy = np.asarray(payload["zxy"], dtype=np.float64)
180
+ psixy = np.asarray(payload["psixy"], dtype=np.float64)
181
+ geometry = DivertedTokamakGeometry(
182
+ rxy=rxy,
183
+ zxy=zxy,
184
+ psixy=psixy,
185
+ wall_r=np.asarray(rxy[-1, :], dtype=np.float64),
186
+ wall_z=np.asarray(zxy[-1, :], dtype=np.float64),
187
+ lower_target_r=np.asarray(rxy[:, 0], dtype=np.float64),
188
+ lower_target_z=np.asarray(zxy[:, 0], dtype=np.float64),
189
+ upper_target_r=np.asarray(rxy[:, -1], dtype=np.float64),
190
+ upper_target_z=np.asarray(zxy[:, -1], dtype=np.float64),
191
+ )
192
+ return geometry, field_name, time_points, field_history_2d
193
+
194
+
195
+ def create_diverted_tokamak_movie_package(
196
+ *,
197
+ workdir: str | Path,
198
+ mesh_path: str | Path,
199
+ output_root: str | Path,
200
+ field_name: str = "Nd+",
201
+ case_label: str = "diverted_tokamak_turbulence",
202
+ fps: int = 10,
203
+ frames_per_interval: int = 8,
204
+ ) -> DivertedTokamakMovieArtifacts:
205
+ root = Path(output_root)
206
+ data_dir = root / "data"
207
+ images_dir = root / "images"
208
+ movies_dir = root / "movies"
209
+ data_dir.mkdir(parents=True, exist_ok=True)
210
+ images_dir.mkdir(parents=True, exist_ok=True)
211
+ movies_dir.mkdir(parents=True, exist_ok=True)
212
+
213
+ history = assemble_tokamak_rank_history(workdir, field_name=field_name)
214
+ geometry = load_diverted_tokamak_geometry(
215
+ mesh_path, active_nx=history.history_4d.shape[1]
216
+ )
217
+ field_history_2d = toroidal_mean_fluctuation(history)
218
+ analysis = build_diverted_tokamak_analysis(
219
+ geometry, history, field_history_2d=field_history_2d
220
+ )
221
+
222
+ arrays_npz_path = write_diverted_tokamak_arrays_npz(
223
+ geometry,
224
+ history,
225
+ field_history_2d=field_history_2d,
226
+ path=data_dir / f"{case_label}_arrays.npz",
227
+ )
228
+ analysis_json_path = write_diverted_tokamak_analysis_json(
229
+ analysis,
230
+ data_dir / f"{case_label}_analysis.json",
231
+ )
232
+ snapshots_png_path = save_diverted_tokamak_snapshot_panel(
233
+ geometry,
234
+ time_points=history.time_points,
235
+ field_history_2d=field_history_2d,
236
+ field_name=field_name,
237
+ path=images_dir / f"{case_label}_snapshots.png",
238
+ )
239
+ poster_png_path = save_diverted_tokamak_poster_frame(
240
+ geometry,
241
+ time_points=history.time_points,
242
+ field_history_2d=field_history_2d,
243
+ field_name=field_name,
244
+ path=images_dir / f"{case_label}_poster.png",
245
+ )
246
+ movie_gif_path = save_diverted_tokamak_gif(
247
+ geometry,
248
+ time_points=history.time_points,
249
+ field_history_2d=field_history_2d,
250
+ field_name=field_name,
251
+ path=movies_dir / f"{case_label}.gif",
252
+ fps=fps,
253
+ frames_per_interval=frames_per_interval,
254
+ )
255
+ return DivertedTokamakMovieArtifacts(
256
+ arrays_npz_path=arrays_npz_path,
257
+ analysis_json_path=analysis_json_path,
258
+ snapshots_png_path=snapshots_png_path,
259
+ poster_png_path=poster_png_path,
260
+ movie_gif_path=movie_gif_path,
261
+ )
262
+
263
+
264
+ def create_diverted_tokamak_movie_package_from_arrays(
265
+ *,
266
+ arrays_npz_path: str | Path,
267
+ output_root: str | Path,
268
+ case_label: str = "diverted_tokamak_turbulence",
269
+ field_name: str | None = None,
270
+ fps: int = 10,
271
+ frames_per_interval: int = 8,
272
+ ) -> DivertedTokamakMovieArtifacts:
273
+ root = Path(output_root)
274
+ data_dir = root / "data"
275
+ images_dir = root / "images"
276
+ movies_dir = root / "movies"
277
+ data_dir.mkdir(parents=True, exist_ok=True)
278
+ images_dir.mkdir(parents=True, exist_ok=True)
279
+ movies_dir.mkdir(parents=True, exist_ok=True)
280
+
281
+ source_npz = Path(arrays_npz_path)
282
+ (
283
+ geometry,
284
+ stored_field_name,
285
+ time_points,
286
+ field_history_2d,
287
+ ) = load_diverted_tokamak_arrays_npz(source_npz)
288
+ resolved_field_name = field_name or stored_field_name
289
+ arrays_target = data_dir / f"{case_label}_arrays.npz"
290
+ if source_npz.resolve() != arrays_target.resolve():
291
+ shutil.copyfile(source_npz, arrays_target)
292
+ else:
293
+ arrays_target = source_npz
294
+ history = DivertedTokamakFieldHistory(
295
+ field_name=resolved_field_name,
296
+ time_points=time_points,
297
+ history_4d=np.empty((time_points.size, 0, 0, 0), dtype=np.float64),
298
+ )
299
+ analysis = build_diverted_tokamak_analysis(
300
+ geometry,
301
+ history,
302
+ field_history_2d=field_history_2d,
303
+ )
304
+ analysis_json_path = write_diverted_tokamak_analysis_json(
305
+ analysis,
306
+ data_dir / f"{case_label}_analysis.json",
307
+ )
308
+ snapshots_png_path = save_diverted_tokamak_snapshot_panel(
309
+ geometry,
310
+ time_points=time_points,
311
+ field_history_2d=field_history_2d,
312
+ field_name=resolved_field_name,
313
+ path=images_dir / f"{case_label}_snapshots.png",
314
+ )
315
+ poster_png_path = save_diverted_tokamak_poster_frame(
316
+ geometry,
317
+ time_points=time_points,
318
+ field_history_2d=field_history_2d,
319
+ field_name=resolved_field_name,
320
+ path=images_dir / f"{case_label}_poster.png",
321
+ )
322
+ movie_gif_path = save_diverted_tokamak_gif(
323
+ geometry,
324
+ time_points=time_points,
325
+ field_history_2d=field_history_2d,
326
+ field_name=resolved_field_name,
327
+ path=movies_dir / f"{case_label}.gif",
328
+ fps=fps,
329
+ frames_per_interval=frames_per_interval,
330
+ )
331
+ return DivertedTokamakMovieArtifacts(
332
+ arrays_npz_path=arrays_target,
333
+ analysis_json_path=analysis_json_path,
334
+ snapshots_png_path=snapshots_png_path,
335
+ poster_png_path=poster_png_path,
336
+ movie_gif_path=movie_gif_path,
337
+ )
338
+
339
+
340
+ def save_diverted_tokamak_snapshot_panel(
341
+ geometry: DivertedTokamakGeometry,
342
+ *,
343
+ time_points: np.ndarray,
344
+ field_history_2d: np.ndarray,
345
+ field_name: str,
346
+ path: str | Path,
347
+ ) -> Path:
348
+ target = Path(path)
349
+ target.parent.mkdir(parents=True, exist_ok=True)
350
+ frame_indices = _representative_frame_indices(field_history_2d.shape[0])
351
+ figure, axes = plt.subplots(
352
+ 1, len(frame_indices), figsize=(14.0, 5.2), constrained_layout=True
353
+ )
354
+ if len(frame_indices) == 1:
355
+ axes = [axes]
356
+ vlim = _symmetric_color_limit(field_history_2d)
357
+ image = None
358
+ for axis, frame_index, label in zip(
359
+ axes, frame_indices, ("Initial", "Mid", "Final"), strict=True
360
+ ):
361
+ image = _draw_diverted_tokamak_frame(
362
+ axis,
363
+ geometry=geometry,
364
+ field_frame=field_history_2d[frame_index],
365
+ field_name=field_name,
366
+ time_value=float(time_points[frame_index]),
367
+ color_limit=vlim,
368
+ title_prefix=label,
369
+ )
370
+ figure.colorbar(
371
+ image,
372
+ ax=axes,
373
+ shrink=0.88,
374
+ pad=0.02,
375
+ label=f"{field_name} toroidal-mean fluctuation",
376
+ )
377
+ figure.savefig(target, dpi=180)
378
+ plt.close(figure)
379
+ return target
380
+
381
+
382
+ def save_diverted_tokamak_poster_frame(
383
+ geometry: DivertedTokamakGeometry,
384
+ *,
385
+ time_points: np.ndarray,
386
+ field_history_2d: np.ndarray,
387
+ field_name: str,
388
+ path: str | Path,
389
+ ) -> Path:
390
+ target = Path(path)
391
+ target.parent.mkdir(parents=True, exist_ok=True)
392
+ vlim = _symmetric_color_limit(field_history_2d)
393
+ frame_index = field_history_2d.shape[0] - 1
394
+ figure, axis = plt.subplots(figsize=(7.2, 8.0), constrained_layout=True)
395
+ image = _draw_diverted_tokamak_frame(
396
+ axis,
397
+ geometry=geometry,
398
+ field_frame=field_history_2d[frame_index],
399
+ field_name=field_name,
400
+ time_value=float(time_points[frame_index]),
401
+ color_limit=vlim,
402
+ title_prefix="Final",
403
+ )
404
+ figure.colorbar(
405
+ image,
406
+ ax=axis,
407
+ shrink=0.88,
408
+ pad=0.02,
409
+ label=f"{field_name} toroidal-mean fluctuation",
410
+ )
411
+ figure.savefig(target, dpi=180)
412
+ plt.close(figure)
413
+ return target
414
+
415
+
416
+ def save_diverted_tokamak_gif(
417
+ geometry: DivertedTokamakGeometry,
418
+ *,
419
+ time_points: np.ndarray,
420
+ field_history_2d: np.ndarray,
421
+ field_name: str,
422
+ path: str | Path,
423
+ fps: int,
424
+ frames_per_interval: int,
425
+ ) -> Path:
426
+ target = Path(path)
427
+ target.parent.mkdir(parents=True, exist_ok=True)
428
+ dense_time_points, dense_history = _interpolate_history(
429
+ np.asarray(time_points, dtype=np.float64),
430
+ np.asarray(field_history_2d, dtype=np.float64),
431
+ frames_per_interval=frames_per_interval,
432
+ )
433
+ vlim = _symmetric_color_limit(dense_history)
434
+ figure, axis = plt.subplots(figsize=(7.2, 8.0), constrained_layout=True)
435
+ image = _draw_diverted_tokamak_frame(
436
+ axis,
437
+ geometry=geometry,
438
+ field_frame=dense_history[0],
439
+ field_name=field_name,
440
+ time_value=float(dense_time_points[0]),
441
+ color_limit=vlim,
442
+ title_prefix="Toroidal Mean",
443
+ )
444
+ figure.colorbar(image, ax=axis, shrink=0.88, pad=0.02, label=f"{field_name} toroidal-mean fluctuation")
445
+
446
+ def update(frame_index: int):
447
+ axis.clear()
448
+ return (
449
+ _draw_diverted_tokamak_frame(
450
+ axis,
451
+ geometry=geometry,
452
+ field_frame=dense_history[frame_index],
453
+ field_name=field_name,
454
+ time_value=float(dense_time_points[frame_index]),
455
+ color_limit=vlim,
456
+ title_prefix="Toroidal Mean",
457
+ ),
458
+ )
459
+
460
+ movie = animation.FuncAnimation(
461
+ figure,
462
+ update,
463
+ frames=dense_history.shape[0],
464
+ interval=1000 / max(fps, 1),
465
+ blit=False,
466
+ )
467
+ movie.save(target, writer=animation.PillowWriter(fps=fps), dpi=140)
468
+ plt.close(figure)
469
+ return target
470
+
471
+
472
+ def _draw_diverted_tokamak_frame(
473
+ axis,
474
+ *,
475
+ geometry: DivertedTokamakGeometry,
476
+ field_frame: np.ndarray,
477
+ field_name: str,
478
+ time_value: float,
479
+ color_limit: float,
480
+ title_prefix: str,
481
+ ):
482
+ image = axis.tripcolor(
483
+ geometry.rxy.ravel(),
484
+ geometry.zxy.ravel(),
485
+ field_frame.ravel(),
486
+ shading="gouraud",
487
+ cmap="RdBu_r",
488
+ vmin=-color_limit,
489
+ vmax=color_limit,
490
+ rasterized=True,
491
+ )
492
+ axis.contour(
493
+ geometry.rxy,
494
+ geometry.zxy,
495
+ geometry.psixy,
496
+ levels=[0.0],
497
+ colors="white",
498
+ linewidths=1.5,
499
+ linestyles="--",
500
+ )
501
+ axis.plot(geometry.wall_r, geometry.wall_z, color="black", linewidth=2.4, label="Wall")
502
+ axis.plot(
503
+ geometry.lower_target_r,
504
+ geometry.lower_target_z,
505
+ color="#ff9f1c",
506
+ linewidth=2.2,
507
+ label="Lower divertor",
508
+ )
509
+ axis.plot(
510
+ geometry.upper_target_r,
511
+ geometry.upper_target_z,
512
+ color="#2ec4b6",
513
+ linewidth=2.2,
514
+ label="Upper divertor",
515
+ )
516
+ axis.set_aspect("equal")
517
+ axis.set_xlabel("R [m]")
518
+ axis.set_ylabel("Z [m]")
519
+ axis.set_title(f"{title_prefix}: {field_name} | t = {time_value:.3f}")
520
+ axis.legend(loc="upper right", frameon=True)
521
+ return image
522
+
523
+
524
+ def _representative_frame_indices(frame_count: int) -> tuple[int, int, int]:
525
+ if frame_count <= 1:
526
+ return (0, 0, 0)
527
+ if frame_count == 2:
528
+ return (0, 1, 1)
529
+ return (0, frame_count // 2, frame_count - 1)
530
+
531
+
532
+ def _symmetric_color_limit(field_history_2d: np.ndarray) -> float:
533
+ limit = float(np.percentile(np.abs(field_history_2d), 99.0))
534
+ return max(limit, 1.0e-12)
535
+
536
+
537
+ def _interpolate_history(
538
+ time_points: np.ndarray,
539
+ field_history_2d: np.ndarray,
540
+ *,
541
+ frames_per_interval: int,
542
+ ) -> tuple[np.ndarray, np.ndarray]:
543
+ if field_history_2d.shape[0] <= 1 or frames_per_interval <= 1:
544
+ return np.asarray(time_points, dtype=np.float64), np.asarray(field_history_2d, dtype=np.float64)
545
+ dense_times: list[float] = []
546
+ dense_frames: list[np.ndarray] = []
547
+ for index in range(field_history_2d.shape[0] - 1):
548
+ start_time = float(time_points[index])
549
+ end_time = float(time_points[index + 1])
550
+ start_frame = np.asarray(field_history_2d[index], dtype=np.float64)
551
+ end_frame = np.asarray(field_history_2d[index + 1], dtype=np.float64)
552
+ for substep in range(frames_per_interval):
553
+ alpha = substep / float(frames_per_interval)
554
+ dense_times.append((1.0 - alpha) * start_time + alpha * end_time)
555
+ dense_frames.append((1.0 - alpha) * start_frame + alpha * end_frame)
556
+ dense_times.append(float(time_points[-1]))
557
+ dense_frames.append(np.asarray(field_history_2d[-1], dtype=np.float64))
558
+ return np.asarray(dense_times, dtype=np.float64), np.asarray(dense_frames, dtype=np.float64)