diff --git a/.gitignore b/.gitignore index f0b50b73..739b4265 100644 --- a/.gitignore +++ b/.gitignore @@ -178,11 +178,3 @@ examples/input.optimized # README figures, regenerated by docs/make_readme_figures.py !docs/readme_*.png - -# Generated tracing output stays local; compact reference data are committed. -.tmp/ -examples/benchmarks/results/ -!examples/benchmarks/references/*.json -!docs/_static/analytical_perturbations/*.png -# Vector copies are generated alongside the committed documentation images. -docs/_static/analytical_perturbations/*.svg diff --git a/README.md b/README.md index ab446b5a..453539d0 100644 --- a/README.md +++ b/README.md @@ -206,38 +206,22 @@ and its derivatives, together with the flux functions `G`, `I` and `iota`. ### Prescribed analytical Alfvén perturbations -Analytical modes supply `delta A = alpha B0` and an electric potential to the -existing guiding-centre equations, in Boozer coordinates or full VMEC geometry. -The corrections include magnetic flutter, induction and the parallel-force -correction, with constant magnetic moment and physical wave energy exchange. +Analytical modes supply `delta A = alpha B0` and a potential to the guiding-centre +equations, in Boozer coordinates (`trace_boozer(..., perturbation=...)`) or in full +VMEC geometry, with flutter, induction and constant magnetic moment: ```python from essos.gc_perturbations import AnalyticalVmecAlfvenMode -wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4, - radial_center=.4, radial_width=.5) -tracing = Tracing(field=field, particles=particles, - model="GuidingCenterAdaptative", perturbation=wave, - maxtime=2e-7, times_to_trace=9, progress=False) +wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4, radial_center=.4, radial_width=.5) +tracing = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", + perturbation=wave, maxtime=2e-7, times_to_trace=9, progress=False) ``` -The [small CPU example](examples/particle_tracing/vmec_alfven_cpu_smoke.py) -traces two particles with and without a wave under a 120-second cap. -[Equations, conservation checks and reproduction commands](docs/analytical_perturbations.rst) -describe the model and its limits. +See [the equations, tests and the comparison with Paul et al. (2023)](docs/analytical_perturbations.rst); +[`alfven_perturbation.py`](examples/particle_tracing/alfven_perturbation.py) is a short example. -![Paul alpha-loss comparison: 100 particles per curve](docs/_static/analytical_perturbations/paul_loss_100.png) - -The Paul comparison uses the same 100 initial particles for Boozer / Perfect QS -and VMEC / full equilibrium, without and with the m=15 wave. Weighted losses -are 12.25% / 21.53% for Boozer and 12.25% / 20.56% for VMEC. Published endpoints -are shown as crosses. This small comparison does not establish quantitative -paper reproduction. Compact saved data regenerate all documentation figures -without particle tracing: - -```bash -python -m examples.benchmarks.plot_alfven_results -``` +![Paul alpha-loss comparison](docs/_static/analytical_perturbations/paul_loss_100.png) ## Comparison with other codes diff --git a/docs/_static/analytical_perturbations/gc_verification.png b/docs/_static/analytical_perturbations/gc_verification.png deleted file mode 100644 index 73803a30..00000000 Binary files a/docs/_static/analytical_perturbations/gc_verification.png and /dev/null differ diff --git a/docs/_static/analytical_perturbations/paul_loss_100.png b/docs/_static/analytical_perturbations/paul_loss_100.png index e81172d4..6d42384d 100644 Binary files a/docs/_static/analytical_perturbations/paul_loss_100.png and b/docs/_static/analytical_perturbations/paul_loss_100.png differ diff --git a/docs/_static/analytical_perturbations/vmec_alfven_smoke.png b/docs/_static/analytical_perturbations/vmec_alfven_smoke.png deleted file mode 100644 index 86f4eddd..00000000 Binary files a/docs/_static/analytical_perturbations/vmec_alfven_smoke.png and /dev/null differ diff --git a/docs/analytical_perturbations.rst b/docs/analytical_perturbations.rst index 4ed5c5c1..4331f631 100644 --- a/docs/analytical_perturbations.rst +++ b/docs/analytical_perturbations.rst @@ -1,157 +1,91 @@ Prescribed Alfvén perturbations -============================== +=============================== -ESSOS follows collisionless guiding centres in an equilibrium with imposed, -time-dependent shear-Alfvén potentials. Analytical modes work in Boozer -coordinates and in full VMEC geometry through the existing guiding-centre -functions and integrators. This model prescribes the wave; it does not evolve -its growth, nonlinear saturation or response to the particles. +ESSOS follows collisionless guiding centres in a static equilibrium with imposed, +time-dependent shear-Alfvén potentials, in Boozer coordinates (``trace_boozer``) or in +the native coordinates of any field such as VMEC (``Tracing``). The wave is prescribed: +there is no growth, saturation or response to the particles. -Equations and conventions -------------------------- +Equations +--------- -The reduced electromagnetic action uses a static equilibrium field and +The reduced model uses :math:`\delta\mathbf A=\alpha\mathbf B_0` and a potential +:math:`\Phi`, so :math:`\delta\mathbf B=\nabla\times(\alpha\mathbf B_0)` and +:math:`\delta\mathbf E=-\nabla\Phi-\partial_t\alpha\,\mathbf B_0` (``alpha`` in m, +``Phi`` in V, frequencies in rad/s). The Hamiltonian keeps the equilibrium magnitude, .. math:: - \delta\mathbf A=\alpha\mathbf B_0,\qquad - \delta\mathbf B=\nabla\times(\alpha\mathbf B_0),\qquad - \delta\mathbf E=-\nabla\Phi-\partial_t\alpha\,\mathbf B_0. + H=\tfrac12 Mv_\parallel^2+\mu B_0+q\Phi,\qquad \dot\mu=0, -Here ``alpha`` is in metres, ``Phi`` is in volts and frequency is in rad/s. -The Hamiltonian retains the equilibrium magnitude: +and with :math:`\mathbf B^*=\mathbf B_0+\tfrac{Mv_\parallel}{q}\nabla\times\mathbf b_0 ++\delta\mathbf B`, :math:`\mathbf E^*=\mathbf E_0+\delta\mathbf E-\tfrac{\mu}{q}\nabla B_0`, .. math:: - H=\tfrac12 Mv_\parallel^2+\mu B_0+q\Phi,\qquad - \mu=\frac{Mv_\perp^2}{2B_0},\qquad \dot\mu=0. + \dot{\mathbf R}=\frac{v_\parallel\mathbf B^*+\mathbf E^*\times\mathbf b_0}{\mathbf b_0\cdot\mathbf B^*},\qquad + \dot v_\parallel=\frac{q}{M}\frac{\mathbf B^*\cdot\mathbf E^*}{\mathbf b_0\cdot\mathbf B^*}. -The existing scalar RHS receives the corrections required by the action. -Equivalently, define +In the existing curvature-drift form the corrections are magnetic flutter, inductive +acceleration and the parallel-force term that cancels the extra curvature contraction +with :math:`\delta\mathbf B`. Every Runge-Kutta stage uses its physical time. Kinetic energy +changes through wave work while :math:`\mu` is constant, so the perturbed native trace uses +the fixed-:math:`\mu` ``GuidingCenterMu`` state. The native equations keep all covariant +components of :math:`\mathbf B_0`, including VMEC's radial one; the Boozer model uses +:math:`\mathbf B_{\rm cov}=I\,d\theta+G\,d\zeta` and omits its radial component +(:math:`K=0`). -.. math:: - - \mathbf B^* &= \mathbf B_0+\frac{Mv_\parallel}{q}\nabla\times\mathbf b_0 - +\delta\mathbf B,\\ - B_\parallel^* &= \mathbf b_0\cdot\mathbf B^*,\\ - \mathbf E^* &= \mathbf E_0+\delta\mathbf E-\frac{\mu}{q}\nabla B_0. - -Then - -.. math:: - - \dot{\mathbf R}&=\frac{v_\parallel\mathbf B^*+ - \mathbf E^*\times\mathbf b_0}{B_\parallel^*},\\ - \dot v_\parallel&=\frac{q}{M}\frac{\mathbf B^*\cdot\mathbf E^*}{B_\parallel^*}. +Modes +----- -In ESSOS's curvature-drift form, the updates include magnetic flutter, -inductive electric acceleration and the parallel-force correction that -cancels the extra curvature contraction with the perturbed field. There is -no additional matrix solve or replacement GC integrator. Time-dependent -Runge--Kutta evaluations use the physical time of each stage. - -The native-coordinate equations retain all equilibrium covariant magnetic -components, including VMEC's radial component. The simplified Boozer model -uses ``B_cov = I dtheta + G dzeta`` and neglects its radial covariant component. -Boozer stores the mass-normalized moment ``v_perp**2/(2 B0)``; native -``GuidingCenterMu`` stores the physical moment in J/T. - -Kinetic energy can change through wave work while magnetic moment stays -constant. Inferring magnetic moment from the fixed birth energy would suppress -that exchange. Native perturbed traces therefore use the existing five-state -``GuidingCenterMu`` function with the usual adaptive solver. - -Analytical modes ----------------- - -``essos.perturbations.AnalyticalAlfvenMode`` supplies +``essos.perturbations.AnalyticalAlfvenMode`` has .. math:: - \Phi &= \widehat\Phi f(s)\sin(m\theta_B-n\zeta_B+\omega t+\varphi),\\ - \alpha &= \frac{n-m\iota}{\omega(G+\iota I)}\Phi. - -The latter relation enforces the linear ideal condition -``B0 . delta E = 0``. The toroidal harmonic number ``n`` includes the full -field-period factor. The default radial factor ``s**(m/2)`` makes the angular -harmonic smooth on axis; an optional Gaussian localizes it radially. -``AlfvenSpectrum`` superposes modes with their individual phases and frequencies. - -``AnalyticalVmecAlfvenMode`` instead defines its harmonic in VMEC angles. -To trace the identical Boozer wave in VMEC, use ``MappedBoozerPerturbation`` -with ``VmecBoozerMap`` from the same ``booz_xform_jax`` calculation. Its -derivatives include the coordinate-map chain rule. The current map requires -stellarator symmetry. - -The Paul comparison uses a radially uniform potential, which is singular on -axis for nonzero ``m``. Its default stopping surface is ``s=1e-8``. Inner stops, -outer-boundary losses and numerical failures are separate diagnostics; inner -stops enter the paper-style loss fraction. They are not a coordinate cure or -a convergence test of that cutoff. Smooth analytical modes need no such stop. -Native perturbed tracing currently supports collisionless GC models inside -the equilibrium. Exterior continuation requires an exterior wave model. - -Small CPU example ------------------ - -From the checkout root: - -.. code-block:: bash - - python -m examples.particle_tracing.vmec_alfven_cpu_smoke - -This follows two particles without and with a smooth VMEC-angle mode: four -trajectories, 0.2 microseconds each, under a 120-second process cap including -compilation. It uses ``GuidingCenterAdaptative`` and saves to -``examples/benchmarks/results/vmec_alfven_cpu_smoke``. The example checks finite -trajectories, baseline energy conservation and constant magnetic moment. - -.. image:: _static/analytical_perturbations/vmec_alfven_smoke.png - :alt: Short unperturbed and perturbed VMEC guiding-centre trajectories - -Electromagnetic verification ----------------------------- - -.. code-block:: bash - - python -m examples.benchmarks.alfven_gc_verification - -The 120-second CPU benchmark checks two coupled harmonics at four relative -phases and two solver tolerances, plus uniform induction: 18 short trajectories. -It verifies rotating-frame energy--momentum exchange, the time-dependent -phase-space conservation identity, and an exact inductive trajectory. A -diagnostic that removes induction demonstrates that the conservation checks -detect a missing term. The production RHS is used for every actual trace. -These are analytic verification cases inspired by -`Bierwage, White and Matsuyama (2022) `_, -not a reproduction of their tokamak equilibrium. - -.. image:: _static/analytical_perturbations/gc_verification.png - :alt: Conservation checks, physical wave work and an exact inductive trajectory + \Phi=\hat\Phi f(s)\sin(m\theta_B-n\zeta_B+\omega t+\varphi),\qquad + \alpha=\frac{n-m\iota}{\omega(G+\iota I)}\Phi, + +which enforces :math:`\mathbf B_0\cdot\delta\mathbf E=0` (:math:`n` includes the field-period +factor). By default :math:`f=s^{m/2}`, smooth on axis; ``radial_center``/``radial_width`` give a +Gaussian instead. ``AlfvenSpectrum`` superposes modes. ``AnalyticalVmecAlfvenMode`` defines the +harmonic in VMEC angles, and ``MappedBoozerPerturbation`` with ``VmecBoozerMap`` (from +``booz_xform_jax``, stellarator symmetry) evaluates the identical Boozer wave in VMEC, with the +chain rule of the map. A new mode, including a computed one, only implements ``potentials``. + +The radially uniform harmonic of Paul et al. (``regularize_axis=False``) is singular on axis for +:math:`m>0`. Tracing stops there at ``axis_stop_s`` (default :math:`10^{-8}`) and reports the stops +(``axis_stop_times``; status 6 in ``Tracing``) apart from LCFS exits and failures; +``loss_fractions(include_axis=True)`` counts both, as the paper does. Perturbed native tracing +supports collisionless guiding centres inside the equilibrium. + +Verification +------------ + +``tests/test_perturbations.py`` and ``tests/test_native_gc_perturbations.py`` check the model +against independent laws (after `Bierwage, White and Matsuyama (2022) +`_, on analytic fields): :math:`E_\parallel=0`; the +rotating-frame invariant :math:`H-(\omega/n)P_\zeta` for two coupled harmonics, with a control +showing it detects a missing inductive term; Liouville's theorem for the time-dependent +phase-space density; the exact trajectory in a uniform inductive field; the work identity +:math:`dH/dt=q\,\mathbf v\cdot\mathbf E` in a sheared nonorthogonal chart; coordinate +covariance; gradients with respect to the amplitude; and the zero-amplitude limit. Paul alpha-loss comparison -------------------------- -The collisionless comparison follows -`Paul, Mynick and Bhattacharjee (2023), Table 2 -`_: vacuum QA, ``m=15``, ``n=7``, -source frequency 399000 rad/s, edge proxy ``m*alpha_hat/a=1e-3``, 3.52 MeV, -and 1 ms. The equilibrium is scaled to minor radius 1.7 m and axis -``B00=5.86 T``. Boozer suppresses QS-breaking field-strength harmonics; -VMEC retains the full equilibrium. - -The saved comparison contains 100 common initial coordinate/pitch proposals, -with physical-volume importance weights computed for each background. The -explicit historical convention maps angles and parallel velocity together -with frequency and potential; it is a comparison assumption, not confirmation -of the original paper runtime. The saved run uses angular frequency -399000 -rad/s, potential amplitude -3725.818890765528 V and the documented historical -library mass 6.69509884346e-27 kg at fixed 3.52 MeV. Normal ESSOS mass defaults -are unchanged. No island-width fit or fitted orbit invariant is used. - -.. list-table:: Weighted losses at 1 ms +``examples/particle_tracing/paul_alfven_benchmark.py`` follows `Paul, Mynick and +Bhattacharjee (2023), Table 2 `_: vacuum QA, +:math:`m=15`, :math:`n=7`, 399000 rad/s, edge :math:`m\hat\alpha/a=10^{-3}`, 3.52 MeV, 1 ms, +in a Boozer background without QS-breaking harmonics and in the full VMEC equilibrium +(scaled to :math:`a=1.7` m, :math:`B_{00}=5.86` T), with the same markers weighted to uniform +physical volume. It needs ``pip install -e '.[booz]'``. Edit ``PARTICLES``, ``HISTORICAL`` and +``PLOT`` at the top of the script; ``HISTORICAL`` applies the sign and alpha-mass conventions of +the 2023 SIMSOPT adapter. The table is the run with ``PARTICLES = 100`` and ``HISTORICAL = True`` with the bundled ``wout_LandremanPaul2021_QA_reactorScale_lowres.nc`` (tens of +minutes on one CPU core); the unperturbed curves of the two backgrounds coincide in the figure. +The waves lose 14 markers through the LCFS in both backgrounds, and eight (Boozer) or ten (VMEC) at the inner stop. + +.. list-table:: Weighted losses at 1 ms (100 markers; paper used 5000) :header-rows: 1 - :widths: 25 18 15 25 12 * - Background - Case @@ -161,100 +95,27 @@ are unchanged. No island-width fit or fitted orbit invariant is used. * - Boozer / Perfect QS - Unperturbed - 12.25% - - 7.16--20.16% + - 7.16-20.16% - 6.6% * - Boozer / Perfect QS - Wave - - 21.53% - - 14.57--30.62% + - 22.29% + - 15.21-31.45% - 16.2% * - VMEC / full equilibrium - Unperturbed - 12.25% - - 7.16--20.16% + - 7.16-20.16% - 8.3% * - VMEC / full equilibrium - Wave - - 20.56% - - 13.77--29.56% + - 24.30% + - 16.91-33.62% - 19.4% -All four saved cases have zero failed markers. Boozer wave losses comprise -13 LCFS exits and eight inner stops; VMEC has 13 and seven, respectively. -The maximum Boozer invariant drift is 8.42e-9; native baseline relative energy -change is 8.09e-6 and native wave relative magnetic-moment change is zero. -The original 600-second CPU job completed three cases; a separate native -resume completed the wave case in 549.71 seconds under another 600-second cap. - .. image:: _static/analytical_perturbations/paul_loss_100.png - :alt: Four loss curves with matching Perfect QS and full-equilibrium paper endpoints - -The crosses represent four published endpoints, one for each background/case. -The paper used 5000 particles. This is a small comparison, not established -quantitative paper reproduction: the exact published equilibrium/runtime, -equilibrium-resolution convergence and inner-cutoff sensitivity remain -unconfirmed. Sampling intervals exclude these systematic uncertainties. - -Recovering the figures ----------------------- - -Compact reference data live in ``examples/benchmarks/references``: - -* ``paul_loss_100.npz`` contains the four weighted loss curves; - ``paul_loss_100.json`` records endpoints, intervals, inputs and checks. -* ``paul_births_100.npz`` preserves the exact 100 already-converted births. -* ``gc_verification.npz/.json`` and ``vmec_alfven_smoke.npz/.json`` preserve - the short verification/example data. -* The three TOML files record the two published Table 2 columns and the - historical particle-mass option. - -Regenerate all three PNG/SVG figures without tracing particles: - -.. code-block:: bash - - python -m examples.benchmarks.plot_alfven_results - -The default destination is ``docs/_static/analytical_perturbations``. To review -regenerated images separately, pass ``--output /path/to/figures``. - -Rerunning the loss benchmark ---------------------------- - -The reference equilibrium is committed at -``examples/input_files/wout_LandremanPaul2021_QA_lowres.nc``, SHA256 -``4d301a3c32aa6b12f0c13f2c440d223427275fb00862fac3e64e52dc8421c23c``. -Both loss runners require the optional ``booz_xform_jax`` dependency: - -.. code-block:: bash - - python -m pip install -e '.[booz]' - -Prepare the four-case job below without running trajectories. The CPU budget -is 1200 seconds for the complete job; use ``--platform gpu`` on a GPU machine. - -.. code-block:: bash - - python -m examples.benchmarks.paul_boozer_vmec_benchmark \ - --dry-run --particles 100 --platform cpu --wall-seconds 1200 \ - --batch-size 16 --diagnostic-batch-size 32 \ - --source-convention simsopt_2023 --particle-model simsopt_2023 \ - --births examples/benchmarks/references/paul_births_100.npz \ - --wout examples/input_files/wout_LandremanPaul2021_QA_lowres.nc \ - --output examples/benchmarks/results/paul_100_rerun - -Remove ``--dry-run`` to execute the prepared job. The launcher preserves -existing completed results and refuses to overwrite a completed Boozer run. -Generated output stays ignored by Git. The comparison module verifies matching -births, mass, energy, equilibrium hash and wave parameters before plotting: - -.. code-block:: bash - - python -m examples.benchmarks.paul_boozer_vmec_loss_comparison \ - --particles 100 \ - --boozer examples/benchmarks/results/paul_100_rerun/boozer \ - --vmec examples/benchmarks/results/paul_100_rerun/vmec \ - --output examples/benchmarks/results/paul_100_rerun/comparison + :alt: Loss curves for Boozer and VMEC backgrounds without and with the wave -This last command only postprocesses completed results. Its output includes -``boozer_vmec_loss_100.png/.svg``, ``comparison.csv``, ``summary.json`` and -``loss_curves.npz``. Failed or unfinished cases are rejected. +Crosses mark the published endpoints. The exact published equilibrium and runtime are unknown, and +the intervals contain sampling noise only (no equilibrium-resolution or cutoff convergence). This is +a consistency check, not a quantitative reproduction. diff --git a/essos/boozer.py b/essos/boozer.py index 715fd35a..05e0e6bb 100644 --- a/essos/boozer.py +++ b/essos/boozer.py @@ -21,6 +21,7 @@ from jax.sharding import Mesh, NamedSharding, PartitionSpec from essos.background_species import nu_D_ab, nu_par_ab, d_nu_par_ab, nu_s_ab, JOULE_PER_EV +from essos.perturbations import BoozerPerturbation jax.config.update("jax_enable_x64", True) @@ -601,22 +602,16 @@ def trace_boozer(field, s, theta, zeta, pitch, *, speed, mass, charge, tmax, tim stays below ``tolerance`` (in ``sqrt(s)`` and ``zeta`` units and relative to the speed for ``v_par``); ``timestep`` is then only the first trial step. - ``perturbation`` accepts a ``BoozerPerturbation`` from essos.perturbations. - ``speed`` may be a positive scalar or one positive birth speed per marker - (needed to initialize sections at a common wave-frame invariant). - Every RK stage uses its own physical time. With modes, ``energy_error`` - is None: physical wave work is reported as ``kinetic_energy_change``. - Check a wave-frame invariant in exact-QS single-mode benchmarks instead. - Modes plus collisions use a fixed RK orbit step followed by the existing - Boozer Euler-Maruyama speed/pitch kick. This is velocity-space collision - splitting, without GC spatial diffusion, using the main-branch collision - coefficients and operator. - A singular analytical mode can supply an inner boundary. Axis encounters - stop there and populate ``axis_stop_times``; ``lost`` retains LCFS exits. - ``loss_fractions(include_axis=True)`` additionally counts axis stops. + ``perturbation`` is a ``BoozerPerturbation`` (essos.perturbations); every RK stage uses its + own physical time. ``speed`` may be a scalar or one birth speed per marker. With a wave, + ``energy_error`` is None and the physical wave work is ``kinetic_energy_change``; check a + wave-frame invariant in exact-QS single-mode cases instead. Waves plus collisions need a + fixed RK method and use the existing Euler-Maruyama speed/pitch kick (no GC spatial + diffusion). A singular mode supplies an inner boundary: axis encounters stop there and + fill ``axis_stop_times``, while ``lost`` keeps LCFS exits; + ``loss_fractions(include_axis=True)`` counts both. """ if perturbation is not None: - from essos.perturbations import BoozerPerturbation if not isinstance(perturbation, BoozerPerturbation): raise TypeError("perturbation must implement BoozerPerturbation") if species is not None and method.startswith("adaptive"): diff --git a/essos/gc_perturbations.py b/essos/gc_perturbations.py index d0aff9c3..2001ff57 100644 --- a/essos/gc_perturbations.py +++ b/essos/gc_perturbations.py @@ -15,26 +15,11 @@ import numpy as np from essos.boozer import _evaluate, _spline -from essos.perturbations import AnalyticalAlfvenMode, BoozerPerturbation +from essos.perturbations import AnalyticalAlfvenMode, BoozerPerturbation, Perturbation -class GuidingCenterPerturbation(eqx.Module): - """Return (alpha [m], Phi [V]) in the background's native coordinates.""" - - def potentials(self, field, point, t): - raise NotImplementedError - - def axis_stop_threshold(self): - return None - - def derivatives(self, field, point, t): - """Potentials and their Jacobian in (x1,x2,x3,t), shape (2,4).""" - def evaluate(z): - value = self.potentials(field, z[:3], z[3]) - return value, value - - derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(point, t)) - return value, derivative +class GuidingCenterPerturbation(Perturbation): + """Potentials (alpha [m], Phi [V]) at the background's native point.""" class AnalyticalVmecAlfvenMode(GuidingCenterPerturbation): @@ -59,9 +44,7 @@ def potentials(self, field, point, t): s, theta, phi = point mode = self.mode harmonic = s**(mode.m/2)*jnp.sin(mode.m*theta-mode.n*phi+mode.omega*t+mode.phase) - envelope = (1. if mode.radial_width is None else - jnp.exp(-((s-mode.radial_center)/mode.radial_width)**2)) - potential = mode.amplitude*envelope*harmonic + potential = mode.amplitude*mode.envelope(s)*harmonic B = field.AbsB(point) Bcontra = field.B_contravariant(point) alpha = (mode.n*Bcontra[2]-mode.m*Bcontra[1])*potential/(mode.omega*B**2) diff --git a/essos/perturbations.py b/essos/perturbations.py index 2fde6ce0..f40915f3 100644 --- a/essos/perturbations.py +++ b/essos/perturbations.py @@ -15,31 +15,37 @@ import numpy as np -class BoozerPerturbation(eqx.Module): - """Interface for a future computed-mode adapter, including FAX. +class Perturbation(eqx.Module): + """Prescribed ``potentials(field, point, t) -> (alpha [m], Phi [V])``. - ``potentials(field, xyz, t)`` returns ``(alpha [m], Phi [V])``; - xyz is the regular chart ``(sqrt(s) cos(theta), sqrt(s) sin(theta), zeta)``. - The equilibrium covariant field is ``I dtheta + G dzeta`` (K=0). + ``axis_stop_threshold`` is an optional inner boundary in normalized toroidal + flux (None disables it); ``derivatives`` returns the potentials and their + Jacobian in (point, time), shape (2, 4). """ - def potentials(self, field, xyz, t): + def potentials(self, field, point, t): raise NotImplementedError def axis_stop_threshold(self): - """Optional inner boundary in normalized toroidal flux; None disables it.""" return None - def derivatives(self, field, xyz, t): - """Potentials and their Jacobian in (u, w, zeta, time), shape (2, 4).""" + def derivatives(self, field, point, t): def evaluate(z): value = self.potentials(field, z[:3], z[3]) return value, value - derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(xyz, t)) + derivative, value = jax.jacfwd(evaluate, has_aux=True)(jnp.append(point, t)) return value, derivative +class BoozerPerturbation(Perturbation): + """Perturbation of ``trace_boozer``; ``point`` is the regular chart + ``(sqrt(s) cos(theta), sqrt(s) sin(theta), zeta)``. The equilibrium + covariant field is ``I dtheta + G dzeta`` (K=0). A computed-mode adapter, + including FAX, only needs to implement ``potentials``. + """ + + class AnalyticalAlfvenMode(BoozerPerturbation): """Phi = amplitude * envelope(s) * sin(m theta - n zeta + omega t + phase). @@ -68,29 +74,14 @@ class AnalyticalAlfvenMode(BoozerPerturbation): def __init__(self, m, n, omega, amplitude, *, phase=0., regularize_axis=True, radial_center=0.5, radial_width=None, axis_stop_s=1e-8): - for name, value in (("m", m), ("n", n)): - if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)): - raise ValueError(f"{name} must be an integer") - if m < 0: - raise ValueError("m must be nonnegative") - for name, value in (("omega", omega), ("amplitude", amplitude), - ("phase", phase), ("radial_center", radial_center)): - if isinstance(value, jax.core.Tracer): - if value.ndim: - raise ValueError(f"{name} must be a scalar") - continue - if np.ndim(value) or not np.isfinite(value): - raise ValueError(f"{name} must be a finite scalar") + if any(isinstance(v, (bool, np.bool_)) or not isinstance(v, (int, np.integer)) for v in (m, n)) or m < 0: + raise ValueError("m must be a nonnegative integer and n an integer") if not isinstance(omega, jax.core.Tracer) and omega == 0: raise ValueError("omega must be nonzero for the ideal Alfven relation") - if radial_width is not None and (np.ndim(radial_width) or not np.isfinite(radial_width) - or radial_width <= 0): - raise ValueError("radial_width must be positive and finite") - if not isinstance(regularize_axis, (bool, np.bool_)): - raise ValueError("regularize_axis must be boolean") - if axis_stop_s is not None and (np.ndim(axis_stop_s) or not np.isfinite(axis_stop_s) - or not 0 < axis_stop_s < 1): - raise ValueError("axis_stop_s must be None or a finite scalar strictly between 0 and 1") + if radial_width is not None and not radial_width > 0: + raise ValueError("radial_width must be positive") + if axis_stop_s is not None and not 0 < axis_stop_s < 1: + raise ValueError("axis_stop_s must be None or strictly between 0 and 1") self.m, self.n = int(m), int(n) self.omega, self.amplitude, self.phase = map(jnp.asarray, (omega, amplitude, phase)) self.regularize_axis = bool(regularize_axis) @@ -98,6 +89,11 @@ def __init__(self, m, n, omega, amplitude, *, phase=0., regularize_axis=True, self.radial_width = None if radial_width is None else float(radial_width) self.axis_stop_s = None if axis_stop_s is None else float(axis_stop_s) + def envelope(self, s): + if self.radial_width is None: + return 1. + return jnp.exp(-((s-self.radial_center)/self.radial_width)**2) + def axis_stop_threshold(self): if self.regularize_axis or self.m == 0 or self.axis_stop_s is None: return None @@ -112,8 +108,7 @@ def potentials(self, field, xyz, t): if not self.regularize_axis and self.m: harmonic = jnp.where(s > 0, harmonic / jnp.where(s > 0, s, 1.)**(self.m/2), jnp.where(self.amplitude == 0, 0., jnp.nan)) - envelope = 1. if self.radial_width is None else jnp.exp(-((s-self.radial_center)/self.radial_width)**2) - phi = self.amplitude * envelope * harmonic + phi = self.amplitude * self.envelope(s) * harmonic (iota, G, I), _ = field.profiles(s) alpha = (self.n - self.m*iota) * phi / (self.omega*(G+iota*I)) return jnp.stack([alpha, phi]) diff --git a/examples/benchmarks/alfven_gc_verification.py b/examples/benchmarks/alfven_gc_verification.py deleted file mode 100644 index f2a2838b..00000000 --- a/examples/benchmarks/alfven_gc_verification.py +++ /dev/null @@ -1,322 +0,0 @@ -"""Small CPU checks of the electromagnetic GC equations, inspired by ORBIT. - -Run ``python -m examples.benchmarks.alfven_gc_verification`` from the checkout. -The CLI has a 120 s wall limit including imports and compilation, and traces -18 trajectories in total. It uses the existing adaptive8 integrator. This -adapts the conservation tests of Bierwage, White & Matsuyama (2022), -https://arxiv.org/abs/2205.11280, to analytic fields; it does not reproduce -their JT-60U equilibrium or numerical figures. No collisions are involved. -""" - -import argparse -import json -import os -from pathlib import Path -import threading -import time - - -if __name__ == "__main__": - os.environ.update(JAX_PLATFORMS="cpu", CUDA_VISIBLE_DEVICES="-1", - ESSOS_CPU_DEVICES="1", OMP_NUM_THREADS="1", - OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1") - _started = time.perf_counter() - - def _stop(): - print("GC verification stopped at its 120-second CPU limit", flush=True) - os._exit(124) - - _deadline = threading.Timer(120., _stop) - _deadline.daemon = True - _deadline.start() - -import jax -import jax.numpy as jnp -import numpy as np - -from essos.boozer import BoozerField, guiding_center_rhs, trace_boozer -from essos.constants import ALPHA_PARTICLE_MASS as MASS, ALPHA_PARTICLE_CHARGE as CHARGE, ONE_EV -from essos.perturbations import (AlfvenSpectrum, AnalyticalAlfvenMode, - BoozerPerturbation, poloidal_flux) - - -SPEED = np.sqrt(2*3.5e6*ONE_EV/MASS) -PHASES = np.arange(4)*np.pi/2 -OMEGA = 9e5 -N = 2 -TOLERANCES = (1e-6, 1e-10) -DEFAULT_OUTPUT = Path("examples/benchmarks/results/alfven_gc_verification") - - -def equilibrium(*, uniform=False): - """Analytic axisymmetric fixture, with nonconstant current profiles.""" - s = np.linspace(.005, .995, 32) - if uniform: - return BoozerField.from_booz(s, np.array([5.+0*s]), [0], [0], - 0*s, 40.+0*s, 0*s, -40., 1, angle_grid=None) - return BoozerField.from_booz(s, np.stack([5.+0*s, -np.sqrt(s)]), [0, 1], [0, 0], - .4+.1*s, 40.+.8*s, .8*s, -40., 1, angle_grid=None) - - -def spectrum(relative_phase): - """Adjacent m, common n and omega: a single toroidally rotating pattern.""" - return AlfvenSpectrum(*[ - AnalyticalAlfvenMode(m, N, OMEGA, 3e4, phase=phase, - radial_center=.4, radial_width=.5) - for m, phase in ((3, .3), (4, .3+relative_phase))]) - - -def energy_momentum(field, wave, y, mu, t): - s = y[0]**2+y[1]**2 - B = field.modB(s, jnp.arctan2(y[1], y[0]), y[2]) - (_, G, _), _ = field.profiles(s) - alpha, phi = wave.potentials(field, y[:3], t) - H = MASS*(.5*y[3]**2+mu*B)+CHARGE*phi - P = G*(MASS*y[3]/B+CHARGE*alpha)-CHARGE*poloidal_flux(field, s) - return jnp.stack([H, P]) - - -def phase_space_density(field, wave, y, t): - """GC volume density in (u,w,zeta,v_parallel), up to a constant factor. - - From gamma_theta=q*psi0*s+k*I, gamma_zeta=-q*psi_P+k*G, - k=M*v_parallel/B+q*alpha, and ds dtheta=2 du dw, the density is - 2*M*q*psi0/B * [G+iota*I+(M*v/(q*B)+alpha)*(G*I'-I*G')/psi0]. - Only the constant 2*M*q*psi0 is omitted below. No radial factor is - needed in this regular chart. The density itself is time dependent. - """ - s = y[0]**2+y[1]**2 - B = field.modB(s, jnp.arctan2(y[1], y[0]), y[2]) - (iota, G, I), (_, Gs, Is) = field.profiles(s) - alpha = wave.potentials(field, y[:3], t)[0] - return (G+iota*I+(MASS*y[3]/(CHARGE*B)+alpha)*(G*Is-I*Gs)/field.psi0)/B - - -@jax.jit -def differential_checks(field, wave, y, mu, t): - """Normalized invariant/Liouville residuals and a missing-term control. - - The control cancels only the inductive acceleration in this diagnostic; - the production RHS is always used unchanged for all actual trajectories. - """ - invariant = lambda y, t: energy_momentum(field, wave, y, mu, t)@jnp.array([1., -OMEGA/N]) - density = lambda y, t: phase_space_density(field, wave, y, t) - rhs = lambda y: guiding_center_rhs(field, y, mu, MASS, CHARGE, t=t, perturbation=wave) - gradient = jax.grad(invariant, 0)(y, t) - rate = gradient@rhs(y)+jax.grad(invariant, 1)(y, t) - source = jax.grad(density, 1)(y, t) - divergence_terms = jnp.diag(jax.jacfwd(lambda y: density(y, t)*rhs(y))(y)) - volume_rate = source+jnp.sum(divergence_terms) - volume_scale = jnp.maximum(abs(source)+jnp.sum(abs(divergence_terms)), 1e-30) - energy_scale = abs(energy_momentum(field, wave, y, mu, t)[0])*OMEGA - B = field.modB(y[0]**2+y[1]**2, jnp.arctan2(y[1], y[0]), y[2]) - alpha_t = wave.derivatives(field, y[:3], t)[1][0, 3] - removed_acceleration = CHARGE*B/MASS*alpha_t - broken_rate = rate+gradient[3]*removed_acceleration - broken_volume = volume_rate+jax.grad(density, 0)(y, t)[3]*removed_acceleration - return jnp.array([rate/energy_scale, volume_rate/volume_scale, - broken_rate/energy_scale, broken_volume/volume_scale]) - - -class UniformInduction(BoozerPerturbation): - """Exact nonideal calibration: uniform alpha(t), Phi=0, constant B0.""" - - amplitude: float = .003 - omega: float = 7.5e5 - phase: float = .4 - - def potentials(self, field, xyz, t): - alpha = self.amplitude*jnp.sin(self.omega*t+self.phase) - return jnp.stack([alpha, jnp.zeros_like(alpha)]) - - def exact(self, times, v0, zeta0, *, B=5., G=40.): - times = np.asarray(times) - k = CHARGE*B/MASS*self.amplitude - v = v0-k*(np.sin(self.omega*times+self.phase)-np.sin(self.phase)) - zeta = zeta0+B/G*((v0+k*np.sin(self.phase))*times - +k/self.omega*(np.cos(self.omega*times+self.phase)-np.cos(self.phase))) - return v, zeta - - -def trace_wave(field, wave, tolerance, *, tmax=4e-5, n_save=65): - s, theta, zeta, pitch = np.array([[.3, .43], [.2, 1.4], [0., .3], [.65, -.7]]) - mu = SPEED**2*(1-pitch**2)/(2*np.asarray(jax.vmap(field.modB)(s, theta, zeta))) - trace = trace_boozer(field, s, theta, zeta, pitch, speed=SPEED, mass=MASS, charge=CHARGE, - tmax=tmax, timestep=2e-7, n_save=n_save, method="adaptive8", - tolerance=tolerance, perturbation=wave, progress=False, - compact=False, devices=jax.devices()[:1]) - check_trace(trace) - s, theta, zeta, vpar, _ = np.moveaxis(trace.states, -1, 0) - ys = jnp.stack([np.sqrt(s)*np.cos(theta), np.sqrt(s)*np.sin(theta), zeta, vpar], axis=-1) - values = jax.vmap(lambda y, mu: jax.vmap( - lambda state, t: energy_momentum(field, wave, state, mu, t))(y, trace.times))(ys, mu) - values = np.asarray(values) - H, P = values[..., 0], values[..., 1] - K = H-OMEGA/N*P - # Normalize by initial physical energy, avoiding a nearly zero K denominator. - residual = (K-K[:, :1])/abs(H[:, :1]) - return trace, H, P, residual - - -def trace_induction(tolerance, *, tmax=4e-5, n_save=65): - wave = UniformInduction() - trace = trace_boozer(equilibrium(uniform=True), [.3], [.2], [.3], [.65], - speed=SPEED, mass=MASS, charge=CHARGE, tmax=tmax, - timestep=2e-7, n_save=n_save, method="adaptive8", tolerance=tolerance, - perturbation=wave, progress=False, compact=False, devices=jax.devices()[:1]) - check_trace(trace) - exact_v, exact_zeta = wave.exact(trace.times, .65*SPEED, .3) - return trace, exact_v, exact_zeta - - -def check_trace(trace): - if (trace.failed.any() or trace.lost.any() or np.any(trace.axis_stop_times >= 0) - or not np.isfinite(trace.states).all()): - raise RuntimeError("Verification requires finite, complete, confined trajectories") - - -def run(output): - field = equilibrium() - # Fixed deterministic off-axis points, both directions of parallel velocity. - points = jnp.array([[.45, .27, -.3, .7*SPEED], [.3, -.4, .7, -.65*SPEED], - [-.5, .2, 1.2, .5*SPEED], [.2, .6, -.8, -.8*SPEED]]) - times = jnp.array([0., 1.3e-6, 4.7e-6, 9e-6]) - mu = .5*SPEED**2/(2*5.) - arrays, records = {}, [] - for phase in PHASES: - wave = spectrum(phase) - local = np.asarray(jax.vmap(lambda y, t: differential_checks(field, wave, y, mu, t))(points, times)) - phase_records = [] - for tolerance in TOLERANCES: - trace, H, P, residual = trace_wave(field, wave, tolerance) - phase_records.append(dict(tolerance=tolerance, - max_invariant_error=float(np.max(abs(residual))), - max_relative_energy_exchange=float(np.max(abs((H-H[:, :1])/H[:, :1]))))) - suffix = f"phase{len(records)}_tol{tolerance:g}" - arrays.update({f"{suffix}_states": trace.states, f"{suffix}_energy": H, - f"{suffix}_momentum": P, f"{suffix}_invariant_error": residual}) - arrays[f"phase{len(records)}_local_checks"] = local - records.append(dict(relative_phase_rad=float(phase), - max_local_invariant_residual=float(np.max(abs(local[:, 0]))), - max_liouville_residual=float(np.max(abs(local[:, 1]))), - missing_induction_invariant_residual=float(np.max(abs(local[:, 2]))), - missing_induction_liouville_residual=float(np.max(abs(local[:, 3]))), - traces=phase_records)) - print(f"Completed harmonic phase {phase/np.pi:g} pi", flush=True) - induction = [] - for tolerance in TOLERANCES: - trace, exact_v, exact_zeta = trace_induction(tolerance) - velocity_error = float(np.max(abs(trace.states[0, :, 3]-exact_v))/SPEED) - zeta_error = float(np.max(abs(trace.states[0, :, 2]-exact_zeta))) - induction.append(dict(tolerance=tolerance, max_velocity_error_over_birth_speed=velocity_error, - max_zeta_error_rad=zeta_error)) - arrays[f"induction_tol{tolerance:g}"] = trace.states[0] - arrays.update(times=trace.times, induction_exact_v=exact_v, induction_exact_zeta=exact_zeta) - summary = dict(reference="https://arxiv.org/abs/2205.11280", exact_paper_reproduction=False, - description="ORBIT-style conservation checks on an analytic axisymmetric fixture", - method="adaptive8", platform=jax.devices()[0].platform, trajectories=18, - particles_per_wave_case=2, simulated_time_s=float(trace.times[-1]), - tolerances=list(TOLERANCES), time_limit_s=120, - wave_cases=records, uniform_induction=induction) - # Acceptance limits are absolute checks, not an assumed monotonic error trend - # once roundoff dominates. The two tolerances are reported for inspection. - passed = (all(r["max_local_invariant_residual"] < 1e-12 and r["max_liouville_residual"] < 1e-12 - and r["missing_induction_invariant_residual"] > 1e-6 - and r["missing_induction_liouville_residual"] > 1e-10 - and r["traces"][-1]["max_invariant_error"] < 1e-8 for r in records) - and induction[-1]["max_velocity_error_over_birth_speed"] < 1e-8 - and induction[-1]["max_zeta_error_rad"] < 1e-7) - summary["passed"] = bool(passed) - output.mkdir(parents=True, exist_ok=True) - np.savez_compressed(output/"trajectories.npz", **arrays) - (output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - if not passed: - raise AssertionError(f"GC verification failed; inspect {output/'summary.json'}") - return summary, arrays - - -def plot(output, summary, arrays): - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - - fig, axes = plt.subplots(2, 2, figsize=(11, 7.5), constrained_layout=True) - times = arrays["times"]*1e6 - phase_labels = [r"$\Delta\phi=0$", r"$\Delta\phi=\pi/2$", - r"$\Delta\phi=\pi$", r"$\Delta\phi=3\pi/2$"] - for index, record in enumerate(summary["wave_cases"]): - color = f"C{index}" - label = phase_labels[index] - for tolerance, style in zip(summary["tolerances"], ("--", "-")): - suffix = f"phase{index}_tol{tolerance:g}" - residual = arrays[f"{suffix}_invariant_error"] - axes[0, 0].semilogy(times, np.maximum(abs(residual).max(axis=0), 1e-16), - style, color=color, label=label if style == "-" else None) - H = arrays[f"phase{index}_tol{summary['tolerances'][-1]:g}_energy"] - P = arrays[f"phase{index}_tol{summary['tolerances'][-1]:g}_momentum"] - for marker in range(H.shape[0]): - axes[0, 1].plot(OMEGA/N*(P[marker]-P[marker, 0])/(1e3*ONE_EV), - (H[marker]-H[marker, 0])/(1e3*ONE_EV), color=color, - label=label if marker == 0 else None) - local = arrays[f"phase{index}_local_checks"] - axes[1, 0].scatter([index]*len(local), np.maximum(abs(local[:, 1]), 1e-17), - color=color, marker="o", label="GC RHS" if index == 0 else None) - axes[1, 0].scatter([index]*len(local), abs(local[:, 3]), color=color, marker="x", - label="Inductive term removed (diagnostic only)" if index == 0 else None) - axes[0, 0].set(xlabel="Time [microseconds]", ylabel=r"$|K(t)-K(0)|/|H(0)|$", - title="Two harmonics: rotating-frame invariant") - axes[0, 0].legend(fontsize=8) - axes[0, 0].text(.04, .03, "Solid: tolerance 1e-10; dashed: 1e-6", transform=axes[0, 0].transAxes, fontsize=8) - limits = axes[0, 1].get_xlim() - axes[0, 1].plot(limits, limits, "k:", label="Exact exchange relation") - axes[0, 1].set(xlabel=r"$(\omega/n)\,\Delta P_\zeta$ [keV]", ylabel=r"$\Delta H$ [keV]", - title="Physical energy and momentum exchange") - axes[0, 1].legend(fontsize=8) - axes[1, 0].set(yscale="log", xlabel="Relative harmonic phase", ylabel="Normalized Liouville residual", - xticks=range(4), xticklabels=["0", "pi/2", "pi", "3pi/2"], - title="Phase-space conservation: four points per phase") - axes[1, 0].legend(fontsize=7) - dense_times = np.linspace(arrays["times"][0], arrays["times"][-1], 1001) - # Dense evaluation of the analytic curve only; no additional trajectories. - dense_v, _ = UniformInduction().exact(dense_times, .65*SPEED, .3) - axes[1, 1].plot(dense_times*1e6, dense_v/1e6, "k-", label="Exact") - tight = arrays[f"induction_tol{summary['tolerances'][-1]:g}"] - axes[1, 1].plot(times[::2], tight[::2, 3]/1e6, "o", ms=3, mfc="none", label="Existing adaptive8 GC") - error = summary["uniform_induction"][-1] - axes[1, 1].text(.04, .04, f"max |dv|/v_birth = {error['max_velocity_error_over_birth_speed']:.2e}\n" - f"max |dzeta| = {error['max_zeta_error_rad']:.2e} rad", - transform=axes[1, 1].transAxes, fontsize=8) - axes[1, 1].set(xlabel="Time [microseconds]", ylabel="Parallel velocity [million m/s]", - title="Uniform inductive field: exact trajectory") - axes[1, 1].legend(fontsize=8) - for ax in axes.flat: - ax.grid(alpha=.2) - fig.suptitle("GC electromagnetic corrections: 18 CPU trajectories; analytic equilibrium\n" - "ORBIT-style verification, not a reproduction of the JT-60U figures", fontsize=12) - for extension in ("png", "svg"): - fig.savefig(output/f"gc_verification.{extension}", dpi=170) - plt.close(fig) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) - parser.add_argument("--report-only", action="store_true", help="Redraw saved data without tracing") - args = parser.parse_args() - if args.report_only: - summary = json.loads((args.output/"summary.json").read_text()) - with np.load(args.output/"trajectories.npz") as data: - arrays = dict(data) - else: - summary, arrays = run(args.output) - summary["elapsed_seconds_before_plot"] = time.perf_counter()-_started - (args.output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - plot(args.output, summary, arrays) - print(json.dumps(summary, indent=2), flush=True) - - -if __name__ == "__main__": - try: - main() - finally: - _deadline.cancel() diff --git a/examples/benchmarks/paul_boozer_vmec_benchmark.py b/examples/benchmarks/paul_boozer_vmec_benchmark.py deleted file mode 100644 index 8af709a3..00000000 --- a/examples/benchmarks/paul_boozer_vmec_benchmark.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Run the four-case Paul benchmark with 500 particles per case by default. - -From the checkout root, prepare the job without importing JAX or tracing: - python -m examples.benchmarks.paul_boozer_vmec_benchmark --dry-run - -Remove --dry-run to execute it. The default GPU job has a ten-minute total -wall limit across both formulations and plotting. Defaults retain the original -births and wave convention and raw native field. Historical-input conversion -requires an explicit option. Backgrounds remain -Boozer / Perfect QS and VMEC / full equilibrium. -""" - -import argparse -import hashlib -import json -from pathlib import Path -import shlex -import subprocess -import sys -import os -import time - - -def commands(python, particles, platform, wall_seconds, output, batch_size, diagnostic_batch_size, - *, source_convention="essos", representation="raw", seed=42, births=None, wout=None, - particle_model="essos"): - boozer, vmec, comparison = output/"boozer", output/"vmec", output/"comparison" - native_tolerance = "1e-8" - boozer_mode_tolerance = "1e-6" - steps = [ - [python, "-m", "examples.particle_tracing.analytical_alfven_paper_benchmark", - "--particles", str(particles), "--platform", platform, "--wall-seconds", str(wall_seconds), - "--source-convention", source_convention, "--seed", str(seed), - "--diagnostic-batch-size", str(diagnostic_batch_size), "--output", str(boozer)], - [python, "-m", "examples.particle_tracing.vmec_alfven_paper_benchmark", - "--particles", str(particles), "--platform", platform, "--wall-seconds", str(wall_seconds), - "--source-convention", source_convention, "--seed", str(seed), - "--representation", representation, "--boozer-mode-tolerance", boozer_mode_tolerance, - "--tolerance", native_tolerance, - "--batch-size", str(batch_size), "--diagnostic-batch-size", str(diagnostic_batch_size), - "--births", str(boozer/"trajectories.npz"), "--output", str(vmec)], - [python, "-m", "examples.benchmarks.paul_boozer_vmec_loss_comparison", - "--particles", str(particles), "--boozer", str(boozer), "--vmec", str(vmec), - "--output", str(comparison)], - ] - if births is not None: - steps[0].extend(["--births", str(births)]) - if wout is not None: - for step in steps[:2]: - step.extend(["--wout", str(wout)]) - for step in steps[:2]: - step.extend(["--particle-model", particle_model]) - return steps - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--particles", type=int, default=500, help="Markers per case; four cases total") - parser.add_argument("--platform", choices=("cpu", "gpu"), default="gpu") - parser.add_argument("--wall-seconds", type=float, default=600., help="Total wall limit for all three commands") - parser.add_argument("--batch-size", type=int, default=256, help="VMEC integration batch size") - parser.add_argument("--diagnostic-batch-size", type=int, default=128) - parser.add_argument("--source-convention", choices=("essos", "simsopt_2023"), default="essos", - help="Original benchmark convention by default; historical conversion is an explicit experiment") - parser.add_argument("--representation", choices=("raw",), default="raw", - help="Full native VMEC field") - parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--particle-model", choices=("essos", "simsopt_2023"), default="essos") - parser.add_argument("--births", type=Path, help="Shared saved marker pool; use its first N markers") - parser.add_argument("--wout", type=Path, help="Use this same QA equilibrium in both formulations") - parser.add_argument("--output", type=Path, help="Separate job folder, including convention and representation by default") - parser.add_argument("--python", default=sys.executable) - parser.add_argument("--dry-run", action="store_true", help="Save a job manifest and print commands; no JAX import or simulation") - args = parser.parse_args() - if args.particles < 3 or min(args.batch_size, args.diagnostic_batch_size) < 1: - parser.error("Need particles >= 3 and positive batch sizes") - if not 0 < args.wall_seconds < float("inf"): - parser.error("wall-seconds must be finite and positive") - root = Path(__file__).resolve().parents[2] - wout = (args.wout or root/"examples/input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc").resolve() - if not wout.is_file(): - parser.error("wout must name an existing equilibrium file") - suffix = f"{args.source_convention}_{args.representation.replace('-', '_')}" - output = args.output or root/f"examples/benchmarks/results/paul_boozer_vmec_{args.particles}_{suffix}" - output = output.resolve() - output.mkdir(parents=True, exist_ok=True) - args.births = None if args.births is None else args.births.resolve() - steps = commands(args.python, args.particles, args.platform, args.wall_seconds, output, - args.batch_size, args.diagnostic_batch_size, source_convention=args.source_convention, - representation=args.representation, seed=args.seed, births=args.births, wout=wout, - particle_model=args.particle_model) - manifest = dict(status="prepared", particles_per_case=args.particles, - total_trajectories=4*args.particles, platform=args.platform, tmax_s=.001, - total_wall_limit_seconds=args.wall_seconds, vmec_batch_size=args.batch_size, - diagnostic_batch_size=args.diagnostic_batch_size, - source_convention=args.source_convention, vmec_representation=args.representation, - birth_pool=None if args.births is None else str(args.births.resolve()), - wout=str(wout), wout_sha256=hashlib.sha256(wout.read_bytes()).hexdigest(), - seed=args.seed, source_omega_rad_s=399000., particle_model=args.particle_model, - essos_omega_rad_s=-399000. if args.source_convention == "simsopt_2023" else 399000., - vmec_tolerance=1e-8, - boozer_mode_tolerance=1e-6, - backgrounds=["Boozer / Perfect QS", "VMEC / full equilibrium"], commands=steps) - manifest_path = output/"job.json" - if not args.dry_run and (output/"boozer/summary.json").exists(): - parser.error("Output already contains Boozer results; select a fresh --output to preserve them") - if args.dry_run and manifest_path.exists(): - parser.error("Job manifest already exists; select a fresh --output to preserve it") - manifest_path.write_text(json.dumps(manifest, indent=2)+"\n") - for step in steps: - print(shlex.join(step), flush=True) - if args.dry_run: - print(f"Prepared {4*args.particles} trajectories; no particle tracing started", flush=True) - return - started = time.monotonic() - environment = os.environ.copy() - # Allocate GPU memory as needed, leaving room for desktop applications. - environment.setdefault("XLA_PYTHON_CLIENT_PREALLOCATE", "false") - manifest["status"] = "running" - try: - for index, step in enumerate(steps): - remaining = args.wall_seconds-(time.monotonic()-started) - if remaining <= 0: - raise subprocess.TimeoutExpired(step, args.wall_seconds) - actual = step.copy() - if "--wall-seconds" in actual: - actual[actual.index("--wall-seconds")+1] = str(remaining) - manifest.update(active_step=index, status="running") - manifest_path.write_text(json.dumps(manifest, indent=2)+"\n") - subprocess.run(actual, cwd=root, env=environment, check=True, timeout=remaining) - manifest["status"] = "complete" - except subprocess.TimeoutExpired: - manifest["status"] = "timed_out" - raise - except BaseException: - manifest["status"] = "stopped" - raise - finally: - manifest["elapsed_seconds"] = time.monotonic()-started - manifest_path.write_text(json.dumps(manifest, indent=2)+"\n") - - -if __name__ == "__main__": - main() diff --git a/examples/benchmarks/paul_boozer_vmec_loss_comparison.py b/examples/benchmarks/paul_boozer_vmec_loss_comparison.py deleted file mode 100644 index 81f7afc5..00000000 --- a/examples/benchmarks/paul_boozer_vmec_loss_comparison.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Plot four loss curves from completed Boozer and VMEC cases. - -No particle tracing or JAX import. Boozer is the Paul / Perfect QS -benchmark; VMEC retains the full equilibrium. Published Table 2 endpoints -use the corresponding columns. Birth proposals and pitches must match. -""" - -import argparse -import csv -import json -from pathlib import Path - - -def compare(boozer, vmec, output, *, particles=None): - import numpy as np - from examples.benchmarks.sampling import estimate_interval - - boozer_summary = json.loads((boozer/"summary.json").read_text()) - vmec_summary = json.loads((vmec/"summary.json").read_text()) - if particles is None: - particles = boozer_summary["particles_per_case"] - if boozer_summary["particles_per_case"] != particles or vmec_summary["particles_per_case"] != particles: - raise ValueError(f"Both inputs must contain exactly {particles} markers per case") - if not boozer_summary["numerical_checks_passed"] or not vmec_summary["numerical_checks_passed"]: - raise ValueError("Both comparisons must pass their numerical checks") - if not vmec_summary["all_orbits_resolved"]: - raise ValueError("Unresolved VMEC orbits cannot be presented as a completed loss comparison") - source_convention = boozer_summary.get("source_convention", "essos") - if vmec_summary.get("source_convention", "essos") != source_convention: - raise ValueError("The two formulations use different source conventions") - for key in ("mass_kg", "energy_joule"): - if key in boozer_summary or key in vmec_summary: - if key not in boozer_summary or key not in vmec_summary: - raise ValueError(f"Both formulations must record {key} to compare explicit particle models") - if not np.isclose(boozer_summary[key], vmec_summary[key], rtol=1e-12, atol=0.): - raise ValueError(f"Different particle parameter {key}") - representation = vmec_summary.get("representation", "raw") - b_hash = boozer_summary.get("provenance", {}).get("wout_sha256") - v_hash = vmec_summary.get("wout_sha256") - if b_hash is not None and v_hash is not None and b_hash != v_hash: - raise ValueError("The equilibrium source hashes differ, even if filenames match") - for bcase, vcase in zip(boozer_summary["results"], vmec_summary["cases"]): - for key in ("essos_omega_rad_s", "potential_volts"): - if key in bcase and key in vcase: - np.testing.assert_allclose(bcase[key], vcase[key], rtol=1e-12, atol=1e-12, - err_msg=f"Different actual ESSOS wave parameter {key}") - if len(boozer_summary["reference"]["cases"]) != 2 or len(vmec_summary["reference"]["cases"]) != 2: - raise ValueError("Expected unperturbed and perturbed cases for each formulation") - for bcase, vcase in zip(boozer_summary["reference"]["cases"], vmec_summary["reference"]["cases"]): - for key in ("m", "n", "omega_rad_s", "delta_bhat_psi"): - if bcase[key] != vcase[key]: - raise ValueError(f"The two formulations use different wave parameter {key}") - if not np.isclose(boozer_summary["tmax"], .001) or not np.isclose(vmec_summary["tmax_s"], .001): - raise ValueError("This Paul comparison requires the full 1 ms duration") - for key in ("B_scale", "length_scale"): - np.testing.assert_allclose(boozer_summary["provenance"][key], vmec_summary[key], rtol=1e-13) - if Path(boozer_summary["provenance"]["wout"]).name != Path(vmec_summary["wout"]).name: - raise ValueError("The equilibrium source files differ") - if boozer_summary["axis_stop_s"] != 1e-8: - raise ValueError("The saved Boozer case must use the common s=1e-8 inner cutoff") - output.mkdir(parents=True, exist_ok=True) - times = np.linspace(0., .001, 1001) - curves, rows, data = [], [], {} - with np.load(boozer/"trajectories.npz") as old, np.load(vmec/"births.npz") as native: - for key in ("birth_s", "birth_theta", "birth_zeta", "birth_pitch"): - np.testing.assert_allclose(old[key], native[key], rtol=0, atol=1e-13, - err_msg=f"Different initial {key}") - if len(old[key]) != particles: - raise ValueError("Birth archive marker count does not match its summary") - for model, summary, weights in (("Boozer / Perfect QS", boozer_summary, old["birth_weights"]), - ("VMEC / full equilibrium", vmec_summary, native["birth_weights"])): - for index, case in enumerate(summary["reference"]["cases"]): - if model.startswith("Boozer"): - lcfs, inner = old[f"loss_times_{index}"], old[f"axis_stop_times_{index}"] - lcfs, inner = np.where(lcfs >= 0, lcfs, np.inf), np.where(inner >= 0, inner, np.inf) - if summary["results"][index]["failed"]: - raise ValueError("The saved Boozer case has unresolved markers") - else: - with np.load(vmec/f"case_{index}.npz") as saved: - lcfs, inner = saved["lcfs_times"], saved["axis_stop_times"] - if np.any(saved["status"] == 4): - raise ValueError("The saved VMEC case has unresolved markers") - if saved["times"][-1] != times[-1]: - raise ValueError("VMEC duration differs from the comparison") - np.testing.assert_allclose(saved["weights"], weights, rtol=1e-13) - if len(lcfs) != particles or len(inner) != particles: - raise ValueError("Per-case marker count does not match the requested comparison") - stop_times = np.minimum(lcfs, inner) - weights = weights/weights.sum() - curve = weights@(stop_times[:, None] <= times[None, :]) - estimate = estimate_interval(np.isfinite(stop_times), weights, binary=True) - measured = (summary["results"][index]["loss_fraction"]["value"] if model.startswith("Boozer") - else summary["cases"][index]["weighted_confirmed_loss"]) - np.testing.assert_allclose(estimate["value"], measured, rtol=1e-12, atol=1e-14) - curves.append((model, index, curve, case["loss_fraction"])) - rows.append(dict(model=model, case=case["name"], particles=particles, - lcfs_exits=int(np.isfinite(lcfs).sum()), - inner_stops=int(np.isfinite(inner).sum()), failed=0, - loss_fraction=estimate["value"], - sampling_95_low=estimate["interval_95"][0], - sampling_95_high=estimate["interval_95"][1], - paper_loss_fraction=case["loss_fraction"])) - data[f"loss_curve_{len(curves)-1}"] = curve - _plot(output, times, curves, particles, source_convention=source_convention, representation=representation) - with (output/"comparison.csv").open("w", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=list(rows[0])) - writer.writeheader() - writer.writerows(rows) - np.savez_compressed(output/"loss_curves.npz", times=times, **data) - report = ["# Boozer and VMEC alpha loss fractions", "", - f"{particles} particles per curve; 1 ms; collisionless adaptive GC. " - "Perturbed cases: m=15, n=7, source omega=399000 rad/s, edge amplitude 1e-3.", "", - f"Source convention: `{source_convention}`; actual ESSOS omega: " - f"{boozer_summary['results'][1].get('essos_omega_rad_s', 399000.):g} rad/s. " - f"VMEC field representation: `{representation}`.", "", - "Identical initial coordinate proposals and pitches, with physical-volume " - "importance weights computed for each background.", "", - "| Model | Case | Loss | Approx. 95% sampling interval | LCFS exits | Inner stops | Paper |", - "| --- | --- | ---: | --- | ---: | ---: | ---: |"] - for row in rows: - report.append(f"| {row['model']} | {row['case']} | {100*row['loss_fraction']:.2f}% | " - f"[{100*row['sampling_95_low']:.2f}%, {100*row['sampling_95_high']:.2f}%] | " - f"{row['lcfs_exits']} | {row['inner_stops']} | {100*row['paper_loss_fraction']:.1f}% |") - representation_note = ( - "This comparison uses raw VMEC tables; it does not establish convergence in " - "equilibrium resolution or interpolation. " - ) - report.extend(["", "Boozer uses the earlier Paul benchmark with QS-breaking harmonics filtered out; " - "VMEC retains the full equilibrium. This comparison includes that background " - "difference as well as the coordinate formulation. Paper endpoints use the matching " - "Perfect QS and Equil. columns of Table 2.", "", - "All four cases have zero unresolved failures. Inner stops at s=1e-8 are counted " - "as paper-style losses, separately from LCFS exits. The exact published " - "equilibrium/runtime remains unconfirmed; the paper used 5000 markers.", "", - "The historical SIMSOPT convention is an explicit comparison assumption; " - "the exact paper runtime has not been established. " + representation_note + - "Sampling intervals exclude these systematic uncertainties.", "", - f"Source: {boozer_summary['reference']['source']}", ""]) - (output/"comparison.md").write_text("\n".join(report)) - (output/"summary.json").write_text(json.dumps(dict(particles_per_case=particles, - tmax_s=.001, boozer_source=str(boozer), vmec_source=str(vmec), cases=rows, - source_convention=source_convention, vmec_representation=representation, - background_difference="Boozer Perfect QS; VMEC full equilibrium"), indent=2)+"\n") - print(json.dumps(rows, indent=2), flush=True) - - -def _plot(output, times, curves, particles, *, source_convention="essos", representation="raw", stem=None): - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - from matplotlib.lines import Line2D - fig, ax = plt.subplots(figsize=(9, 6.5), constrained_layout=True) - for k, (model, index, curve, paper) in enumerate(curves): - color = ("#2878b5", "#004c8c", "#e58b26", "#a83f16")[k] - condition = "unperturbed" if index == 0 else "m=15 wave" - ax.step(times*1e3, 100*curve, where="post", color=color, - linestyle="--" if index == 0 else "-", linewidth=2, - label=f"{model}, {condition} ({100*curve[-1]:.2f}%)") - ax.plot(1., 100*paper, "x", color=color, markersize=9, markeredgewidth=2) - handles, labels = ax.get_legend_handles_labels() - handles.append(Line2D([], [], marker="x", linestyle="none", color="black", markersize=8)) - labels.append("Paul Table 2 endpoint (matching background)") - ax.legend(handles, labels, loc="upper left", bbox_to_anchor=(0., -.15), - fontsize=9, frameon=False) - ax.set(xlabel="Time [ms]", ylabel="Volume-weighted loss fraction [%]", xlim=(0, 1.025), - title=f"Paul alpha transport: {particles} particles per curve\n" - f"Source: {source_convention}; VMEC: {representation}") - ax.set_ylim(bottom=0) - ax.grid(alpha=.25) - stem = stem or f"boozer_vmec_loss_{particles}" - for extension in ("png", "svg"): - fig.savefig(output/f"{stem}.{extension}", dpi=180) - plt.close(fig) - - -def main(): - root = Path(__file__).resolve().parents[2] - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--boozer", type=Path, default=root/"examples/benchmarks/results/paul_100_rerun/boozer") - parser.add_argument("--vmec", type=Path, default=root/"examples/benchmarks/results/paul_100_rerun/vmec") - parser.add_argument("--output", type=Path, default=root/"examples/benchmarks/results/paul_100_rerun/comparison") - parser.add_argument("--particles", type=int, help="Require this marker count; otherwise infer it from saved results") - args = parser.parse_args() - compare(args.boozer, args.vmec, args.output, particles=args.particles) - - -if __name__ == "__main__": - main() diff --git a/examples/benchmarks/paul_conventions.py b/examples/benchmarks/paul_conventions.py deleted file mode 100644 index 3a2d0c87..00000000 --- a/examples/benchmarks/paul_conventions.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Explicit convention conversion for benchmark inputs, outside the GC RHS. - -For a stellarator-symmetric Boozer |B| spectrum, historical positive-psi0 -equations map to ESSOS's negative-psi0 equations through -(theta,zeta,v_parallel) -> (-theta,-zeta,-v_parallel). The same map requires -(omega,Phi_hat,phase) -> (-omega,-Phi_hat,-phase) for the analytical harmonic. -The public March 2023 SIMSOPT adapter used the positive flux convention. -That observation does not establish the exact runtime used by Paul (2023). -""" - -import json -from pathlib import Path -try: - import tomllib -except ModuleNotFoundError: # Python 3.10 - import tomli as tomllib - -import numpy as np - - -CONVENTIONS = ("essos", "simsopt_2023") - - -def particle_parameters(model, *, measured_mass, energy_joule): - """Explicit benchmark mass at fixed energy; no changes to ESSOS constants.""" - _validate(model) - if model == "simsopt_2023": - reference = Path(__file__).with_name("references")/"paul2023_particle.toml" - historical = tomllib.loads(reference.read_text())["historical_particle"] - mass, source = historical["mass_kg"], historical["source"] - else: - mass, source = measured_mass, "essos.constants.ALPHA_PARTICLE_MASS" - return dict(particle_model=model, mass_kg=float(mass), energy_joule=float(energy_joule), - birth_speed_m_s=float(np.sqrt(2*energy_joule/mass)), particle_model_source=source) - - -def _validate(source): - if source not in CONVENTIONS: - raise ValueError(f"Unknown source convention {source!r}; expected {CONVENTIONS}") - - -def convert_births(s, theta, zeta, pitch, *, source): - """Return ESSOS-coordinate births; preserve the caller's arrays.""" - _validate(source) - arrays = [np.array(value, dtype=float, copy=True) for value in (s, theta, zeta, pitch)] - if any(value.shape != arrays[0].shape for value in arrays): - raise ValueError("Birth coordinates and pitch must have identical shapes") - if source == "simsopt_2023": - for value in arrays[1:]: - value *= -1 - return tuple(arrays) - - -def load_essos_births(path, particles, *, source): - """Read already-converted births, rejecting a mismatched wave convention. - - Older archives without convention metadata used the ESSOS convention. - Loading an archive must never apply the reflection a second time. - """ - _validate(source) - with np.load(path) as saved: - metadata = json.loads(str(saved["metadata_json"])) if "metadata_json" in saved else {} - archive_source = metadata.get("source_convention", "essos") - if archive_source != source: - raise ValueError(f"Birth archive source convention {archive_source!r} differs from {source!r}") - if metadata.get("birth_coordinate_convention", "essos") != "essos": - raise ValueError("Saved births must already use ESSOS coordinates") - births = tuple(np.array(saved[f"birth_{key}"][:particles], copy=True) - for key in ("s", "theta", "zeta", "pitch")) - if any(value.shape != (particles,) for value in births): - raise ValueError("Birth archive has fewer markers than requested or invalid dimensions") - return births - - -def convert_mode(mode, *, source): - """Convert an analytical harmonic while retaining m, n and its envelope.""" - _validate(source) - if source == "essos": - return mode - import equinox as eqx - from essos.perturbations import AnalyticalAlfvenMode - - if not isinstance(mode, AnalyticalAlfvenMode): - raise TypeError("The benchmark conversion requires an AnalyticalAlfvenMode") - return eqx.tree_at(lambda wave: (wave.omega, wave.amplitude, wave.phase), mode, - (-mode.omega, -mode.amplitude, -mode.phase)) diff --git a/examples/benchmarks/plot_alfven_results.py b/examples/benchmarks/plot_alfven_results.py deleted file mode 100644 index d9fd64f3..00000000 --- a/examples/benchmarks/plot_alfven_results.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Regenerate the documentation figures from committed data; trace no particles. - -From the checkout root: python -m examples.benchmarks.plot_alfven_results -""" - -import argparse -import json -import os -from pathlib import Path - - -def plot_smoke(output, arrays): - import numpy as np - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - - times = arrays["times"]*1e9 - birth_energy = arrays["equilibrium_energy"][:, :1] - fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), constrained_layout=True) - for marker in range(2): - for name, style in (("equilibrium", "--"), ("wave", "-")): - axes[0].plot(times, arrays[f"{name}_states"][marker, :, 0], style, - color=f"C{marker}", label=f"Marker {marker+1}: {name}") - axes[1].plot(times, arrays[f"{name}_energy"][marker]/birth_energy[marker]-1, - style, color=f"C{marker}") - axes[2].plot(times, arrays["wave_B_s"][marker], color=f"C{marker}") - axes[0].set(ylabel="Toroidal flux s", title="Existing adaptive VMEC GC solver") - axes[0].legend(fontsize=7) - axes[1].set(ylabel="Kinetic energy change / birth energy", title="Wave work is allowed") - axes[2].set(ylabel="Covariant radial B_s [T m]", title="Radial covariant field retained") - for ax in axes: - ax.set_xlabel("Time [ns]") - ax.grid(alpha=.2) - fig.suptitle("VMEC analytical-wave smoke test: four CPU trajectories") - for extension in ("png", "svg"): - fig.savefig(output/f"vmec_alfven_smoke.{extension}", dpi=160) - plt.close(fig) - - -def main(): - root = Path(__file__).resolve().parents[2] - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--data", type=Path, default=root/"examples/benchmarks/references") - parser.add_argument("--output", type=Path, default=root/"docs/_static/analytical_perturbations") - args = parser.parse_args() - os.environ.update(JAX_PLATFORMS="cpu", ESSOS_CPU_DEVICES="1", CUDA_VISIBLE_DEVICES="-1") - import numpy as np - from examples.benchmarks.alfven_gc_verification import plot as plot_verification - from examples.benchmarks.paul_boozer_vmec_loss_comparison import _plot as plot_losses - - args.output.mkdir(parents=True, exist_ok=True) - summary = json.loads((args.data/"paul_loss_100.json").read_text()) - with np.load(args.data/"paul_loss_100.npz") as arrays: - curves = [(row["model"], index % 2, arrays[f"loss_curve_{index}"], row["paper_loss_fraction"]) - for index, row in enumerate(summary["cases"])] - plot_losses(args.output, arrays["times"], curves, summary["particles_per_case"], - source_convention=summary["source_convention"], - representation=summary["vmec_representation"], stem="paul_loss_100") - summary = json.loads((args.data/"gc_verification.json").read_text()) - with np.load(args.data/"gc_verification.npz") as arrays: - plot_verification(args.output, summary, dict(arrays)) - with np.load(args.data/"vmec_alfven_smoke.npz") as arrays: - plot_smoke(args.output, arrays) - print(f"Regenerated three figures (PNG and SVG) in {args.output}; zero trajectories traced.") - - -if __name__ == "__main__": - main() diff --git a/examples/benchmarks/references/gc_verification.json b/examples/benchmarks/references/gc_verification.json deleted file mode 100644 index d6d723b8..00000000 --- a/examples/benchmarks/references/gc_verification.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "reference": "https://arxiv.org/abs/2205.11280", - "exact_paper_reproduction": false, - "description": "ORBIT-style conservation checks on an analytic axisymmetric fixture", - "method": "adaptive8", - "platform": "cpu", - "trajectories": 18, - "particles_per_wave_case": 2, - "simulated_time_s": 4e-05, - "tolerances": [ - 1e-06, - 1e-10 - ], - "time_limit_s": 120, - "wave_cases": [ - { - "relative_phase_rad": 0.0, - "max_local_invariant_residual": 1.1307965909208213e-16, - "max_liouville_residual": 4.164974411553334e-16, - "missing_induction_invariant_residual": 0.0027668111687867533, - "missing_induction_liouville_residual": 2.966965316978514e-05, - "traces": [ - { - "tolerance": 1e-06, - "max_invariant_error": 2.2463727344620044e-10, - "max_relative_energy_exchange": 0.014004273509993056 - }, - { - "tolerance": 1e-10, - "max_invariant_error": 1.1880054192895783e-10, - "max_relative_energy_exchange": 0.014004273510141956 - } - ] - }, - { - "relative_phase_rad": 1.5707963267948966, - "max_local_invariant_residual": 1.673610837488043e-16, - "max_liouville_residual": 9.544023900421639e-16, - "missing_induction_invariant_residual": 0.00255997301305586, - "missing_induction_liouville_residual": 3.145964440004823e-05, - "traces": [ - { - "tolerance": 1e-06, - "max_invariant_error": 2.5236997777707767e-10, - "max_relative_energy_exchange": 0.009477125904500656 - }, - { - "tolerance": 1e-10, - "max_invariant_error": 3.125318213637519e-11, - "max_relative_energy_exchange": 0.00947712590568446 - } - ] - }, - { - "relative_phase_rad": 3.141592653589793, - "max_local_invariant_residual": 5.883697419656225e-17, - "max_liouville_residual": 4.283235919770378e-16, - "missing_induction_invariant_residual": 0.0026965170316695214, - "missing_induction_liouville_residual": 3.240990289144592e-05, - "traces": [ - { - "tolerance": 1e-06, - "max_invariant_error": 2.4269469275655413e-10, - "max_relative_energy_exchange": 0.008155614823214844 - }, - { - "tolerance": 1e-10, - "max_invariant_error": 9.975877028651202e-11, - "max_relative_energy_exchange": 0.008155614823331787 - } - ] - }, - { - "relative_phase_rad": 4.71238898038469, - "max_local_invariant_residual": 1.610227243455888e-16, - "max_liouville_residual": 9.961730066639321e-16, - "missing_induction_invariant_residual": 0.0025736513073272385, - "missing_induction_liouville_residual": 2.3798764486757964e-05, - "traces": [ - { - "tolerance": 1e-06, - "max_invariant_error": 2.2673957976348239e-10, - "max_relative_energy_exchange": 0.012471303018490351 - }, - { - "tolerance": 1e-10, - "max_invariant_error": 6.019224527206296e-11, - "max_relative_energy_exchange": 0.012471303017081221 - } - ] - } - ], - "uniform_induction": [ - { - "tolerance": 1e-06, - "max_velocity_error_over_birth_speed": 2.150569404308856e-15, - "max_zeta_error_rad": 5.684341886080802e-14 - }, - { - "tolerance": 1e-10, - "max_velocity_error_over_birth_speed": 2.150569404308856e-15, - "max_zeta_error_rad": 5.684341886080802e-14 - } - ], - "passed": true, - "elapsed_seconds_before_plot": 27.08597719499994 -} diff --git a/examples/benchmarks/references/gc_verification.npz b/examples/benchmarks/references/gc_verification.npz deleted file mode 100644 index 78d5e8df..00000000 Binary files a/examples/benchmarks/references/gc_verification.npz and /dev/null differ diff --git a/examples/benchmarks/references/paul2023_particle.toml b/examples/benchmarks/references/paul2023_particle.toml deleted file mode 100644 index a8fa72b1..00000000 --- a/examples/benchmarks/references/paul2023_particle.toml +++ /dev/null @@ -1,6 +0,0 @@ -[historical_particle] -source = "https://github.com/hiddenSymmetries/simsopt/blob/70182c529d9aa70275d15ecaba636419a4b0ffae/src/simsopt/util/constants.py" -mass_kg = 6.69509884346e-27 -mass_definition = "2*PROTON_MASS + 2*NEUTRON_MASS; not the measured bound-alpha mass" -energy_MeV = 3.52 -scope = "Documented historical library constants; exact published runtime remains unconfirmed" diff --git a/examples/benchmarks/references/paul2023_vacuum_qa.toml b/examples/benchmarks/references/paul2023_vacuum_qa.toml deleted file mode 100644 index 73885a04..00000000 --- a/examples/benchmarks/references/paul2023_vacuum_qa.toml +++ /dev/null @@ -1,36 +0,0 @@ -# Published numbers, not ESSOS-generated regression targets. -# Table 2, vacuum QA, "Perfect QS" column (NOT "Equil."). -paper = "Fast-ion transport in quasisymmetric equilibria in the presence of a resonant Alfvenic perturbation" -doi = "10.1017/S0022377823001095" -source = "https://arxiv.org/html/2306.12531v2#S6.T2" -table = "Table 2, QA vac, Perfect QS" -mode_source = "Table 1(c)" -particles = 5000 -tmax_seconds = 0.001 -energy_MeV = 3.52 -s_min = 0.25 -s_max = 0.75 -birth_distribution = "Uniform physical volume and pitch" -minor_radius_m = 1.70 -field_strength_T = 5.86 -potential_envelope = "Uniform radial potential" -loss_boundary = "s=0 or s=1" -published_decimal_places = 3 - -[[cases]] -name = "Unperturbed" -m = 15 -n = 7 -omega_rad_s = 399000.0 -delta_bhat_psi = 0.0 -loss_fraction = 0.066 -mean_abs_delta_s = 0.112 - -[[cases]] -name = "m=15 mode" -m = 15 -n = 7 -omega_rad_s = 399000.0 -delta_bhat_psi = 0.001 -loss_fraction = 0.162 -mean_abs_delta_s = 0.146 diff --git a/examples/benchmarks/references/paul2023_vacuum_qa_equilibrium.toml b/examples/benchmarks/references/paul2023_vacuum_qa_equilibrium.toml deleted file mode 100644 index a23ea022..00000000 --- a/examples/benchmarks/references/paul2023_vacuum_qa_equilibrium.toml +++ /dev/null @@ -1,29 +0,0 @@ -# Full equilibrium column; distinct from the existing Perfect QS benchmark. -paper = "Fast-ion transport in quasisymmetric equilibria in the presence of a resonant Alfvenic perturbation" -doi = "10.1017/S0022377823001095" -source = "https://arxiv.org/html/2306.12531v2#S6.T2" -table = "Table 2, QA vac, Equil." -particles = 5000 -tmax_seconds = 0.001 -energy_MeV = 3.52 -minor_radius_m = 1.70 -field_strength_T = 5.86 -loss_boundary = "s=0 or s=1" - -[[cases]] -name = "Unperturbed" -m = 15 -n = 7 -omega_rad_s = 399000.0 -delta_bhat_psi = 0.0 -loss_fraction = 0.083 -mean_abs_delta_s = 0.105 - -[[cases]] -name = "m=15 mode" -m = 15 -n = 7 -omega_rad_s = 399000.0 -delta_bhat_psi = 0.001 -loss_fraction = 0.194 -mean_abs_delta_s = 0.163 diff --git a/examples/benchmarks/references/paul_births_100.npz b/examples/benchmarks/references/paul_births_100.npz deleted file mode 100644 index 1a874ceb..00000000 Binary files a/examples/benchmarks/references/paul_births_100.npz and /dev/null differ diff --git a/examples/benchmarks/references/paul_loss_100.json b/examples/benchmarks/references/paul_loss_100.json deleted file mode 100644 index e2640f02..00000000 --- a/examples/benchmarks/references/paul_loss_100.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "particles_per_case": 100, - "tmax_s": 0.001, - "boozer_source": "examples.particle_tracing.analytical_alfven_paper_benchmark", - "vmec_source": "examples.particle_tracing.vmec_alfven_paper_benchmark", - "cases": [ - { - "model": "Boozer / Perfect QS", - "case": "Unperturbed", - "particles": 100, - "lcfs_exits": 12, - "inner_stops": 0, - "failed": 0, - "loss_fraction": 0.12248008197203858, - "sampling_95_low": 0.07163206304867896, - "sampling_95_high": 0.20158504408431133, - "paper_loss_fraction": 0.066 - }, - { - "model": "Boozer / Perfect QS", - "case": "m=15 mode", - "particles": 100, - "lcfs_exits": 13, - "inner_stops": 8, - "failed": 0, - "loss_fraction": 0.215275051747804, - "sampling_95_low": 0.14570779796391908, - "sampling_95_high": 0.30615364912716153, - "paper_loss_fraction": 0.162 - }, - { - "model": "VMEC / full equilibrium", - "case": "Unperturbed", - "particles": 100, - "lcfs_exits": 12, - "inner_stops": 0, - "failed": 0, - "loss_fraction": 0.12248227279125565, - "sampling_95_low": 0.07163366050095822, - "sampling_95_high": 0.20158773932939683, - "paper_loss_fraction": 0.083 - }, - { - "model": "VMEC / full equilibrium", - "case": "m=15 mode", - "particles": 100, - "lcfs_exits": 13, - "inner_stops": 7, - "failed": 0, - "loss_fraction": 0.20564537625504117, - "sampling_95_low": 0.13770037638861454, - "sampling_95_high": 0.295622548655027, - "paper_loss_fraction": 0.194 - } - ], - "source_convention": "simsopt_2023", - "vmec_representation": "raw", - "background_difference": "Boozer Perfect QS; VMEC full equilibrium", - "source": "https://arxiv.org/html/2306.12531v2#S6.T2", - "wout": "examples/input_files/wout_LandremanPaul2021_QA_lowres.nc", - "wout_sha256": "4d301a3c32aa6b12f0c13f2c440d223427275fb00862fac3e64e52dc8421c23c", - "particle_model": "simsopt_2023", - "mass_kg": 6.69509884346e-27, - "energy_joule": 5.639661751679999e-13, - "B_scale": 5.822466638556906, - "length_scale": 10.100286074838252, - "source_omega_rad_s": 399000.0, - "essos_omega_rad_s": -399000.0, - "potential_volts": -3725.818890765528, - "edge_m_alpha_over_a": 0.001, - "m": 15, - "n": 7, - "axis_stop_s": 1e-08, - "numerical_checks_passed": true, - "boozer_max_invariant_drift": 8.423105710097552e-09, - "vmec_baseline_max_relative_energy_change": 8.092553829719407e-06, - "vmec_wave_max_relative_mu_change": 0.0, - "timing": { - "initial_capped_job_seconds": 600.145247852, - "vmec_resume_seconds": 549.707305507 - }, - "quantitative_paper_validation": "not established; 100-marker comparison; exact paper input/runtime unconfirmed" -} diff --git a/examples/benchmarks/references/paul_loss_100.npz b/examples/benchmarks/references/paul_loss_100.npz deleted file mode 100644 index cae48a78..00000000 Binary files a/examples/benchmarks/references/paul_loss_100.npz and /dev/null differ diff --git a/examples/benchmarks/references/vmec_alfven_smoke.json b/examples/benchmarks/references/vmec_alfven_smoke.json deleted file mode 100644 index 50d29035..00000000 --- a/examples/benchmarks/references/vmec_alfven_smoke.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "passed": true, - "platform": "cpu", - "total_trajectories": 4, - "simulated_time_s": 2e-07, - "time_limit_s": 120, - "cases": [ - { - "case": "equilibrium", - "particles": 2, - "failures": 0, - "max_relative_kinetic_energy_change": 2.7205085729731238e-06, - "max_abs_radial_covariant_B_Tm": 2.555101366490655 - }, - { - "case": "wave", - "particles": 2, - "failures": 0, - "max_relative_kinetic_energy_change": 3.051884377147651e-05, - "max_abs_radial_covariant_B_Tm": 2.555880444961748, - "max_relative_mu_change": 0.0 - } - ], - "model": "Existing GuidingCenterAdaptative with full VMEC covariant field", - "perturbation": "Native VMEC-angle analytical mode; not a mapped Paul benchmark", - "elapsed_seconds_before_plot": 34.34983612599899 -} diff --git a/examples/benchmarks/references/vmec_alfven_smoke.npz b/examples/benchmarks/references/vmec_alfven_smoke.npz deleted file mode 100644 index f601c514..00000000 Binary files a/examples/benchmarks/references/vmec_alfven_smoke.npz and /dev/null differ diff --git a/examples/benchmarks/sampling.py b/examples/benchmarks/sampling.py deleted file mode 100644 index 491996cf..00000000 --- a/examples/benchmarks/sampling.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Sampling intervals shared by the Boozer and VMEC transport comparisons.""" - - -def estimate_interval(values, weights, *, binary=False): - """Weighted mean and approximate 95% interval for sampling noise only. - - Losses use Wilson with Kish effective count. Displacements use an - unbiased weighted variance and a normal interval. - """ - import numpy as np - values, weights = np.asarray(values, float), np.asarray(weights, float) - weights = weights/weights.sum() - mean = float(weights@values) - sum_squared = float(weights@weights) - effective_count = 1/sum_squared - z = 1.959963984540054 - if binary: - denominator = 1+z*z/effective_count - center = (mean+z*z/(2*effective_count))/denominator - radius = z*np.sqrt(mean*(1-mean)/effective_count+z*z/(4*effective_count**2))/denominator - interval = [max(0., center-radius), min(1., center+radius)] - else: - variance = float(weights@((values-mean)**2))/(1-sum_squared) - radius = z*np.sqrt(variance*sum_squared) - interval = [max(0., mean-radius), mean+radius] - return dict(value=mean, interval_95=[float(x) for x in interval], effective_particles=effective_count) diff --git a/examples/input_files/wout_LandremanPaul2021_QA_lowres.nc b/examples/input_files/wout_LandremanPaul2021_QA_lowres.nc deleted file mode 100644 index 90d820c3..00000000 Binary files a/examples/input_files/wout_LandremanPaul2021_QA_lowres.nc and /dev/null differ diff --git a/examples/particle_tracing/alfven_perturbation.py b/examples/particle_tracing/alfven_perturbation.py new file mode 100644 index 00000000..e14a49af --- /dev/null +++ b/examples/particle_tracing/alfven_perturbation.py @@ -0,0 +1,30 @@ +"""Guiding centres in a VMEC equilibrium with and without a prescribed shear-Alfven wave. + +The wave Phi = 2e4 V s^(3/2) sin(3 theta - 2 phi + omega t) with alpha = (n B^phi - m B^theta) Phi / (omega B^2) +has E_parallel = 0, constant magnetic moment and physical energy exchange (see docs/analytical_perturbations.rst). +""" + +from pathlib import Path + +import jax +import jax.numpy as jnp +import numpy as np + +from essos.dynamics import Particles, Tracing +from essos.fields import Vmec +from essos.gc_perturbations import AnalyticalVmecAlfvenMode + +field = Vmec(str(Path(__file__).resolve().parents[1]/"input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc"), + ntheta=8, nphi=8, mode_tolerance=.01) +particles = Particles(initial_xyz=jnp.array([[.35, .7, .3], [.4, 1.2, .5]]), + initial_vparallel_over_v=jnp.array([.65, -.7])) +wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4, radial_center=.4, radial_width=.5) + +for name, perturbation in (("equilibrium", None), ("wave", wave)): + trace = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", perturbation=perturbation, + maxtime=2e-7, timestep=1e-8, times_to_trace=9, rtol=1e-9, atol=1e-10, max_steps=1024, + progress=False, devices=jax.devices()[:1]) + energy = np.asarray(trace.energy())/float(particles.energy) - 1 + print(f"{name:12s} failed {int(trace.failed.sum())} max |dE/E| {np.max(abs(energy)):.2e}" + + ("" if perturbation is None else + f" max |dmu/mu| {np.max(abs(np.asarray(trace.trajectories)[:, :, 4]/trace.trajectories[:, :1, 4]-1)):.1e}")) diff --git a/examples/particle_tracing/analytical_alfven_paper_benchmark.py b/examples/particle_tracing/analytical_alfven_paper_benchmark.py deleted file mode 100644 index d0ed00cd..00000000 --- a/examples/particle_tracing/analytical_alfven_paper_benchmark.py +++ /dev/null @@ -1,341 +0,0 @@ -"""Paul et al. (2023), Table 2, vacuum QA / perfect QS, on CPU or GPU. - -From the checkout root: - python -m examples.particle_tracing.analytical_alfven_paper_benchmark - -Defaults to 32 markers per case, 64 trajectories total, at most 120 seconds including -compilation. Uses the existing adaptive8 GC integrator. The low-resolution -equilibrium and axis-loss convention differ from the paper, so numerical -checks and published-value comparisons are reported separately. -""" - -from __future__ import annotations - -import argparse -import csv -import hashlib -import json -import os -from pathlib import Path -import threading -import time -try: - import tomllib -except ModuleNotFoundError: # Python 3.10 - import tomli as tomllib - -from examples.benchmarks.sampling import estimate_interval -from examples.benchmarks.paul_conventions import (CONVENTIONS, convert_births, convert_mode, - load_essos_births, particle_parameters) - -def write_comparison(output, reference, results): - """Persist published values beside ESSOS estimates without a physics pass/fail gate.""" - rows = [] - for case, result in zip(reference["cases"], results): - for metric in ("loss_fraction", "mean_abs_delta_s"): - estimate = result[metric] - rows.append(dict(case=case["name"], metric=metric, paper=case[metric], - essos=estimate["value"], difference=estimate["value"]-case[metric], - approximate_95_low=estimate["interval_95"][0], - approximate_95_high=estimate["interval_95"][1], - reference_in_sampling_interval=bool(estimate["interval_95"][0] - <= case[metric] - <= estimate["interval_95"][1]))) - with (output/"comparison.csv").open("w", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=list(rows[0])) - writer.writeheader() - writer.writerows(rows) - return rows - - -def write_report(output, summary): - reference, rows = summary["reference"], summary["comparisons"] - (output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - report = ["# Paul et al. (2023) vacuum-QA transport comparison", "", - f"Source: [Table 2, Perfect QS]({reference['source']}).", "", - "| Case | Quantity | Paper | ESSOS | Approx. 95% sampling interval |", - "| --- | --- | ---: | ---: | --- |"] - for row in rows: - report.append(f"| {row['case']} | {row['metric']} | {row['paper']:.3f} | " - f"{row['essos']:.4f} | [{row['approximate_95_low']:.4f}, " - f"{row['approximate_95_high']:.4f}] |") - report += ["", f"{summary['total_trajectories']} trajectories total; " - f"{summary['tmax']*1e3:g} ms physical time.", "", - "Numerical conservation checks passed. Quantitative agreement with the paper " - "is not established by this small comparison.", ""] - report.extend(f"- {item}" for item in summary["limitations"]) - (output/"comparison.md").write_text("\n".join(report)+"\n") - - -def report_saved(output, reference): - """Recover tabulated diagnostics without tracing or initializing JAX.""" - import numpy as np - - with np.load(output/"trajectories.npz") as archive: - weights, times = archive["birth_weights"], archive["times"] - results = [] - for index, case in enumerate(reference["cases"]): - states, lcfs = archive[f"states_{index}"], archive[f"loss_times_{index}"] - axes = archive[f"axis_stop_times_{index}"] if f"axis_stop_times_{index}" in archive else np.full_like(lcfs, -1.) - losses = np.where(axes >= 0, axes, lcfs) - drift = archive[f"invariant_drift_{index}"] - valid = (losses[:, None] < 0) | (times < losses[:, None]) - max_drift = float(np.max(np.where(valid, drift, 0.))) - if not np.isfinite(states).all() or not np.isfinite(max_drift) or max_drift > 1e-6: - raise RuntimeError("Saved trajectories fail the numerical checks") - # This archive is written only after both cases pass the failed-marker - # and conservation checks. Frozen finite failed markers cannot reach it. - results.append(dict(name=case["name"], particles=len(weights), - delta_bhat_psi=case["delta_bhat_psi"], lost=int((losses >= 0).sum()), - lcfs_exits=int((lcfs >= 0).sum()), axis_stops=int((axes >= 0).sum()), - failed=0, loss_fraction=estimate_interval(losses >= 0, weights, binary=True), - mean_abs_delta_s=estimate_interval(archive[f"displacement_{index}"], weights), - max_normalized_invariant_drift=max_drift, - minimum_saved_s=float(states[:, :, 0].min()))) - rows = write_comparison(output, reference, results) - summary_file = output/"summary.json" - # Preserve original provenance and timing when a prior summary exists. - if summary_file.exists(): - saved_metadata = json.loads(summary_file.read_text()) - elif "metadata_json" in archive: - saved_metadata = json.loads(str(archive["metadata_json"])) - else: - saved_metadata = None - summary = saved_metadata if saved_metadata is not None else dict( - reference=reference, particles_per_case=len(weights), total_trajectories=2*len(weights), - tmax=float(times[-1]), saved_times=len(times), numerical_checks_passed=True, - quantitative_paper_validation="not established", - setup_metadata="Not stored in the original archive; see the benchmark command/defaults", - limitations=["Low-resolution shipped QA equilibrium; differs from the authors' exact data", - f"Importance-weighted sampling; {len(weights)} proposals per case versus 5000 in the paper", - "Approximate intervals include sampling noise only", - "ESSOS counts LCFS exits; paper also counts s=0 with its singular potential", - "No equilibrium-resolution or timestep convergence study"]) - summary.update(results=results, comparisons=rows, report_rebuilt_from_saved_trajectories=True) - write_report(output, summary) - print(f"Rebuilt comparison tables from saved data in {output}; no particles traced", flush=True) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--particles", type=int, default=32, help="per case; two cases total") - parser.add_argument("--platform", choices=("cpu", "gpu"), default="cpu") - parser.add_argument("--diagnostic-batch-size", type=int, default=128, - help="Bound the device memory used by invariant diagnostics") - parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--births", type=Path, help="Use a prefix of an already-converted saved marker pool") - parser.add_argument("--wout", type=Path, help="Explicit QA equilibrium; bundled reactor-scale input by default") - parser.add_argument("--source-convention", choices=CONVENTIONS, default="essos", - help="Convention of the source births and wave; converted together to ESSOS") - parser.add_argument("--particle-model", choices=CONVENTIONS, default="essos", - help="Measured alpha mass by default; explicit historical library-mass control") - parser.add_argument("--axis-stop-s", type=float, default=1e-8, - help="inner stopping surface for the singular mode; refine for cutoff convergence") - parser.add_argument("--wall-seconds", type=float, default=120.) - parser.add_argument("--report-only", action="store_true", help="rebuild tables from saved data; no tracing") - parser.add_argument("--case", choices=("both", "mode"), default="both", - help="mode runs only the perturbed case and saves diagnostic data") - parser.add_argument("--output", type=Path, - default=Path("examples/benchmarks/results/analytical_alfven_paper_benchmark")) - args = parser.parse_args() - if args.particles < 3 or args.diagnostic_batch_size < 1: - parser.error("Need particles >= 3 and diagnostic-batch-size >= 1") - if not 0 < args.wall_seconds < float("inf"): - parser.error("wall-seconds must be positive and finite") - os.environ.update(JAX_PLATFORMS="cuda" if args.platform == "gpu" else "cpu", ESSOS_CPU_DEVICES="1", - OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1") - if args.platform == "cpu": - os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - started = time.perf_counter() - - def timeout(): - print(f"Stopped at the {args.wall_seconds:g}-second wall-time limit", flush=True) - os._exit(124) - - deadline = threading.Timer(args.wall_seconds, timeout) - deadline.daemon = True - deadline.start() - try: - checkout = Path(__file__).resolve().parents[2] - reference_file = checkout/"examples/benchmarks/references/paul2023_vacuum_qa.toml" - reference = tomllib.loads(reference_file.read_text()) - if args.report_only: - report_saved(args.output, reference) - return - import jax - import numpy as np - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - from essos.constants import ALPHA_PARTICLE_MASS, ONE_EV - from .analytical_alfven_transport import (load_field, make_mode, trace, - invariant_errors) - particle = particle_parameters(args.particle_model, measured_mass=ALPHA_PARTICLE_MASS, - energy_joule=reference["energy_MeV"]*1e6*ONE_EV) - mass, speed = particle["mass_kg"], particle["birth_speed_m_s"] - assert all(device.platform == args.platform for device in jax.devices()) - args.wout = args.wout or checkout/"examples/input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc" - args.helicity, args.m, args.mboz, args.nboz = 0, 15, 16, 16 - args.regular_axis = False - args.tmax, args.saves = reference["tmax_seconds"], 1001 - args.method, args.timestep, args.tolerance = "adaptive8", 5e-8, 1e-9 - args.output.mkdir(parents=True, exist_ok=True) - case_count = 2 if args.case == "both" else 1 - print(f"{args.platform.upper()}; {args.particles} markers x {case_count} cases; tmax={args.tmax:g} s; " - f"adaptive8; hard wall limit {args.wall_seconds:g} s", flush=True) - field, provenance = load_field(args) - provenance["wout_sha256"] = hashlib.sha256(args.wout.read_bytes()).hexdigest() - print(f"Field ready after {time.perf_counter()-started:.1f} s", flush=True) - - rng = np.random.default_rng(args.seed) - if args.births is None: - source_births = (rng.uniform(reference["s_min"], reference["s_max"], args.particles), - rng.uniform(0, 2*np.pi, args.particles), rng.uniform(0, 2*np.pi, args.particles), - rng.uniform(-1, 1, args.particles)) - births = (*convert_births(*source_births, source=args.source_convention), speed) - else: - births = (*load_essos_births(args.births, args.particles, source=args.source_convention), speed) - profiles, _ = jax.vmap(field.profiles)(births[0]) - iota, G, I = np.asarray(profiles).T - B = np.asarray(jax.vmap(field.modB)(*births[:3])) - # Uniform coordinate proposals, with the equilibrium Boozer Jacobian - # as importance weights, target uniform physical volume. Keep the - # same proposals, pitches and weights in both cases. - weights = np.abs(float(field.psi0)*(G+iota*I)/B**2) - weights /= weights.sum() - arrays = dict(birth_s=births[0], birth_theta=births[1], birth_zeta=births[2], - birth_pitch=births[3], birth_weights=weights) - results = [] - for index, case in enumerate(reference["cases"]): - if args.case == "mode" and index == 0: - continue - source_wave = make_mode(field, args, case["delta_bhat_psi"], case["n"], case["omega_rad_s"]) - wave = convert_mode(source_wave, source=args.source_convention) - print(f"Tracing {case['name']}; elapsed {time.perf_counter()-started:.1f} s", flush=True) - result = trace(field, args, births, wave, mass=mass) - # Keep raw evidence even when a subsequent validity check fails. - np.savez_compressed(args.output/f"case_{index}.npz", times=result.times, - states=result.states, loss_times=result.loss_times, - failed_times=result.failed_times, axis_stop_times=result.axis_stop_times, - **{key: value for key, value in arrays.items() if key.startswith("birth_")}) - if result.failed.any() or not np.isfinite(result.states).all(): - failed = np.flatnonzero(result.failed) - lower = float(weights@(result.lost | result.axis_stopped)) - unknown = float(weights@result.failed) - diagnostic = dict(case=case["name"], particles=args.particles, seed=args.seed, **particle, - backend=str(jax.devices()[0]), tmax=args.tmax, - method=args.method, tolerance=args.tolerance, - provenance=provenance, lost=int(result.lost.sum()), - axis_stops=int(result.axis_stopped.sum()), axis_stop_s=args.axis_stop_s, - failed=int(result.failed.sum()), - numerical_checks_passed=False, - empirical_loss_fraction_bounds=[lower, lower+unknown], - bounds_note="Unresolved failures may or may not be lost; these are not confidence intervals", - failed_markers=[dict(index=int(i), birth_s=float(births[0][i]), - birth_pitch=float(births[3][i]), - failed_time=float(result.failed_times[i]), - last_finite_s=float(result.states[i, -1, 0]), - minimum_saved_s=float(result.states[i, :, 0].min())) - for i in failed]) - (args.output/f"case_{index}_diagnostic.json").write_text(json.dumps(diagnostic, indent=2)+"\n") - print(json.dumps(diagnostic), flush=True) - raise RuntimeError(f"{case['name']}: {int(result.failed.sum())} failed markers; " - "loss comparison would be invalid") - drift = invariant_errors(field, wave, result, args.helicity, - batch_size=args.diagnostic_batch_size, mass=mass) - stop_times = np.where(result.axis_stopped, result.axis_stop_times, result.loss_times) - valid = (stop_times[:, None] < 0) | (result.times < stop_times[:, None]) - max_drift = float(np.max(np.where(valid, drift, 0.))) - if max_drift > 1e-6: - raise RuntimeError(f"{case['name']}: invariant drift {max_drift:g} exceeds 1e-6") - displacement = np.abs(result.states[:, -1, 0]-births[0]) - loss_curve = weights@((stop_times[:, None] >= 0) & (stop_times[:, None] <= result.times)) - results.append(dict(name=case["name"], particles=args.particles, **particle, - delta_bhat_psi=case["delta_bhat_psi"], - source_omega_rad_s=float(source_wave.omega), - essos_omega_rad_s=float(wave.omega), - source_potential_volts=float(source_wave.amplitude), - potential_volts=float(wave.amplitude), lost=int((result.lost | result.axis_stopped).sum()), - lcfs_exits=int(result.lost.sum()), axis_stops=int(result.axis_stopped.sum()), - axis_stop_s=args.axis_stop_s, - failed=int(result.failed.sum()), - loss_fraction=estimate_interval(result.lost | result.axis_stopped, weights, binary=True), - mean_abs_delta_s=estimate_interval(displacement, weights), - max_normalized_invariant_drift=max_drift, - minimum_saved_s=float(result.states[:, :, 0].min()))) - for key, value in dict(states=result.states, loss_times=result.loss_times, - axis_stop_times=result.axis_stop_times, - loss_curve=loss_curve, displacement=displacement, - invariant_drift=drift).items(): - arrays[f"{key}_{index}"] = value - (args.output/f"case_{index}_summary.json").write_text(json.dumps(results[-1], indent=2)+"\n") - print(json.dumps(results[-1]), flush=True) - - if args.case == "mode": - (args.output/"mode_summary.json").write_text(json.dumps(results[-1], indent=2)+"\n") - return - rows = write_comparison(args.output, reference, results) - fig, axes = plt.subplots(1, 3, figsize=(13, 4), constrained_layout=True) - colors = ("tab:blue", "tab:orange") - for index, (case, color) in enumerate(zip(reference["cases"], colors)): - axes[0].plot(result.times*1e3, 100*arrays[f"loss_curve_{index}"], - color=color, label=f"ESSOS: {case['name']}") - axes[0].scatter([1.], [100*case["loss_fraction"]], marker="D", s=40, - color=color, edgecolor="black", zorder=5, - label=f"Paper endpoint: {case['name']}") - axes[0].set(xlabel="Time (ms)", ylabel="Volume-weighted loss fraction (%)", - title="ESSOS curves; published endpoints") - axes[0].legend(fontsize=7) - for ax, metric, scale, title in zip(axes[1:], ("loss_fraction", "mean_abs_delta_s"), - (100., 1.), ("Loss fraction at 1 ms (%)", r"Mean $|\Delta s|$ at 1 ms")): - for index, (case, measured, color) in enumerate(zip(reference["cases"], results, colors)): - estimate = measured[metric] - low, high = estimate["interval_95"] - ax.scatter(index-.1, scale*case[metric], marker="D", color="black", s=40, - label="Paper, Table 2" if index == 0 else None) - ax.errorbar(index+.1, scale*estimate["value"], - yerr=scale*np.array([[estimate["value"]-low], [high-estimate["value"]]]), - fmt="o", color=color, capsize=4, - label="ESSOS, approx. 95% interval" if index == 0 else None) - ax.set(xticks=[0, 1], xticklabels=["Unperturbed", "m=15 mode"], title=title, - xlim=(-.5, 1.5)) - ax.set_ylim(bottom=0) - ax.legend(fontsize=7) - for ax in axes: - ax.grid(alpha=.2) - fig.suptitle(f"Paul et al. (2023), Table 2: vacuum QA / perfect QS\n" - f"ESSOS: {args.particles} markers/case, {args.platform.upper()} adaptive8; " - "low-resolution equilibrium, sampling intervals only") - for extension in ("png", "svg"): - fig.savefig(args.output/f"paper_comparison.{extension}", dpi=180) - plt.close(fig) - summary = dict(reference=reference, reference_file=str(reference_file.relative_to(checkout)), - provenance=provenance, backend=str(jax.devices()[0]), - particles_per_case=args.particles, total_trajectories=2*args.particles, - tmax=args.tmax, saved_times=len(result.times), seed=args.seed, **particle, - source_convention=args.source_convention, birth_coordinate_convention="essos", - birth_pool=None if args.births is None else str(args.births.resolve()), - method=args.method, tolerance=args.tolerance, initial_timestep=args.timestep, - axis_stop_s=args.axis_stop_s, loss_definition="LCFS exits plus singular-mode axis stops", - platform=args.platform, diagnostic_batch_size=args.diagnostic_batch_size, - numerical_checks_passed=True, quantitative_paper_validation="not established", - results=results, comparisons=rows, wall_seconds=time.perf_counter()-started, - wall_limit_seconds=args.wall_seconds, - limitations=[f"{args.particles} markers per case versus the paper's 5000; intervals are approximate", - "Importance-weighted proposals approximate uniform physical volume", - "Exact published equilibrium/runtime unconfirmed; no equilibrium/step convergence study", - "Field normalized to innermost B00=5.86 T and minor radius=1.70 m", - "Historical SIMSOPT convention is explicit; the paper's exact runtime is unconfirmed", - "Axis stops use a finite cutoff and chord interpolation; refine cutoff and timestep", - "Intervals include sampling noise only, not model or numerical uncertainty"]) - np.savez_compressed(args.output/"trajectories.npz", times=result.times, - metadata_json=json.dumps(summary), **arrays) - write_report(args.output, summary) - print(f"Saved comparison plot, CSV, report and trajectories in {args.output}; " - f"total {summary['wall_seconds']:.1f} s", flush=True) - finally: - deadline.cancel() - - -if __name__ == "__main__": - main() diff --git a/examples/particle_tracing/analytical_alfven_transport.py b/examples/particle_tracing/analytical_alfven_transport.py deleted file mode 100644 index 30787b15..00000000 --- a/examples/particle_tracing/analytical_alfven_transport.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Shared field, mode and invariant helpers for the Paul loss benchmark. - -Run examples.particle_tracing.analytical_alfven_paper_benchmark for the -comparison, or vmec_alfven_cpu_smoke for the small standalone example. -""" - -import jax -import jax.numpy as jnp -import numpy as np - -from essos.boozer import BoozerField, psi0_from_vmec, trace_boozer -from essos.constants import ALPHA_PARTICLE_MASS as MASS, ALPHA_PARTICLE_CHARGE as CHARGE -from essos.constants import FUSION_ALPHA_PARTICLE_ENERGY -from essos.perturbations import AnalyticalAlfvenMode, wave_frame_invariant - -MINOR_RADIUS = 1.70 - - -def load_field(args): - if args.wout is None: - s = np.linspace(.001, .999, 64) - field = BoozerField.from_booz(s, np.stack([5.86+0*s, -1.1*np.sqrt(s)]), - [0, 1], [0, args.helicity], .4+.08*s, - 5.86*7.74+0*s, 0*s, -.5*5.86*MINOR_RADIUS**2, - max(1, abs(args.helicity)), angle_grid=None) - return field, {"kind": "analytic QS benchmark", "helicity": args.helicity} - from booz_xform_jax import Booz_xform - from netCDF4 import Dataset - - booz = Booz_xform(verbose=0, mboz=args.mboz, nboz=args.nboz) - booz.read_wout(str(args.wout), flux=False) - booz.run() - with Dataset(args.wout) as nc: - minor = float(nc.variables["Aminor_p"][...]) - phi_edge = float(nc.variables["phi"][-1]) - xm, xn = np.asarray(booz.xm_b), np.asarray(booz.xn_b) - b = np.asarray(booz.bmnc_b).copy() - b00 = b[(xm == 0) & (xn == 0), 0].item() - bscale, lscale = 5.86/b00, MINOR_RADIUS/minor - b *= bscale - b[xn != args.helicity*xm] = 0. - field = BoozerField.from_booz(booz.s_b, b, xm, xn, booz.iota, - np.asarray(booz.Boozer_G)*bscale*lscale, - np.asarray(booz.Boozer_I)*bscale*lscale, - psi0_from_vmec(phi_edge)*bscale*lscale**2, int(booz.nfp), - mode_tolerance=1e-7, angle_grid=None) - return field, {"kind": "VMEC transformed to Boozer, QS filtered", "wout": str(args.wout), - "helicity": args.helicity, "B_scale": bscale, "length_scale": lscale, - "mboz": args.mboz, "nboz": args.nboz} - - -def trace(field, args, births, wave, *, tmax=None, n_save=None, mass=MASS): - s, theta, zeta, pitch, speed = births - return trace_boozer(field, s, theta, zeta, pitch, speed=speed, mass=mass, charge=CHARGE, - tmax=args.tmax if tmax is None else tmax, timestep=args.timestep, - n_save=args.saves if n_save is None else n_save, method=args.method, - tolerance=args.tolerance, perturbation=wave, compact=False, progress=False) - - -def make_mode(field, args, delta, n, omega): - (iota, G, I), _ = field.profiles(1.) - # Set alpha_hat at the edge; potential amplitude is in physical volts. - amplitude = delta*MINOR_RADIUS/args.m*omega*float(G+iota*I)/float(n-args.m*iota) - return AnalyticalAlfvenMode(args.m, n, omega, amplitude, regularize_axis=args.regular_axis, - axis_stop_s=getattr(args, "axis_stop_s", 1e-8)) - - -def invariant_errors(field, wave, result, helicity, *, batch_size=None, mass=MASS): - """Wave-frame drift, optionally evaluated in bounded particle batches.""" - count = len(result.states) - batch_size = count if batch_size is None else batch_size - if batch_size < 1: - raise ValueError("batch_size must be positive") - evaluate = jax.jit(jax.vmap(lambda orbit, moment: - jax.vmap(lambda y, t: wave_frame_invariant(field, wave, y, moment, mass, CHARGE, - t, helicity=helicity))(orbit, result.times))) - errors = [] - for start in range(0, count, batch_size): - values = result.states[start:start+batch_size] - s, theta, zeta, vpar, speed = np.moveaxis(values, -1, 0) - ys = jnp.stack([np.sqrt(s)*np.cos(theta), np.sqrt(s)*np.sin(theta), zeta, vpar], -1) - B0 = jax.vmap(field.modB)(s[:, 0], theta[:, 0], zeta[:, 0]) - mu = (speed[:, 0]**2-vpar[:, 0]**2)/(2*B0) - invariant = np.asarray(evaluate(ys, mu)) - # Avoid a spurious blow-up at K=0 while retaining the existing scale. - scale = np.maximum(np.abs(invariant[:, :1]), FUSION_ALPHA_PARTICLE_ENERGY) - errors.append(np.abs(invariant-invariant[:, :1])/scale) - return np.concatenate(errors) diff --git a/examples/particle_tracing/paul_alfven_benchmark.py b/examples/particle_tracing/paul_alfven_benchmark.py new file mode 100644 index 00000000..80e477c8 --- /dev/null +++ b/examples/particle_tracing/paul_alfven_benchmark.py @@ -0,0 +1,142 @@ +"""Alpha losses with a resonant Alfven wave: Paul, Mynick & Bhattacharjee (2023), Table 2. + +Vacuum QA, m=15, n=7, 399000 rad/s, edge m*alpha/a = 1e-3, 3.52 MeV, 1 ms, in a +Boozer background without QS-breaking harmonics ("Perfect QS") and in the full +VMEC equilibrium, which sees the same Boozer wave through VmecBoozerMap. +Needs ``pip install -e '.[booz]'``. From the checkout root:: + + python examples/particle_tracing/paul_alfven_benchmark.py + +Set PARTICLES and HISTORICAL below (the docs table uses 100 and True). The paper used 5000 +markers and its exact equilibrium is unknown, so compare only within the printed sampling +intervals. HISTORICAL reproduces the sign and +alpha-mass conventions of the 2023 SIMSOPT adapter (angles, pitch, omega and +Phi reflected; mass 2 m_p + 2 m_n). Markers are uniform in coordinates and +weighted by the Boozer Jacobian, i.e. uniform in physical volume. Singular +inner stops (s < 1e-8) count as losses, as in the paper. +""" + +from pathlib import Path + +import jax +import jax.numpy as jnp +import numpy as np +from netCDF4 import Dataset + +from essos.boozer import BoozerField, psi0_from_vmec, trace_boozer +from essos.constants import (ALPHA_PARTICLE_CHARGE, ALPHA_PARTICLE_MASS, FUSION_ALPHA_PARTICLE_ENERGY, + NEUTRON_MASS, PROTON_MASS) +from essos.dynamics import Particles, Tracing +from essos.fields import VMEC_WOUT_ARRAYS, Vmec +from essos.gc_perturbations import MappedBoozerPerturbation, VmecBoozerMap +from essos.perturbations import AnalyticalAlfvenMode + +M, N, OMEGA, EDGE_ALPHA = 15, 7, 399000., 1e-3 +BACKGROUNDS = ("Boozer / Perfect QS", "VMEC / full equilibrium") +PAPER = {BACKGROUNDS[0]: (.066, .162), BACKGROUNDS[1]: (.083, .194)} # unperturbed, wave +WOUT = Path(__file__).resolve().parents[1]/"input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc" +PARTICLES, HISTORICAL, TMAX, SEED = 32, False, 1e-3, 42 +PLOT = None # path of an image with the loss curves + + +def load(wout): + """Booz_xform of the equilibrium scaled to B00 = 5.86 T, a = 1.7 m, in both formulations.""" + from booz_xform_jax import Booz_xform + + booz = Booz_xform(verbose=0, mboz=16, nboz=16) + booz.read_wout(str(wout), flux=False) + booz.run() + xm, xn, bmnc = np.asarray(booz.xm_b), np.asarray(booz.xn_b), np.asarray(booz.bmnc_b) + with Dataset(wout) as nc: + tables = {key: np.asarray(nc.variables[key][:]) for key in VMEC_WOUT_ARRAYS} + nfp, ns, phi = int(nc.variables["nfp"][...]), int(nc.variables["ns"][...]), float(nc.variables["phi"][-1]) + b, a = 5.86/bmnc[(xm == 0) & (xn == 0), 0].item(), 1.7/float(nc.variables["Aminor_p"][...]) + for key, factor in (("rmnc", a), ("zmns", a), ("Aminor_p", a), ("bmnc", b), ("gmnc", a**3), ("bsubsmns", a*b), + ("bsubumnc", a*b), ("bsubvmnc", a*b), ("bsupumnc", b/a), ("bsupvmnc", b/a)): + tables[key] = tables[key]*factor + vmec = Vmec.from_arrays(nfp, ns, **{key: jnp.asarray(value) for key, value in tables.items()}, + ntheta=8, nphi=8, mode_tolerance=1e-7) + + def boozer(keep, tolerance): + return BoozerField.from_booz(booz.s_b, bmnc*b*keep[:, None], xm, xn, booz.iota, + np.asarray(booz.Boozer_G)*a*b, np.asarray(booz.Boozer_I)*a*b, + psi0_from_vmec(phi)*a*a*b, nfp, mode_tolerance=tolerance, angle_grid=None) + + return (boozer(xn == 0, 1e-7), boozer(xn > -np.inf, 1e-6), vmec, VmecBoozerMap.from_booz_xform(booz)) + + +def wilson(loss, weights): + """Weighted loss fraction and approximate 95% interval (Wilson, Kish effective count).""" + p, n, z = float(weights@loss), 1/float(weights@weights), 1.959964 + center = (p + z*z/(2*n))/(1 + z*z/n) + radius = z*np.sqrt(p*(1-p)/n + z*z/(4*n*n))/(1 + z*z/n) + return p, max(0., center-radius), min(1., center+radius) + + +sign = -1. if HISTORICAL else 1. +mass = 2*(PROTON_MASS + NEUTRON_MASS) if HISTORICAL else ALPHA_PARTICLE_MASS +energy, charge = float(FUSION_ALPHA_PARTICLE_ENERGY), ALPHA_PARTICLE_CHARGE +speed = np.sqrt(2*energy/mass) +qs, full, vmec, mapping = load(WOUT) + +rng = np.random.default_rng(SEED) +n = PARTICLES +s, theta, zeta, pitch = rng.uniform(.25, .75, n), *(rng.uniform(0, 2*np.pi, n) for _ in range(2)), rng.uniform(-1, 1, n) +theta, zeta, pitch = sign*theta, sign*zeta, sign*pitch +births = jnp.asarray(np.stack([s, theta, zeta], 1)) +native = jax.jit(jax.vmap(mapping.inverse))(births) +assert float(jnp.max(abs(jax.vmap(mapping)(native) - births))) < 1e-10, "birth map failed" + +(iota, G, I), _ = full.profiles(1.) +# alpha_hat at the edge fixes the potential amplitude in volts +wave = AnalyticalAlfvenMode(M, N, sign*OMEGA, sign*EDGE_ALPHA*1.7/M*OMEGA*float(G + iota*I)/float(N - M*iota), + regularize_axis=False) +times = np.linspace(0., TMAX, 201) +curves = {} +for name, field in zip(BACKGROUNDS, (qs, full)): + profiles, _ = jax.vmap(field.profiles)(jnp.asarray(s)) + weights = np.abs(float(field.psi0)*(profiles[:, 1] + profiles[:, 0]*profiles[:, 2]) + / np.asarray(jax.vmap(field.modB)(jnp.asarray(s), jnp.asarray(theta), jnp.asarray(zeta)))**2) + weights /= weights.sum() + for case, perturbation in enumerate((None, wave)): + if name == BACKGROUNDS[0]: + out = trace_boozer(field, s, theta, zeta, pitch, speed=speed, mass=mass, charge=charge, + tmax=TMAX, timestep=5e-8, n_save=201, method="adaptive8", tolerance=1e-9, + perturbation=perturbation, compact=False, progress=False) + failed, exits, inner = out.failed, out.lost, out.axis_stopped + stop = np.where(inner, out.axis_stop_times, out.loss_times) + stop = np.where(stop >= 0, stop, np.inf) + else: + perturbation = None if perturbation is None else MappedBoozerPerturbation(full, perturbation, mapping) + particles = Particles(initial_xyz=native, initial_vparallel_over_v=jnp.asarray(pitch), + mass=mass, energy=energy) + out = Tracing(field=vmec, particles=particles, model="GuidingCenterAdaptative", + perturbation=perturbation, maxtime=TMAX, timestep=5e-9, times_to_trace=201, + rtol=1e-8, atol=1e-8, max_steps=200000, progress=False, particle_batch_size=8, + devices=jax.devices()[:1]) + failed, exits = out.failed, np.isfinite(out.lcfs_times) + inner = out.axis_stopped + stop = np.minimum(out.lcfs_times, out.axis_stop_times) + if failed.any(): + raise RuntimeError(f"{name}: {int(failed.sum())} failed markers; the loss fraction is undefined") + curves[name, case] = weights@(stop[:, None] <= times) + p, lo, hi = wilson(np.isfinite(stop), weights) + print(f"{name:24s} {'wave' if case else 'none':5s} loss {100*p:6.2f}% [{100*lo:5.2f}, {100*hi:5.2f}] " + f"paper {100*PAPER[name][case]:5.1f}% (LCFS exits {int(exits.sum())}, inner stops {int(inner.sum())})", + flush=True) +if PLOT: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(figsize=(8, 5), constrained_layout=True) + for k, ((name, case), curve) in enumerate(curves.items()): + ax.step(times*1e3, 100*curve, where="post", color=f"C{k}", ls="-" if case else "--", + label=f"{name}, {'m=15 wave' if case else 'unperturbed'}") + ax.plot(TMAX*1e3, 100*PAPER[name][case], "x", color=f"C{k}", ms=9, mew=2) + ax.set(xlabel="Time [ms]", ylabel="Volume-weighted loss fraction [%]", ylim=(0, None), + title=f"{n} markers per curve; crosses: Paul et al. (2023), Table 2") + ax.legend(fontsize=8, loc="upper left") + ax.grid(alpha=.25) + fig.savefig(PLOT, dpi=110) + diff --git a/examples/particle_tracing/vmec_alfven_cpu_smoke.py b/examples/particle_tracing/vmec_alfven_cpu_smoke.py deleted file mode 100644 index 1828adfa..00000000 --- a/examples/particle_tracing/vmec_alfven_cpu_smoke.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Four short CPU trajectories through the existing VMEC GC integrator. - -Run python -m examples.particle_tracing.vmec_alfven_cpu_smoke from the checkout. -The 120 s wall limit includes imports and compilation. The native VMEC wave -is a smoke test, not the identical Boozer harmonic of the Paul benchmark. -""" - -import json -import os -from pathlib import Path -import threading -import time - - -def main(): - os.environ.update(JAX_PLATFORMS="cpu", ESSOS_CPU_DEVICES="1", CUDA_VISIBLE_DEVICES="-1", - OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1") - started = time.perf_counter() - - def stop(): - print("VMEC wave smoke test stopped at its 120-second CPU limit", flush=True) - os._exit(124) - - deadline = threading.Timer(120., stop) - deadline.daemon = True - deadline.start() - try: - import jax - import jax.numpy as jnp - import numpy as np - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - from essos.dynamics import Particles, Tracing - from essos.fields import Vmec - from essos.gc_perturbations import AnalyticalVmecAlfvenMode - - root = Path(__file__).resolve().parents[2] - field = Vmec(str(root/"examples/input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc"), - ntheta=8, nphi=8, mode_tolerance=.01) - particles = Particles(initial_xyz=jnp.array([[.35, .7, .3], [.4, 1.2, .5]]), - initial_vparallel_over_v=jnp.array([.65, -.7])) - wave = AnalyticalVmecAlfvenMode(3, 2, 9e5, 2e4, radial_center=.4, radial_width=.5) - results, traces, arrays = [], [], {} - for name, perturbation in (("equilibrium", None), ("wave", wave)): - trace = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", - perturbation=perturbation, maxtime=2e-7, timestep=1e-8, - times_to_trace=9, rtol=1e-9, atol=1e-10, max_steps=1024, - progress=False, devices=jax.devices()[:1]) - if trace.failed.any() or trace.boundary_hits.any() or not np.isfinite(trace.trajectories).all(): - raise AssertionError("Smoke test requires complete finite VMEC trajectories") - states = np.asarray(trace.trajectories) - energy = np.asarray(trace.energy()) - B_s = np.asarray(jax.vmap(jax.vmap(lambda x: field.B_covariant(x)[0]))(states[:, :, :3])) - result = dict(case=name, particles=2, failures=int(trace.failed.sum()), - max_relative_kinetic_energy_change=float(np.max(abs(energy/float(particles.energy)-1))), - max_abs_radial_covariant_B_Tm=float(np.max(abs(B_s)))) - if perturbation is not None: - result["max_relative_mu_change"] = float(np.max(abs(states[:, :, 4]/states[:, :1, 4]-1))) - assert result["max_relative_mu_change"] < 1e-12 - results.append(result) - arrays.update({f"{name}_states": states, f"{name}_energy": energy, f"{name}_B_s": B_s}) - traces.append(trace) - print(f"Completed VMEC {name}: two particles", flush=True) - assert results[0]["max_relative_kinetic_energy_change"] < 1e-4 - output = root/"examples/benchmarks/results/vmec_alfven_cpu_smoke" - output.mkdir(parents=True, exist_ok=True) - summary = dict(passed=True, platform="cpu", total_trajectories=4, - simulated_time_s=2e-7, time_limit_s=120, cases=results, - model="Existing GuidingCenterAdaptative with full VMEC covariant field", - perturbation="Native VMEC-angle analytical mode; not a mapped Paul benchmark", - elapsed_seconds_before_plot=time.perf_counter()-started) - times = np.asarray(traces[0].times) - np.savez_compressed(output/"trajectories.npz", times=times, **arrays) - (output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), constrained_layout=True) - for marker in range(2): - for name, style in (("equilibrium", "--"), ("wave", "-")): - color = f"C{marker}" - label = f"Marker {marker+1}: {name}" - axes[0].plot(times*1e9, arrays[f"{name}_states"][marker, :, 0], style, color=color, label=label) - axes[1].plot(times*1e9, arrays[f"{name}_energy"][marker]/float(particles.energy)-1, - style, color=color) - axes[2].plot(times*1e9, arrays["wave_B_s"][marker], color=f"C{marker}") - axes[0].set(ylabel="Toroidal flux s", title="Existing adaptive VMEC GC solver") - axes[0].legend(fontsize=7) - axes[1].set(ylabel="Kinetic energy change / birth energy", title="Wave work is allowed") - axes[2].set(ylabel="Covariant radial B_s [T m]", title="Radial covariant field retained") - for ax in axes: - ax.set_xlabel("Time [ns]") - ax.grid(alpha=.2) - fig.suptitle("VMEC analytical-wave smoke test: four CPU trajectories") - for extension in ("png", "svg"): - fig.savefig(output/f"vmec_alfven_smoke.{extension}", dpi=160) - plt.close(fig) - print(json.dumps(summary, indent=2), flush=True) - finally: - deadline.cancel() - - -if __name__ == "__main__": - main() diff --git a/examples/particle_tracing/vmec_alfven_paper_benchmark.py b/examples/particle_tracing/vmec_alfven_paper_benchmark.py deleted file mode 100644 index f18dd5d9..00000000 --- a/examples/particle_tracing/vmec_alfven_paper_benchmark.py +++ /dev/null @@ -1,347 +0,0 @@ -"""Full-geometry VMEC comparison to Paul (2023), Table 2, QA vac / Equil. - -Uses the identical Boozer-angle potential, mapped into VMEC, and the existing -adaptive GC integrator. Defaults to 32 markers/case, 1 ms, CPU, 120 s wall cap. -Run larger samples or GPU jobs explicitly; partial cases are saved immediately. -""" - -import argparse -import hashlib -import json -import os -from pathlib import Path -import threading -import time -try: - import tomllib -except ModuleNotFoundError: # Python 3.10 - import tomli as tomllib - -from examples.benchmarks.paul_conventions import (CONVENTIONS, convert_births, convert_mode, - load_essos_births, particle_parameters) - - -def load_fields(wout, *, mode_tolerance=1e-7, boozer_mode_tolerance=1e-6, representation="raw"): - """Load the same scaled, full equilibrium in both coordinate formulations.""" - import jax.numpy as jnp - import numpy as np - from netCDF4 import Dataset - from booz_xform_jax import Booz_xform - from essos.boozer import BoozerField, psi0_from_vmec - from essos.fields import Vmec, VMEC_WOUT_ARRAYS - from essos.gc_perturbations import VmecBoozerMap - - booz = Booz_xform(verbose=0, mboz=16, nboz=16) - booz.read_wout(str(wout), flux=False) - booz.run() - mapping = VmecBoozerMap.from_booz_xform(booz) - m, n = np.asarray(booz.xm_b), np.asarray(booz.xn_b) - bscale = 5.86/np.asarray(booz.bmnc_b)[(m == 0) & (n == 0), 0].item() - with Dataset(wout) as nc: - lscale = 1.70/float(nc.variables["Aminor_p"][...]) - phi = float(nc.variables["phi"][-1]) - tables = {key: np.asarray(nc.variables[key][:]) for key in VMEC_WOUT_ARRAYS} - nfp, ns = int(nc.variables["nfp"][...]), int(nc.variables["ns"][...]) - for key in ("rmnc", "zmns", "Aminor_p"): - tables[key] *= lscale - tables["bmnc"] *= bscale - for key in ("bsubsmns", "bsubumnc", "bsubvmnc"): - tables[key] *= bscale*lscale - for key in ("bsupumnc", "bsupvmnc"): - tables[key] *= bscale/lscale - tables["gmnc"] *= lscale**3 - field = Vmec.from_arrays(nfp, ns, **{key: jnp.asarray(value) for key, value in tables.items()}, - ntheta=8, nphi=8, mode_tolerance=mode_tolerance) - background = BoozerField.from_booz(booz.s_b, np.asarray(booz.bmnc_b)*bscale, m, n, - booz.iota, np.asarray(booz.Boozer_G)*bscale*lscale, - np.asarray(booz.Boozer_I)*bscale*lscale, - psi0_from_vmec(phi)*bscale*lscale**2, nfp, - mode_tolerance=boozer_mode_tolerance, angle_grid=None) - if representation != "raw": - raise ValueError(f"Unknown equilibrium representation: {representation}") - return field, background, mapping, dict(B_scale=bscale, length_scale=lscale) - - -def main(): - root = Path(__file__).resolve().parents[2] - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--wout", type=Path, default=root/"examples/input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc") - parser.add_argument("--output", type=Path, default=root/"examples/benchmarks/results/vmec_alfven_paper_benchmark") - parser.add_argument("--particles", type=int, default=32, help="Markers per case; two cases") - parser.add_argument("--tmax", type=float, default=1e-3) - parser.add_argument("--saves", type=int, default=201) - parser.add_argument("--timestep", type=float, default=5e-9) - parser.add_argument("--tolerance", type=float, default=1e-8) - parser.add_argument("--mode-tolerance", type=float, default=1e-7) - parser.add_argument("--boozer-mode-tolerance", type=float, default=1e-6) - parser.add_argument("--representation", choices=("raw",), default="raw", - help="Full native VMEC field") - parser.add_argument("--source-convention", choices=CONVENTIONS, default="essos") - parser.add_argument("--particle-model", choices=CONVENTIONS, default="essos") - parser.add_argument("--max-steps", type=int, default=200000) - parser.add_argument("--batch-size", type=int, default=8) - parser.add_argument("--diagnostic-batch-size", type=int, default=128, - help="Bound device memory while evaluating saved kinetic energies") - parser.add_argument("--wall-seconds", type=float, default=120.) - parser.add_argument("--platform", choices=("cpu", "gpu"), default="cpu") - parser.add_argument("--births", type=Path, help="Optional earlier Boozer benchmark trajectories.npz") - parser.add_argument("--resume", action="store_true", help="Reuse completed cases after checking configuration and births") - parser.add_argument("--report-only", action="store_true", help="Replot completed saved cases without tracing") - parser.add_argument("--seed", type=int, default=42) - args = parser.parse_args() - if args.report_only: - report_saved(args.output) - return - if args.particles < 2 or args.tmax <= 0 or args.wall_seconds <= 0 or args.diagnostic_batch_size < 1: - parser.error("Need at least two markers, positive tmax, wall-seconds and diagnostic-batch-size") - os.environ.update(JAX_PLATFORMS="cuda" if args.platform == "gpu" else "cpu", ESSOS_CPU_DEVICES="1", - OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1") - if args.platform == "cpu": - os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - started = time.perf_counter() - args.output.mkdir(parents=True, exist_ok=True) - - def timeout(): - print(f"VMEC Paul benchmark reached its {args.wall_seconds:g}-second wall limit; saved cases remain available", flush=True) - os._exit(124) - - deadline = threading.Timer(args.wall_seconds, timeout) - deadline.daemon = True - deadline.start() - try: - import jax - import jax.numpy as jnp - import numpy as np - from essos.dynamics import Particles, Tracing - from essos.constants import ALPHA_PARTICLE_MASS, ONE_EV - from essos.gc_perturbations import MappedBoozerPerturbation - from examples.particle_tracing.analytical_alfven_transport import make_mode - from examples.benchmarks.sampling import estimate_interval - reference = tomllib.loads((root/"examples/benchmarks/references/paul2023_vacuum_qa_equilibrium.toml").read_text()) - particle = particle_parameters(args.particle_model, measured_mass=ALPHA_PARTICLE_MASS, - energy_joule=reference["energy_MeV"]*1e6*ONE_EV) - # No QS filtering: match the paper's Equil. column, not Perfect QS. - field, background, mapping, scales = load_fields(args.wout, mode_tolerance=args.mode_tolerance, - boozer_mode_tolerance=args.boozer_mode_tolerance, representation=args.representation) - bscale, lscale = scales["B_scale"], scales["length_scale"] - rng = np.random.default_rng(args.seed) - if args.births is None: - s = rng.uniform(.25, .75, args.particles) - theta = rng.uniform(0, 2*np.pi, args.particles) - zeta = rng.uniform(0, 2*np.pi, args.particles) - pitch = rng.uniform(-1, 1, args.particles) - s, theta, zeta, pitch = convert_births(s, theta, zeta, pitch, source=args.source_convention) - else: - s, theta, zeta, pitch = load_essos_births(args.births, args.particles, source=args.source_convention) - boozer_births = jnp.asarray(np.stack([s, theta, zeta], axis=1)) - native_births = jax.jit(jax.vmap(mapping.inverse))(boozer_births) - residual = float(np.max(abs(np.asarray(jax.vmap(mapping)(native_births))-boozer_births))) - if residual > 1e-10: - raise AssertionError(f"Birth coordinate map failed: {residual:g}") - profiles, _ = jax.vmap(background.profiles)(jnp.asarray(s)) - iota, G, I = profiles.T - B = jax.vmap(background.modB)(jnp.asarray(s), jnp.asarray(theta), jnp.asarray(zeta)) - weights = np.array(abs(background.psi0*(G+iota*I)/B**2)) - weights /= weights.sum() - config = dict(platform=args.platform, particles_per_case=args.particles, tmax_s=args.tmax, **particle, - wall_seconds=args.wall_seconds, tolerance=args.tolerance, mode_tolerance=args.mode_tolerance, - boozer_mode_tolerance=args.boozer_mode_tolerance, representation=args.representation, - source_convention=args.source_convention, birth_coordinate_convention="essos", - saves=args.saves, initial_timestep=args.timestep, batch_size=args.batch_size, - max_steps=args.max_steps, seed=args.seed, wout=str(args.wout), - wout_sha256=hashlib.sha256(args.wout.read_bytes()).hexdigest(), B_scale=bscale, - length_scale=lscale, max_birth_map_residual=residual, reference=reference, - wave="Mapped uniform-radial Boozer potential; m=15,n=7; source omega=399000 rad/s", - loss_definition="LCFS exit plus singular-wave inner stop at s=1e-8, reported separately") - saved_results = [] - if args.resume: - previous = json.loads((args.output/"configuration.json").read_text()) - for key in config.keys()-{"wall_seconds", "max_birth_map_residual"}: - if key == "wout_sha256" and key not in previous: - continue # Legacy configuration; preserve its existing resume checks. - if key in particle and key not in previous and args.particle_model == "essos": - continue # Earlier runs used the same measured-mass default at 3.52 MeV. - if previous.get(key) != config[key]: - raise ValueError(f"Cannot resume a different configuration: {key}") - with np.load(args.output/"births.npz") as saved: - for key, values in (("birth_s", s), ("birth_theta", theta), ("birth_zeta", zeta), - ("birth_pitch", pitch), ("birth_weights", weights)): - np.testing.assert_allclose(saved[key], values, rtol=1e-13, atol=1e-15, - err_msg=f"Cannot resume different {key}") - saved_results = json.loads((args.output/"progress.json").read_text())["cases"] - np.savez_compressed(args.output/"births.npz", birth_s=s, birth_theta=theta, birth_zeta=zeta, - birth_pitch=pitch, birth_weights=weights, native_births=native_births, - metadata_json=json.dumps(config)) - (args.output/"configuration.json").write_text(json.dumps(config, indent=2)+"\n") - particles = Particles(initial_xyz=native_births, initial_vparallel_over_v=jnp.asarray(pitch), - mass=particle["mass_kg"], energy=particle["energy_joule"]) - mode_args = argparse.Namespace(m=15, regular_axis=False, axis_stop_s=1e-8) - results, curves, energies = [], [], [] - for index, case in enumerate(reference["cases"]): - if index < len(saved_results): - with np.load(args.output/f"case_{index}.npz") as saved: - if len(saved["status"]) != args.particles or saved["times"][-1] != args.tmax: - raise ValueError("Saved case dimensions/duration differ from this run") - times = saved["times"] - curves.append((saved["loss_curve"], saved["unresolved_curve"])) - energies.append(saved["energy_change"]) - results.append(saved_results[index]) - print(f"Restored completed VMEC {case['name']} case", flush=True) - continue - source_mode = make_mode(background, mode_args, case["delta_bhat_psi"], case["n"], case["omega_rad_s"]) - mode = convert_mode(source_mode, source=args.source_convention) - wave = None if index == 0 else MappedBoozerPerturbation(background, mode, mapping) - print(f"Tracing VMEC {case['name']}: {args.particles} particles, {args.tmax:g} s", flush=True) - trace = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", perturbation=wave, - maxtime=args.tmax, timestep=args.timestep, times_to_trace=args.saves, - rtol=args.tolerance, atol=args.tolerance, max_steps=args.max_steps, - progress=False, particle_batch_size=args.batch_size, devices=jax.devices()[:1]) - states, times = np.asarray(trace.trajectories), np.asarray(trace.times) - stop_times = np.minimum(trace.lcfs_times, trace.axis_stop_times) - lost = np.isfinite(stop_times) - final_s = np.where(np.isfinite(trace.lcfs_times), trace.lcfs_states[:, 0], states[:, -1, 0]) - final_s = np.where(trace.axis_stopped, trace.axis_stop_states[:, 0], final_s) - curve = weights@(stop_times[:, None] <= times[None, :]) - unresolved = weights@(trace.failure_times[:, None] <= times[None, :]) - energy = energy_changes(trace, args.diagnostic_batch_size) - np.savez_compressed(args.output/f"case_{index}.npz", times=times, states=states, - status=trace.status, lcfs_times=trace.lcfs_times, lcfs_states=trace.lcfs_states, - axis_stop_times=trace.axis_stop_times, axis_stop_states=trace.axis_stop_states, - failure_times=trace.failure_times, energy_change=energy, loss_curve=curve, - unresolved_curve=unresolved, final_s=final_s, weights=weights) - failed = int(trace.failed.sum()) - result = dict(name=case["name"], failed=failed, lcfs_exits=int(trace.boundary_hits.sum()), - source_omega_rad_s=float(source_mode.omega), essos_omega_rad_s=float(mode.omega), - source_potential_volts=float(source_mode.amplitude), potential_volts=float(mode.amplitude), - axis_stops=int(trace.axis_stopped.sum()), weighted_confirmed_loss=float(weights@lost), - weighted_unresolved=float(weights@trace.failed), - max_relative_kinetic_energy_change=float(np.max(abs(energy[np.isfinite(energy)])))) - if not failed: - result["loss_fraction"] = estimate_interval(lost, weights, binary=True) - result["mean_abs_delta_s"] = estimate_interval(abs(final_s-s), weights) - if wave is not None: - mu = states[:, :, 4] - result["max_relative_mu_change"] = float(np.nanmax(np.where(np.isfinite(mu), abs(mu/mu[:, :1]-1), np.nan))) - results.append(result) - curves.append((curve, unresolved)) - energies.append(energy) - (args.output/"progress.json").write_text(json.dumps(dict(config, cases=results), indent=2)+"\n") - print(json.dumps(result), flush=True) - _plot(args.output, times, curves, energies, reference, results, args.particles, args.tmax) - summary = dict(config, cases=results, elapsed_seconds=time.perf_counter()-started, - elapsed_time_scope="current invocation", - resumed_cases=[case["name"] for case in saved_results], - full_paper_duration=bool(np.isclose(args.tmax, .001, rtol=0, atol=1e-12)), - all_orbits_resolved=all(case["failed"] == 0 for case in results), - limitations=["Low-resolution input equilibrium; exact paper input unconfirmed; paper uses 5000 markers", - "Sampling intervals exclude equilibrium, interpolation and model errors", - "Uniform-volume importance weights from full Boozer Jacobian", - f"Native field representation: {args.representation}", - "Historical SIMSOPT convention is explicit; paper runtime is unconfirmed", - "The full equilibrium has no exact QS wave-frame invariant"]) - summary["numerical_checks_passed"] = bool(summary["all_orbits_resolved"] - and results[0]["max_relative_kinetic_energy_change"] < 1e-3 - and results[1]["max_relative_mu_change"] < 1e-12) - (args.output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - _report(args.output, summary) - print(f"Saved comparison to {args.output}; elapsed {summary['elapsed_seconds']:.1f} s", flush=True) - finally: - deadline.cancel() - - -def energy_changes(trace, batch_size): - """Use the existing energy diagnostic in batches, without changing the trace.""" - import copy - import numpy as np - if batch_size < 1: - raise ValueError("batch_size must be positive") - view = copy.copy(trace) - energies = [] - for start in range(0, len(trace.trajectories), batch_size): - view.trajectories = trace.trajectories[start:start+batch_size] - energies.append(np.asarray(view.energy())/float(trace.particles.energy)-1) - return np.concatenate(energies) - - -def report_saved(output): - """Regenerate plots and the report using saved data; no JAX import or tracing.""" - import numpy as np - summary = json.loads((output/"summary.json").read_text()) - curves, energies = [], [] - for index in range(len(summary["cases"])): - with np.load(output/f"case_{index}.npz") as saved: - times = saved["times"] - curves.append((saved["loss_curve"], saved["unresolved_curve"])) - energies.append(saved["energy_change"]) - summary["elapsed_time_scope"] = "current invocation" - cases = summary["cases"] - summary["numerical_checks_passed"] = bool(summary["all_orbits_resolved"] - and cases[0]["max_relative_kinetic_energy_change"] < 1e-3 - and cases[1]["max_relative_mu_change"] < 1e-12) - (output/"summary.json").write_text(json.dumps(summary, indent=2)+"\n") - _plot(output, times, curves, energies, summary["reference"], cases, - summary["particles_per_case"], summary["tmax_s"]) - _report(output, summary) - - -def _report(output, summary): - lines = ["# Full VMEC / mapped Paul wave", "", - f"Reference: [Paul et al., QA vac / Equil.]({summary['reference']['source']}).", "", - f"{summary['particles_per_case']} markers per case; {summary['tmax_s']*1e3:g} ms; " - f"{summary['elapsed_seconds']:.1f} seconds in the completing invocation.", ""] - if summary.get("resumed_cases"): - lines.extend(["Restored completed cases: "+", ".join(summary["resumed_cases"])+". " - "The elapsed time excludes the earlier invocation.", ""]) - lines.extend([ - "| Case | Confirmed loss | Unresolved weight | LCFS exits | Inner stops | Paper at 1 ms |", - "| --- | ---: | ---: | ---: | ---: | ---: |"]) - for case, reference in zip(summary["cases"], summary["reference"]["cases"]): - lines.append(f"| {case['name']} | {case['weighted_confirmed_loss']:.4f} | " - f"{case['weighted_unresolved']:.4f} | {case['lcfs_exits']} | " - f"{case['axis_stops']} | {reference['loss_fraction']:.3f} |") - for case in summary["cases"]: - if "loss_fraction" in case: - lo, hi = case["loss_fraction"]["interval_95"] - lines.append("") - lines.append(f"{case['name']}: approximate 95% sampling interval [{lo:.4f}, {hi:.4f}].") - lines.extend(["", f"Full paper duration: {summary['full_paper_duration']}. " - f"Numerical checks passed: {summary['numerical_checks_passed']}.", "", - "The full VMEC equilibrium retains QS-breaking modes; the older Boozer comparison " - "uses the separate Perfect QS reference. This small run does not establish " - "a converged reproduction.", ""]) - lines.extend(f"- {item}" for item in summary["limitations"]) - (output/"comparison.md").write_text("\n".join(lines)+"\n") - - -def _plot(output, times, curves, energies, reference, results, particles, tmax): - import numpy as np - import matplotlib - matplotlib.use("Agg") - import matplotlib.pyplot as plt - fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) - for i, (case, result, (curve, unresolved), energy) in enumerate(zip(reference["cases"], results, curves, energies)): - axes[0].plot(times*1e3, 100*curve, color=f"C{i}", label=f"VMEC {case['name']}") - if np.max(unresolved) > 0: - axes[0].fill_between(times*1e3, 100*curve, 100*(curve+unresolved), color=f"C{i}", alpha=.2) - axes[0].plot(1., 100*case["loss_fraction"], "x", color=f"C{i}", markersize=9, - label=f"Paul Equil. {case['name']}") - if "loss_fraction" in result: - lo, hi = np.array(result["loss_fraction"]["interval_95"])*100 - value = result["weighted_confirmed_loss"]*100 - axes[0].errorbar(tmax*1e3, value, yerr=[[value-lo], [hi-value]], fmt=".", color=f"C{i}") - axes[1].plot(times*1e3, np.nanmax(np.where(np.isfinite(energy), abs(energy), np.nan), axis=0), - color=f"C{i}", label=case["name"]) - axes[0].set(xlabel="Time [ms]", ylabel="Weighted loss fraction [%]", title="LCFS exits + wave inner stops") - axes[1].set(xlabel="Time [ms]", ylabel="Max active-marker |kinetic energy change| / birth energy", - title="Equilibrium conservation; wave energy exchange") - for ax in axes: - ax.grid(alpha=.2) - ax.legend(fontsize=8) - fig.suptitle(f"Mapped Paul wave, full VMEC geometry: {particles} markers per case") - for extension in ("png", "svg"): - fig.savefig(output/f"vmec_paul_comparison.{extension}", dpi=160) - plt.close(fig) - - -if __name__ == "__main__": - main() diff --git a/pyproject.toml b/pyproject.toml index 551f258b..24aa83e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,6 @@ dependencies = [ "f90nml", # Used internally by SurfaceRZFourier.to_vtk() and Coils.to_vtk(). "pyevtk", - "tomli; python_version < '3.11'", ] # pyQSC_JAX is not on PyPI, and PyPI rejects any distribution that names a diff --git a/tests/test_benchmark_batch_diagnostics.py b/tests/test_benchmark_batch_diagnostics.py deleted file mode 100644 index 5f98c5c1..00000000 --- a/tests/test_benchmark_batch_diagnostics.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Batching must preserve existing diagnostic values and the original trace.""" - -import json -import sys -from types import SimpleNamespace - -import jax.numpy as jnp -import numpy as np - -from essos.constants import ALPHA_PARTICLE_MASS, FUSION_ALPHA_PARTICLE_ENERGY -from essos.dynamics import Tracing -from essos.perturbations import AnalyticalAlfvenMode -from examples.benchmarks.alfven_gc_verification import equilibrium -from examples.benchmarks import paul_boozer_vmec_benchmark -from examples.particle_tracing.analytical_alfven_transport import invariant_errors -from examples.particle_tracing.vmec_alfven_paper_benchmark import energy_changes - - -def snapshots(): - speed = np.sqrt(2*FUSION_ALPHA_PARTICLE_ENERGY/ALPHA_PARTICLE_MASS) - y = np.zeros((5, 7, 5)) - y[:, :, 0] = np.linspace(.3, .6, 5)[:, None]+np.linspace(0, .01, 7) - y[:, :, 1] = np.linspace(.1, .7, 7) - y[:, :, 2] = np.linspace(.2, .8, 7) - y[:, :, 3] = .6*speed+np.linspace(0, 1000, 7) - y[:, :, 4] = speed - return y - - -def test_invariant_batches_preserve_drift_including_partial_final_batch(): - field = equilibrium() - mode = AnalyticalAlfvenMode(3, 2, 9e5, 2e4) - result = SimpleNamespace(states=snapshots(), times=np.linspace(0, 1e-6, 7)) - expected = invariant_errors(field, mode, result, 0) - actual = invariant_errors(field, mode, result, 0, batch_size=2) - np.testing.assert_allclose(actual, expected, rtol=1e-11, atol=1e-13) - - -def test_energy_batches_use_existing_energy_method_without_mutating_trace(): - class Field: - def AbsB(self, x): - return 5.+.2*x[0] - - trace = Tracing.__new__(Tracing) - trace.field = Field() - trace.model = "GuidingCenterAdaptative" - trace.particles = SimpleNamespace(mass=ALPHA_PARTICLE_MASS, energy=FUSION_ALPHA_PARTICLE_ENERGY) - trace.trajectories = jnp.asarray(snapshots()) - original = trace.trajectories - expected = np.asarray(trace.energy())/FUSION_ALPHA_PARTICLE_ENERGY-1 - np.testing.assert_allclose(energy_changes(trace, 2), expected, rtol=1e-11, atol=1e-13) - assert trace.trajectories is original - - -def test_default_job_prepares_500_per_case_without_starting_a_subprocess(tmp_path, monkeypatch): - def forbidden(*args, **kwargs): - raise AssertionError("dry-run must not launch a simulation") - - monkeypatch.setattr(paul_boozer_vmec_benchmark.subprocess, "run", forbidden) - monkeypatch.setattr(sys, "argv", ["benchmark", "--dry-run", "--output", str(tmp_path)]) - paul_boozer_vmec_benchmark.main() - job = json.loads((tmp_path/"job.json").read_text()) - assert job["particles_per_case"] == 500 - assert job["total_trajectories"] == 2000 - assert job["total_wall_limit_seconds"] == 600. - assert job["status"] == "prepared" - assert all(step[step.index("--particles")+1] == "500" for step in job["commands"]) - assert job["source_convention"] == "essos" - assert job["vmec_representation"] == "raw" - assert job["essos_omega_rad_s"] == 399000. - assert job["vmec_tolerance"] == 1e-8 - assert job["boozer_mode_tolerance"] == 1e-6 - for step in job["commands"][:2]: - assert step[step.index("--source-convention")+1] == "essos" - native = job["commands"][1] - assert native[native.index("--representation")+1] == "raw" - assert native[native.index("--births")+1] == str(tmp_path/"boozer/trajectories.npz") - - -def test_historical_convention_requires_an_explicit_option(tmp_path, monkeypatch): - def forbidden(*args, **kwargs): - raise AssertionError("dry-run must not launch a simulation") - - monkeypatch.setattr(paul_boozer_vmec_benchmark.subprocess, "run", forbidden) - monkeypatch.setattr(sys, "argv", ["benchmark", "--dry-run", "--output", str(tmp_path), - "--source-convention", "simsopt_2023"]) - paul_boozer_vmec_benchmark.main() - job = json.loads((tmp_path/"job.json").read_text()) - assert job["source_convention"] == "simsopt_2023" - assert job["essos_omega_rad_s"] == -399000. - assert job["vmec_representation"] == "raw" - for step in job["commands"][:2]: - assert step[step.index("--source-convention")+1] == "simsopt_2023" - native = job["commands"][1] - assert native[native.index("--representation")+1] == "raw" diff --git a/tests/test_gc_electromagnetic_verification.py b/tests/test_gc_electromagnetic_verification.py deleted file mode 100644 index 1b60d84f..00000000 --- a/tests/test_gc_electromagnetic_verification.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Independent conservation laws and an exact inductive trajectory.""" - -import jax -import jax.numpy as jnp -import numpy as np -import pytest - -from examples.benchmarks.alfven_gc_verification import ( - MASS, CHARGE, SPEED, PHASES, UniformInduction, differential_checks, - equilibrium, phase_space_density, spectrum, trace_induction, trace_wave, -) -from essos.boozer import guiding_center_rhs - - -@pytest.mark.parametrize("phase", PHASES) -def test_two_harmonic_wave_preserves_energy_momentum_and_phase_space(phase): - field, wave = equilibrium(), spectrum(phase) - points = jnp.array([[.45, .27, -.3, .7*SPEED], [.3, -.4, .7, -.65*SPEED]]) - times = jnp.array([1.3e-6, 4.7e-6]) - checks = np.asarray(jax.vmap(lambda y, t: differential_checks( - field, wave, y, .5*SPEED**2/(2*5.), t))(points, times)) - assert np.max(abs(checks[:, 0])) < 1e-12 - assert np.max(abs(checks[:, 1])) < 1e-12 - # These laws must detect an omitted inductive force, not merely return zero. - assert np.max(abs(checks[:, 2])) > 1e-6 - assert np.max(abs(checks[:, 3])) > 1e-10 - - -def test_volume_density_has_a_nonzero_time_derivative(): - field, wave = equilibrium(), spectrum(np.pi/2) - y = jnp.array([.45, .27, -.3, .7*SPEED]) - source = jax.grad(lambda t: phase_space_density(field, wave, y, t))(1.3e-6) - assert abs(float(source)) > 1e-3 - # In u,w the volume density has no polar radial factor: it stays nonzero - # as the axis is approached in the smooth, m>=3 perturbation fixture. - densities = [float(phase_space_density(field, wave, y.at[:2].set(jnp.array([r, 0.])), 0.)) - for r in (.01, .001)] - assert min(densities) > 1. - assert float(densities[0]) == pytest.approx(float(densities[1]), rel=.01) - - -def test_uniform_inductive_force_has_the_exact_sign_and_normalization(): - field, wave = equilibrium(uniform=True), UniformInduction() - y = jnp.array([.45, .27, -.3, .7*SPEED]) - t = 1.3e-6 - dy = guiding_center_rhs(field, y, 1e12, MASS, CHARGE, t=t, perturbation=wave) - expected = -CHARGE*5./MASS*wave.amplitude*wave.omega*np.cos(wave.omega*t+wave.phase) - np.testing.assert_allclose(dy[:2], 0., atol=1e-12) - assert float(dy[2]) == pytest.approx(float(5./40.*y[3]), rel=1e-13) - assert float(dy[3]) == pytest.approx(float(expected), rel=1e-13) - - -def test_adaptive_inductive_trajectory_matches_exact_velocity_and_position(): - trace, exact_v, exact_zeta = trace_induction(1e-10, tmax=1.5e-5, n_save=17) - assert np.max(abs(trace.states[0, :, 3]-exact_v))/SPEED < 1e-8 - assert np.max(abs(trace.states[0, :, 2]-exact_zeta)) < 1e-7 - np.testing.assert_allclose(trace.states[0, :, 0], .3, atol=1e-13) - np.testing.assert_allclose(trace.states[0, :, 1], .2, atol=1e-13) - - -def test_adaptive_two_harmonic_trajectory_exchanges_energy_at_fixed_wave_invariant(): - _, H, _, residual = trace_wave(equilibrium(), spectrum(np.pi/2), 1e-10, - tmax=1.5e-5, n_save=17) - assert np.max(abs(residual)) < 1e-8 - assert np.max(abs((H-H[:, :1])/H[:, :1])) > 1e-5 diff --git a/tests/test_native_gc_perturbations.py b/tests/test_native_gc_perturbations.py index 1f318c59..43b78454 100644 --- a/tests/test_native_gc_perturbations.py +++ b/tests/test_native_gc_perturbations.py @@ -1,4 +1,4 @@ -"""Full-geometry MHD corrections, including nonorthogonal radial components.""" +"""Full-geometry GC corrections (nonorthogonal radial components) and the VMEC -> Boozer wave map.""" from pathlib import Path from functools import partial @@ -8,13 +8,16 @@ import numpy as np import pytest +from essos.boozer import BoozerField, psi0_from_vmec from essos.constants import ALPHA_PARTICLE_MASS as MASS, ALPHA_PARTICLE_CHARGE as CHARGE, ONE_EV from essos.dynamics import (GuidingCenterMu, Particles, Tracing, _axis_regular, _guiding_center_velocity, _to_axis_regular) from essos.electric_field import Electric_field_zero from essos.fields import Vmec from essos.gc_perturbations import (AnalyticalVmecAlfvenMode, GuidingCenterPerturbation, - MappedBoozerPerturbation) + MappedBoozerPerturbation, VmecBoozerMap) +from essos.perturbations import AnalyticalAlfvenMode +from tests.test_perturbations import equilibrium, spectrum SPEED = np.sqrt(2*3.5e6*ONE_EV/MASS) @@ -160,21 +163,21 @@ def test_vmec_ideal_wave_and_radial_covariant_field_are_retained(): (field, particles, Electric_field_zero()))).all() -def test_boozer_adapter_includes_coordinate_map_derivatives(): - from examples.benchmarks.alfven_gc_verification import equilibrium, spectrum - background, wave = equilibrium(), spectrum(np.pi/2) - mapping = lambda x: jnp.array([x[0], x[1]+.2*jnp.sin(x[2]), x[2]+.1*x[0]*jnp.sin(x[1])]) - adapter = MappedBoozerPerturbation(background, wave, mapping) - x, t = jnp.array([.35, .7, .3]), 1.3e-6 - _, derivative = adapter.derivatives(None, x, t) - z, steps = np.append(x, t), [1e-6, 1e-6, 1e-6, 1e-11] - columns = [] - for i, step in enumerate(steps): - dz = np.eye(4)[i]*step - plus, minus = z+dz, z-dz +def assert_chain_rule(adapter, x, t, rtol, atol): + """Autodiff Jacobian of (alpha, Phi) through a coordinate map against central differences.""" + _, derivative = jax.jit(lambda x, t: adapter.derivatives(None, x, t))(x, t) + z, columns = np.append(x, t), [] + for i, step in enumerate([1e-6, 1e-6, 1e-6, 1e-11]): + plus, minus = z+np.eye(4)[i]*step, z-np.eye(4)[i]*step columns.append((adapter.potentials(None, plus[:3], plus[3]) -adapter.potentials(None, minus[:3], minus[3]))/(2*step)) - np.testing.assert_allclose(derivative, np.stack(columns, axis=1), rtol=1e-6, atol=1e-7) + np.testing.assert_allclose(derivative, np.stack(columns, axis=1), rtol=rtol, atol=atol) + + +def test_boozer_adapter_includes_coordinate_map_derivatives(): + mapping = lambda x: jnp.array([x[0], x[1]+.2*jnp.sin(x[2]), x[2]+.1*x[0]*jnp.sin(x[1])]) + adapter = MappedBoozerPerturbation(equilibrium(), spectrum(np.pi/2), mapping) + assert_chain_rule(adapter, jnp.array([.35, .7, .3]), 1.3e-6, 1e-6, 1e-7) def test_adaptive_trace_uses_constant_mu_while_inductive_field_changes_energy(): @@ -220,3 +223,62 @@ def test_unsupported_models_and_fixed_energy_shortcut_are_rejected(): Tracing(model="GuidingCenterCollisions", perturbation=Wave()) with pytest.raises(ValueError, match="exterior wave model"): Tracing(model="GuidingCenterAdaptative", perturbation=Wave(), exterior_field=ShearedField()) + + +@pytest.fixture(scope="module") +def transformed(): + Booz_xform = pytest.importorskip("booz_xform_jax").Booz_xform + from netCDF4 import Dataset + booz = Booz_xform(verbose=0, mboz=16, nboz=16) + booz.read_wout(str(WOUT), flux=False) + booz.run() + with Dataset(WOUT) as nc: + psi = psi0_from_vmec(nc.variables["phi"][-1]) + return booz, VmecBoozerMap.from_booz_xform(booz), BoozerField.from_booz_xform(booz, psi, angle_grid=None) + + +def test_vmec_boozer_map_agrees_with_booz_xform_and_chain_rule(transformed): + booz, mapping, background = transformed + j = len(booz.s_b)//2 + point = jnp.array([booz.s_b[j], .7, .3]) + mapped = mapping(point) + nu = np.sin(float(mapped[1])*np.asarray(booz.xm_b) + -float(mapped[2])*np.asarray(booz.xn_b))@np.asarray(booz.numns_b)[:, j] + assert float(mapped[2]-point[2]) == pytest.approx(nu, abs=2e-6) + np.testing.assert_allclose(mapping.inverse(mapped), point, atol=2e-13) + wave = AnalyticalAlfvenMode(15, 7, 399000., 1e4, regularize_axis=False) + adapter = MappedBoozerPerturbation(background, wave, mapping) + assert adapter.axis_stop_threshold() == 1e-8 + assert_chain_rule(adapter, point, 1e-6, 2e-6, 1e-6) + + +def test_wave_inner_cutoff_is_separate_from_lcfs_loss_and_failure(transformed): + _, mapping, background = transformed + field = Vmec(str(WOUT), ntheta=8, nphi=8, mode_tolerance=.01) + # An enlarged cutoff exercises both t=0 stopping and a root-found crossing cheaply. + wave = AnalyticalAlfvenMode(3, 2, 9e5, 1e3, regularize_axis=False, axis_stop_s=.36) + adapter = MappedBoozerPerturbation(background, wave, mapping) + particles = Particles(initial_xyz=jnp.array([[.35, .7, .3]]), initial_vparallel_over_v=jnp.array([.65])) + speed = particles.total_speed + angles = jnp.linspace(0., 2*jnp.pi, 9)[:-1] + + def radial_speed(theta): + point = jnp.array([.36, theta, .3]) + mu = particles.mass*speed**2*(1-.65**2)/(2*field.AbsB(point)) + state = jnp.concatenate([point, jnp.array([.65*speed, mu])]) + return GuidingCenterMu(0., state, (field, particles, Electric_field_zero()), perturbation=adapter)[0] + + speeds = jax.jit(jax.vmap(radial_speed))(angles) + inward = int(jnp.argmin(speeds)) + assert speeds[inward] < 0 + moving = jnp.array([.36-float(speeds[inward])*5e-9, angles[inward], .3]) + particles = Particles(initial_xyz=jnp.vstack([particles.initial_xyz, moving]), + initial_vparallel_over_v=jnp.array([.65, .65])) + trace = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", perturbation=adapter, + maxtime=2e-8, timestep=1e-9, times_to_trace=3, max_steps=32, progress=False, + devices=jax.devices()[:1]) + assert trace.status[0] == 6 and trace.axis_stopped[0] and trace.axis_stop_times[0] == 0. + assert trace.status[1] == 6 and 0 < trace.axis_stop_times[1] < 2e-8 + assert trace.axis_stop_states[1, 0] == pytest.approx(.36, abs=1e-9) + assert not trace.failed.any() and not trace.boundary_hits.any() + np.testing.assert_allclose(trace.axis_stop_states[0, :3], particles.initial_xyz[0]) diff --git a/tests/test_paul_benchmark_births.py b/tests/test_paul_benchmark_births.py deleted file mode 100644 index 7ecfbfee..00000000 --- a/tests/test_paul_benchmark_births.py +++ /dev/null @@ -1,113 +0,0 @@ -"""A shared marker cohort must retain the tested birth/wave convention map.""" - -import json - -import numpy as np -import pytest - -from examples.benchmarks.paul_conventions import convert_births, load_essos_births, particle_parameters -from examples.benchmarks.paul_boozer_vmec_loss_comparison import compare -from examples.benchmarks.paul_boozer_vmec_benchmark import commands - - -def test_shared_archive_retains_converted_angles_and_pitch_without_second_reflection(tmp_path): - source = ([.3, .4, .5], [.1, .2, .3], [.4, .5, .6], [.7, -.2, -.8]) - expected = convert_births(*source, source="simsopt_2023") - path = tmp_path/"births.npz" - np.savez(path, **dict(zip((f"birth_{k}" for k in ("s", "theta", "zeta", "pitch")), expected)), - metadata_json=json.dumps(dict(source_convention="simsopt_2023", - birth_coordinate_convention="essos"))) - actual = load_essos_births(path, 3, source="simsopt_2023") - for a, b in zip(actual, expected): - np.testing.assert_array_equal(a, b) - np.testing.assert_array_equal(actual[-1], -np.array(source[-1])) - with pytest.raises(ValueError, match="source convention"): - load_essos_births(path, 3, source="essos") - - -def test_legacy_essos_archive_cannot_be_combined_with_historical_source_wave(tmp_path): - path = tmp_path/"old.npz" - np.savez(path, **{f"birth_{k}": np.ones(3) for k in ("s", "theta", "zeta", "pitch")}) - with pytest.raises(ValueError, match="source convention"): - load_essos_births(path, 3, source="simsopt_2023") - assert len(load_essos_births(path, 3, source="essos")[0]) == 3 - with pytest.raises(ValueError, match="fewer markers"): - load_essos_births(path, 4, source="essos") - - - - -def test_shared_marker_pool_is_forwarded_to_boozer_and_its_converted_births_to_vmec(tmp_path): - pool = tmp_path/"pool.npz" - steps = commands("python", 100, "cpu", 120, tmp_path/"output", 8, 8, births=pool) - assert steps[0][steps[0].index("--births")+1] == str(pool) - assert steps[1][steps[1].index("--births")+1] == str(tmp_path/"output/boozer/trajectories.npz") - - -def test_equilibrium_override_reaches_both_formulations_with_original_wave_defaults(tmp_path): - wout = tmp_path/"reference_wout.nc" - steps = commands("python", 100, "cpu", 120, tmp_path/"output", 8, 8, wout=wout) - for step in steps[:2]: - assert step[step.index("--wout")+1] == str(wout) - assert step[step.index("--source-convention")+1] == "essos" - - -def test_explicit_historical_mass_retains_fixed_birth_energy_and_reaches_both_formulations(tmp_path): - energy, measured_mass = 3.52e6*1.602176634e-19, 6.644657345e-27 - original = particle_parameters("essos", measured_mass=measured_mass, energy_joule=energy) - historical = particle_parameters("simsopt_2023", measured_mass=measured_mass, energy_joule=energy) - assert original["mass_kg"] == measured_mass - assert historical["mass_kg"] == 6.69509884346e-27 - assert historical["birth_speed_m_s"] < original["birth_speed_m_s"] - for particle in (original, historical): - assert .5*particle["mass_kg"]*particle["birth_speed_m_s"]**2 == pytest.approx(energy, rel=2e-15) - steps = commands("python", 100, "cpu", 600, tmp_path, 8, 8, particle_model="simsopt_2023") - for step in steps[:2]: - assert step[step.index("--particle-model")+1] == "simsopt_2023" - - -@pytest.mark.parametrize("key,other", [("mass_kg", 6.644657345e-27), ("energy_joule", 4e-13)]) -def test_loss_comparison_rejects_different_particle_masses_or_energies(tmp_path, key, other): - boozer, vmec = tmp_path/"boozer", tmp_path/"vmec" - boozer.mkdir() - vmec.mkdir() - common = dict(particles_per_case=3, numerical_checks_passed=True, all_orbits_resolved=True, - mass_kg=6.69509884346e-27, energy_joule=3.52e6*1.602176634e-19) - b, v = dict(common), dict(common) - v[key] = other - (boozer/"summary.json").write_text(json.dumps(b)) - (vmec/"summary.json").write_text(json.dumps(v)) - with pytest.raises(ValueError, match=f"Different particle parameter {key}"): - compare(boozer, vmec, tmp_path/"comparison", particles=3) - - -def test_loss_comparison_rejects_different_equilibria_with_the_same_filename(tmp_path): - boozer, vmec = tmp_path/"boozer", tmp_path/"vmec" - boozer.mkdir() - vmec.mkdir() - common = dict(particles_per_case=3, numerical_checks_passed=True, all_orbits_resolved=True) - b = dict(common, provenance=dict(wout="first/wout.nc", wout_sha256="1"*64)) - v = dict(common, wout="second/wout.nc", wout_sha256="2"*64) - (boozer/"summary.json").write_text(json.dumps(b)) - (vmec/"summary.json").write_text(json.dumps(v)) - with pytest.raises(ValueError, match="hashes differ"): - compare(boozer, vmec, tmp_path/"comparison", particles=3) - - -@pytest.mark.parametrize("mismatch", ["source_convention", "essos_omega_rad_s", "potential_volts"]) -def test_loss_comparison_rejects_different_physical_wave_configurations(tmp_path, mismatch): - boozer, vmec = tmp_path/"boozer", tmp_path/"vmec" - boozer.mkdir() - vmec.mkdir() - wave = dict(essos_omega_rad_s=-399000., potential_volts=-3734.) - common = dict(particles_per_case=3, numerical_checks_passed=True, source_convention="simsopt_2023") - b = dict(common, results=[wave.copy(), wave.copy()]) - v = dict(common, all_orbits_resolved=True, cases=[wave.copy(), wave.copy()]) - if mismatch == "source_convention": - v[mismatch] = "essos" - else: - v["cases"][1][mismatch] *= -1 - (boozer/"summary.json").write_text(json.dumps(b)) - (vmec/"summary.json").write_text(json.dumps(v)) - with pytest.raises((ValueError, AssertionError), match="different source conventions|Different actual ESSOS"): - compare(boozer, vmec, tmp_path/"comparison", particles=3) diff --git a/tests/test_perturbation_axis_stop.py b/tests/test_perturbation_axis_stop.py deleted file mode 100644 index 5af5e1b8..00000000 --- a/tests/test_perturbation_axis_stop.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Small deterministic checks of singular-mode stopping and outcome accounting.""" - -import jax -import jax.numpy as jnp -import numpy as np -import pytest - -from essos.boozer import BoozerField, _axis_intersection, trace_boozer -from essos.constants import ALPHA_PARTICLE_MASS as MASS, ALPHA_PARTICLE_CHARGE as CHARGE, ONE_EV -from essos.perturbations import AnalyticalAlfvenMode, AlfvenSpectrum - - -SPEED = np.sqrt(2*3.52e6*ONE_EV/MASS) - - -def field(): - s = np.linspace(.005, .995, 16) - return BoozerField.from_booz(s, np.stack([5.+0*s, -np.sqrt(s)]), [0, 1], [0, 0], - .4+0*s, 40.+0*s, 0*s, -40., 1, angle_grid=None) - - -def mode(**kwargs): - return AnalyticalAlfvenMode(1, 2, 9e5, kwargs.pop("amplitude", 2000.), - regularize_axis=kwargs.pop("regularize_axis", False), **kwargs) - - -def test_only_nonzero_singular_angular_modes_request_axis_stops(): - assert float(mode().axis_stop_threshold()) == 1e-8 - assert float(mode(amplitude=0.).axis_stop_threshold()) == 0. - assert mode(regularize_axis=True).axis_stop_threshold() is None - assert mode(axis_stop_s=None).axis_stop_threshold() is None - assert AnalyticalAlfvenMode(0, 2, 9e5, 2000., regularize_axis=False).axis_stop_threshold() is None - assert float(AlfvenSpectrum(mode(), mode(axis_stop_s=1e-7)).axis_stop_threshold()) == 1e-7 - - -@pytest.mark.parametrize("threshold", [0., -1e-8, 1., np.nan]) -def test_invalid_axis_cutoffs_are_rejected(threshold): - with pytest.raises(ValueError, match="axis_stop_s"): - mode(axis_stop_s=threshold) - - -def test_axis_segment_intersection_detects_entry_and_pass_through(): - hit, fraction = _axis_intersection(jnp.array([-.2, 0., 0., 1.]), - jnp.array([.2, 0., 0., 1.]), .01) - assert bool(hit) - assert float(fraction) == pytest.approx(.25) - # Tangentially displaced chord misses the disk; a disabled cutoff never hits. - assert not bool(_axis_intersection(jnp.array([-.2, .2]), jnp.array([.2, .2]), .01)[0]) - assert not bool(_axis_intersection(jnp.array([-.2, 0.]), jnp.array([.2, 0.]), 0.)[0]) - assert not bool(_axis_intersection(jnp.array([.2, 0.]), jnp.array([jnp.nan, 0.]), .01)[0]) - - -@pytest.mark.parametrize("compact", [False, True]) -def test_births_inside_axis_boundary_stop_cleanly_and_survive_compaction(compact): - out = trace_boozer(field(), [0., 5e-9, .3], [0., 0., .2], [0., 0., 0.], [1., 1., 1.], - speed=SPEED, mass=MASS, charge=CHARGE, tmax=1e-10, timestep=1e-11, - n_save=4, method="rk4", perturbation=mode(), compact=compact, - progress=False, devices=jax.devices()[:1]) - np.testing.assert_array_equal(out.axis_stopped, [True, True, False]) - np.testing.assert_allclose(out.axis_stop_times[:2], 0.) - assert not out.failed.any() and not out.lost.any() - assert np.isfinite(out.states).all() - np.testing.assert_allclose(out.states[:2], np.broadcast_to(out.states[:2, :1], out.states[:2].shape)) - np.testing.assert_allclose(out.loss_fractions(), 0.) - np.testing.assert_allclose(out.loss_fractions(include_axis=True), 2/3) - - -@pytest.mark.parametrize("method", ["rk4", "adaptive8"]) -def test_incoming_orbit_stops_at_configured_boundary_with_finite_frozen_state(method): - cutoff = 1e-8 - out = trace_boozer(field(), [4*cutoff], [np.pi], [0.], [0.], - speed=SPEED, mass=MASS, charge=CHARGE, tmax=2e-9, timestep=2e-11, - n_save=6, method=method, tolerance=1e-10, - perturbation=mode(axis_stop_s=cutoff), compact=False, - progress=False, devices=jax.devices()[:1]) - assert out.axis_stopped[0] and not out.lost[0] and not out.failed[0] - assert 0 < out.axis_stop_times[0] < out.times[-1] - assert np.isfinite(out.states).all() - assert out.states[0, -1, 0] == pytest.approx(cutoff, rel=1e-10) - frozen = out.states[0, out.times >= out.axis_stop_times[0]] - np.testing.assert_allclose(frozen, np.broadcast_to(frozen[0], frozen.shape)) - assert out.loss_fractions()[-1] == 0. - assert out.loss_fractions(include_axis=True)[-1] == 1. - - -def test_zero_amplitude_uniform_mode_does_not_stop_or_fail_on_axis(): - out = trace_boozer(field(), [0., 1e-10], [0., .3], [0., 0.], [1., 1.], - speed=SPEED, mass=MASS, charge=CHARGE, tmax=1e-10, timestep=1e-11, - n_save=3, method="rk4", perturbation=mode(amplitude=0.), - compact=False, progress=False, devices=jax.devices()[:1]) - assert not out.axis_stopped.any() and not out.failed.any() - assert np.isfinite(out.states).all() diff --git a/tests/test_perturbations.py b/tests/test_perturbations.py index 4cc4ed85..cc12c2a7 100644 --- a/tests/test_perturbations.py +++ b/tests/test_perturbations.py @@ -1,4 +1,4 @@ -"""Ideal electric fields, GC invariants and nonautonomous stepping checks.""" +"""Boozer-coordinate shear-Alfven perturbations: E_parallel = 0, exact conservation laws, time stepping.""" import equinox as eqx import jax @@ -6,27 +6,122 @@ import numpy as np import pytest -from essos.boozer import BoozerField, _embedded_step, _rk_step, guiding_center_rhs, trace_boozer +from essos.boozer import (BoozerField, _axis_intersection, _embedded_step, _rk_step, + guiding_center_rhs, trace_boozer) from essos.constants import ALPHA_PARTICLE_MASS as MASS, ALPHA_PARTICLE_CHARGE as CHARGE, ONE_EV -from essos.perturbations import (AnalyticalAlfvenMode, poloidal_flux, - wave_frame_invariant) - +from essos.perturbations import (AlfvenSpectrum, AnalyticalAlfvenMode, BoozerPerturbation, + poloidal_flux, wave_frame_invariant) SPEED = np.sqrt(2*3.5e6*ONE_EV/MASS) +MU = .5*SPEED**2/(2*5.) +POINT = jnp.array([.45, .27, -.3, .7*SPEED]) +OMEGA, N = 9e5, 2 +KW = dict(speed=SPEED, mass=MASS, charge=CHARGE, progress=False, devices=jax.devices()[:1]) -def equilibrium(helicity=0): +def equilibrium(helicity=0, uniform=False): + """Analytic fixture with nonconstant iota, G and I (or uniform B0 with G=40, I=iota=0).""" s = np.linspace(.005, .995, 32) + if uniform: + return BoozerField.from_booz(s, np.array([5.+0*s]), [0], [0], 0*s, 40.+0*s, 0*s, -40., 1, angle_grid=None) return BoozerField.from_booz(s, np.stack([5.+0*s, -np.sqrt(s)]), [0, 1], [0, helicity], - .4+.1*s, 40.+.1*s, .2*s, -40., max(1, abs(helicity)), - angle_grid=None) + .4+.1*s, 40.+.8*s, .8*s, -40., max(1, abs(helicity)), angle_grid=None) def mode(**kwargs): - params = dict(m=3, n=2, omega=9.e5, amplitude=2.e4, phase=.3, - radial_center=.4, radial_width=.5) - params.update(kwargs) - return AnalyticalAlfvenMode(**params) + params = dict(m=3, n=N, omega=OMEGA, amplitude=2e4, phase=.3, radial_center=.4, radial_width=.5) + return AnalyticalAlfvenMode(**{**params, **kwargs}) + + +def singular(**kwargs): + return AnalyticalAlfvenMode(1, N, OMEGA, kwargs.pop("amplitude", 2000.), + regularize_axis=False, **kwargs) + + +def spectrum(relative_phase): + """Adjacent m, common n and omega: one toroidally rotating pattern.""" + return AlfvenSpectrum(mode(m=3, phase=.3), mode(m=4, phase=.3+relative_phase)) + + +class UniformInduction(BoozerPerturbation): + """Exact nonideal calibration: uniform alpha(t), Phi=0, constant B0.""" + + amplitude: float = .003 + omega: float = 7.5e5 + phase: float = .4 + + def potentials(self, field, xyz, t): + alpha = self.amplitude*jnp.sin(self.omega*t+self.phase) + return jnp.stack([alpha, jnp.zeros_like(alpha)]) + + def exact(self, times, v0, zeta0, *, B=5., G=40.): + k = CHARGE*B/MASS*self.amplitude + v = v0-k*(np.sin(self.omega*times+self.phase)-np.sin(self.phase)) + zeta = zeta0+B/G*((v0+k*np.sin(self.phase))*times + +k/self.omega*(np.cos(self.omega*times+self.phase)-np.cos(self.phase))) + return v, zeta + + +class ParallelWave(BoozerPerturbation): + """Phi = A sin(omega t - n zeta) in a uniform field: a pure parallel electric field, no alpha.""" + + amplitude: float = 5e2 + + def potentials(self, field, xyz, t): + return jnp.stack([0.*t, self.amplitude*jnp.sin(OMEGA*t-N*xyz[2])]) + + +def modB(field, y): + return field.modB(y[0]**2+y[1]**2, jnp.arctan2(y[1], y[0]), y[2]) + + +def chart(states): + """Saved (s, theta, zeta, v_par, v) states to the regular chart (u, w, zeta, v_par).""" + s, theta, zeta, vpar, _ = np.moveaxis(states, -1, 0) + return jnp.stack([np.sqrt(s)*np.cos(theta), np.sqrt(s)*np.sin(theta), zeta, vpar], -1) + + +def energy_momentum(field, wave, y, mu, t): + """GC energy H and canonical toroidal momentum P = G (M v/B + q alpha) - q psi_P.""" + B = modB(field, y) + (_, G, _), _ = field.profiles(y[0]**2+y[1]**2) + alpha, phi = wave.potentials(field, y[:3], t) + return jnp.stack([MASS*(.5*y[3]**2+mu*B)+CHARGE*phi, + G*(MASS*y[3]/B+CHARGE*alpha)-CHARGE*poloidal_flux(field, y[0]**2+y[1]**2)]) + + +def phase_space_density(field, wave, y, t): + """GC phase-space density in (u, w, zeta, v_par) up to the constant 2 M q psi0. + + From gamma_theta = q psi0 s + k I, gamma_zeta = -q psi_P + k G, k = M v/B + q alpha: + [G + iota I + (M v/(q B) + alpha)(G I' - I G')/psi0]/B. It is time dependent. + """ + s = y[0]**2+y[1]**2 + (iota, G, I), (_, Gs, Is) = field.profiles(s) + alpha = wave.potentials(field, y[:3], t)[0] + return (G+iota*I+(MASS*y[3]/(CHARGE*modB(field, y))+alpha)*(G*Is-I*Gs)/field.psi0)/modB(field, y) + + +def conservation_residuals(field, wave, y, t): + """Normalized rotating-frame invariant and Liouville residuals of the production RHS. + + The last two repeat both laws with the inductive acceleration removed; they must + not vanish, otherwise the laws could not detect a missing term. + """ + invariant = lambda y, t: energy_momentum(field, wave, y, MU, t)@jnp.array([1., -OMEGA/N]) + density = lambda y, t: phase_space_density(field, wave, y, t) + rhs = lambda y: guiding_center_rhs(field, y, MU, MASS, CHARGE, t=t, perturbation=wave) + gradient = jax.grad(invariant, 0)(y, t) + rate = gradient@rhs(y)+jax.grad(invariant, 1)(y, t) + source = jax.grad(density, 1)(y, t) + terms = jnp.diag(jax.jacfwd(lambda y: density(y, t)*rhs(y))(y)) + volume = source+jnp.sum(terms) + volume_scale = jnp.maximum(abs(source)+jnp.sum(abs(terms)), 1e-30) + energy_scale = abs(energy_momentum(field, wave, y, MU, t)[0])*OMEGA + removed = CHARGE*modB(field, y)/MASS*wave.derivatives(field, y[:3], t)[1][0, 3] + return jnp.array([rate/energy_scale, volume/volume_scale, + (rate+gradient[3]*removed)/energy_scale, + (volume+jax.grad(density, 0)(y, t)[3]*removed)/volume_scale]) def test_poloidal_flux_integrates_iota_with_the_vmec_flux_sign(): @@ -38,152 +133,234 @@ def test_poloidal_flux_integrates_iota_with_the_vmec_flux_sign(): @pytest.mark.parametrize("helicity", [0, 4]) def test_potentials_satisfy_ideal_parallel_electric_field(helicity): - field, wave = equilibrium(helicity), mode() - xyz, t = jnp.array([.45, .27, -.3]), 2.3e-6 - (_, phi), derivative = jax.jit(lambda x: wave.derivatives(field, x, t))(xyz) - (iota, G, I), _ = field.profiles(jnp.sum(xyz[:2]**2)) - phi_theta = -xyz[1]*derivative[1, 0]+xyz[0]*derivative[1, 1] - residual = derivative[0, 3]+(iota*phi_theta+derivative[1, 2])/(G+iota*I) + field, wave, t = equilibrium(helicity), mode(), 2.3e-6 + (_, phi), derivative = jax.jit(lambda x: wave.derivatives(field, x, t))(POINT[:3]) + (iota, G, I), _ = field.profiles(jnp.sum(POINT[:2]**2)) + phi_theta = -POINT[1]*derivative[1, 0]+POINT[0]*derivative[1, 1] + # B0 . (-d_t(alpha B0) - grad Phi) = 0 assert abs(float(phi)) > 1. - assert abs(float(residual)) < 1e-10 + assert abs(float(derivative[0, 3]+(iota*phi_theta+derivative[1, 2])/(G+iota*I))) < 1e-10 def test_zero_amplitude_recovers_existing_gc_equations(): - field, wave = equilibrium(), mode(amplitude=0.) - y, mu = jnp.array([.45, .27, -.3, .7*SPEED]), .5*SPEED**2/(2*5.) - actual = guiding_center_rhs(field, y, mu, MASS, CHARGE, t=1e-6, perturbation=wave) - np.testing.assert_allclose(actual, guiding_center_rhs(field, y, mu, MASS, CHARGE), rtol=2e-13) + field = equilibrium() + actual = guiding_center_rhs(field, POINT, MU, MASS, CHARGE, t=1e-6, perturbation=mode(amplitude=0.)) + np.testing.assert_allclose(actual, guiding_center_rhs(field, POINT, MU, MASS, CHARGE), rtol=2e-13) @pytest.mark.parametrize("helicity", [0, 4]) def test_single_mode_wave_frame_invariant_is_a_differential_identity(helicity): - field, wave = equilibrium(helicity), mode() - y, mu, t = jnp.array([.45, .27, -.3, .7*SPEED]), .5*SPEED**2/(2*5.), 2.3e-6 - invariant = lambda y, t: wave_frame_invariant(field, wave, y, mu, MASS, CHARGE, - t, helicity=helicity) - dy = guiding_center_rhs(field, y, mu, MASS, CHARGE, t=t, perturbation=wave) - rate = jax.grad(invariant, 0)(y, t)@dy+jax.grad(invariant, 1)(y, t) - scale = abs(float(invariant(y, t)))*abs(float(wave.omega)) - assert abs(float(rate))/scale < 1e-12 + field, wave, t = equilibrium(helicity), mode(), 2.3e-6 + invariant = lambda y, t: wave_frame_invariant(field, wave, y, MU, MASS, CHARGE, t, helicity=helicity) + dy = guiding_center_rhs(field, POINT, MU, MASS, CHARGE, t=t, perturbation=wave) + rate = jax.grad(invariant, 0)(POINT, t)@dy+jax.grad(invariant, 1)(POINT, t) + assert abs(float(rate))/(abs(float(invariant(POINT, t)))*OMEGA) < 1e-12 # Energy exchange is physical even while this combined invariant is conserved. - kinetic = lambda y: MASS*(.5*y[3]**2+mu*field.modB(y[0]**2+y[1]**2, - jnp.arctan2(y[1], y[0]), y[2])) - assert abs(float(jax.grad(kinetic)(y)@dy)) > 1e-12 - - -@pytest.mark.parametrize("m", [0, 1, 2, 3, 15, 30]) + kinetic = lambda y: MASS*(.5*y[3]**2+MU*modB(field, y)) + assert abs(float(jax.grad(kinetic)(POINT)@dy)) > 1e-12 + + +@pytest.mark.parametrize("phase", np.arange(4)*np.pi/2) +def test_two_harmonic_wave_preserves_energy_momentum_and_phase_space(phase): + field, wave = equilibrium(), spectrum(phase) + points = jnp.array([[.45, .27, -.3, .7*SPEED], [.3, -.4, .7, -.65*SPEED], + [-.5, .2, 1.2, .5*SPEED], [.2, .6, -.8, -.8*SPEED]]) + times = jnp.array([0., 1.3e-6, 4.7e-6, 9e-6]) + r = np.asarray(jax.jit(jax.vmap(lambda y, t: conservation_residuals(field, wave, y, t)))(points, times)) + assert np.max(abs(r[:, :2])) < 1e-12 + assert np.max(abs(r[:, 2])) > 1e-6 and np.max(abs(r[:, 3])) > 1e-10 + # The time-dependent density stays finite and positive towards the axis (u, w chart). + near = [float(phase_space_density(field, wave, POINT.at[:2].set(jnp.array([x, 0.])), 0.)) for x in (.01, .001)] + assert min(near) > 1. and near[0] == pytest.approx(near[1], rel=.01) + + +def test_uniform_induction_has_the_exact_sign_and_normalization(): + wave, t = UniformInduction(), 1.3e-6 + dy = guiding_center_rhs(equilibrium(uniform=True), POINT, 1e12, MASS, CHARGE, t=t, perturbation=wave) + expected = -CHARGE*5./MASS*wave.amplitude*wave.omega*np.cos(wave.omega*t+wave.phase) + np.testing.assert_allclose(dy[:2], 0., atol=1e-12) + assert float(dy[2]) == pytest.approx(float(5./40.*POINT[3]), rel=1e-13) + assert float(dy[3]) == pytest.approx(float(expected), rel=1e-13) + + +def test_landau_resonance_gains_energy_by_the_work_of_the_parallel_field(): + # Resonance omega - k_par v_par = 0 with k_par v_par = n zeta_dot = n B v_par / G (White, Theory of + # Toroidally Confined Plasmas); the wave Hamiltonian obeys d(KE + q Phi)/dt = q dPhi/dt at fixed position. + wave, field, v_res = ParallelWave(), equilibrium(uniform=True), OMEGA*40./(N*5.) + out = trace_boozer(field, [.3, .3], [.2, .2], [0., 0.], [v_res/SPEED, .5*v_res/SPEED], tmax=2e-5, + timestep=1e-8, n_save=801, method="rk4", perturbation=wave, compact=False, **KW) + t, zeta, vpar, speed = out.times, out.states[:, :, 2], out.states[:, :, 3], out.states[:, :, 4] + # mu = v_perp^2 / (2 B) is carried unchanged while kinetic energy changes. + np.testing.assert_allclose(speed**2-vpar**2, (speed**2-vpar**2)[:, :1]*np.ones(t.size), rtol=1e-11) + phase = OMEGA*t-N*zeta + work = CHARGE*np.trapezoid(wave.amplitude*OMEGA*np.cos(phase), t, axis=1) + potential = CHARGE*wave.amplitude*np.sin(phase) + gain = .5*MASS*(vpar[:, -1]**2-vpar[:, 0]**2)+potential[:, -1]-potential[:, 0] + np.testing.assert_allclose(gain, work, atol=1e-4*abs(work).max()) # trapezoid quadrature + # Stationary phase for the resonant marker gives secular gain; the detuned one only oscillates. + dv = abs(vpar[:, -1]-vpar[:, 0]) + assert dv[0] > 5e4 and dv[0] > 5*dv[1] + assert np.ptp(phase[0]) < .5 + + +@pytest.mark.parametrize("m", [0, 1, 3, 15, 30]) def test_regular_potential_and_gc_rhs_are_finite_on_axis(m): field, wave = equilibrium(), mode(m=m) y = jnp.array([0., 0., .2, .7*SPEED]) value, derivative = wave.derivatives(field, y[:3], 1e-6) assert np.isfinite(value).all() and np.isfinite(derivative).all() - assert np.isfinite(guiding_center_rhs(field, y, 1e12, MASS, CHARGE, - t=1e-6, perturbation=wave)).all() + assert np.isfinite(guiding_center_rhs(field, y, 1e12, MASS, CHARGE, t=1e-6, perturbation=wave)).all() @pytest.mark.parametrize("method", ["rk4", "dopri5", "dopri8", "adaptive", "adaptive8"]) def test_runge_kutta_uses_physical_stage_times(method): rhs = lambda t, y: jnp.full_like(y, t**3) t, dt, y = .7, .2, jnp.array([1.]) - expected = y+((t+dt)**4-t**4)/4 if method.startswith("adaptive"): actual, _ = _embedded_step(rhs, y, dt, jnp.ones_like(y), method, t=t) else: actual = _rk_step(rhs, y, dt, method, t=t) - np.testing.assert_allclose(actual, expected, rtol=1e-14) + np.testing.assert_allclose(actual, y+((t+dt)**4-t**4)/4, rtol=1e-14) @pytest.mark.parametrize("method", ["rk4", "dopri5", "dopri8", "adaptive", "adaptive8"]) def test_perturbed_trace_conserves_wave_invariant_and_reports_physical_work(method): field, wave = equilibrium(), mode() - out = trace_boozer(field, [.3, .35], [.2, .7], [0., .3], [.65, -.7], - speed=SPEED, mass=MASS, charge=CHARGE, tmax=8e-6, - timestep=2e-8, n_save=15, method=method, tolerance=1e-11, - perturbation=wave, progress=False, compact=False, devices=jax.devices()[:1]) - assert not out.failed.any() and not out.lost.any() - assert out.energy_error is None + out = trace_boozer(field, [.3, .35], [.2, .7], [0., .3], [.65, -.7], tmax=8e-6, timestep=2e-8, + n_save=15, method=method, tolerance=1e-11, perturbation=wave, compact=False, **KW) + assert not out.failed.any() and not out.lost.any() and out.energy_error is None assert np.max(out.kinetic_energy_change) > 1e-6 np.testing.assert_array_equal(out.loss_fractions(), 0.) - for trajectory in out.states: - s, th, ze, vp, speed = trajectory.T - y = jnp.stack([jnp.sqrt(s)*jnp.cos(th), jnp.sqrt(s)*jnp.sin(th), ze, vp], axis=1) - mu = SPEED**2*(1-(float(vp[0])/SPEED)**2)/(2*field.modB(s[0], th[0], ze[0])) - values = jax.vmap(lambda y, t: wave_frame_invariant(field, wave, y, mu, MASS, - CHARGE, t))(y, out.times) + for states in out.states: + y = chart(states) + mu = SPEED**2*(1-(float(y[0, 3])/SPEED)**2)/(2*float(modB(field, y[0]))) + values = jax.vmap(lambda y, t: wave_frame_invariant(field, wave, y, mu, MASS, CHARGE, t))(y, out.times) assert np.max(np.abs(values/values[0]-1)) < 2e-8 -def test_mode_amplitude_derivative_matches_finite_difference_through_gc_step(): +def test_adaptive_traces_match_exact_induction_and_two_harmonic_invariant(): + wave = UniformInduction() + out = trace_boozer(equilibrium(uniform=True), [.3], [.2], [.3], [.65], tmax=1.5e-5, timestep=2e-7, + n_save=17, method="adaptive8", tolerance=1e-10, perturbation=wave, compact=False, **KW) + v, zeta = wave.exact(out.times, .65*SPEED, .3) + assert np.max(abs(out.states[0, :, 3]-v))/SPEED < 1e-8 + assert np.max(abs(out.states[0, :, 2]-zeta)) < 1e-7 + np.testing.assert_allclose(out.states[0, :, :2], [[.3, .2]]*17, atol=1e-13) + field, wave = equilibrium(), spectrum(np.pi/2) + out = trace_boozer(field, [.3, .43], [.2, 1.4], [0., .3], [.65, -.7], tmax=1.5e-5, timestep=2e-7, + n_save=17, method="adaptive8", tolerance=1e-10, perturbation=wave, compact=False, **KW) + for states in out.states: + y = chart(states) + mu = SPEED**2*(1-(float(y[0, 3])/SPEED)**2)/(2*float(modB(field, y[0]))) + H, P = np.asarray(jax.vmap(lambda y, t: energy_momentum(field, wave, y, mu, t))(y, out.times)).T + K = H-OMEGA/N*P + assert np.max(abs(K-K[0]))/abs(H[0]) < 1e-8 + assert np.max(abs(H/H[0]-1)) > 1e-5 # wave work is real, K is the conserved combination + + +def test_amplitude_gradient_matches_finite_difference_through_gc_step(): field, wave = equilibrium(), mode() - y = jnp.array([.45, .27, -.3, .7*SPEED]) def objective(amplitude): changed = eqx.tree_at(lambda p: p.amplitude, wave, amplitude) rhs = lambda t, y: guiding_center_rhs(field, y, 1e12, MASS, CHARGE, t=t, perturbation=changed) - end = _rk_step(rhs, y, 1e-8, "rk4", t=2e-6) + end = _rk_step(rhs, POINT, 1e-8, "rk4", t=2e-6) return end[0]**2+end[1]**2 - amplitude, h = float(wave.amplitude), 1. - ad = float(jax.jit(jax.grad(objective))(amplitude)) - fd = float((objective(amplitude+h)-objective(amplitude-h))/(2*h)) + ad = float(jax.jit(jax.grad(objective))(2e4)) assert abs(ad) > 1e-12 - assert ad == pytest.approx(fd, rel=2e-5, abs=1e-13) - - -def test_unregularized_paper_harmonic_is_flagged_on_axis(): - field, wave = equilibrium(), mode(regularize_axis=False, axis_stop_s=None) - out = trace_boozer(field, [0.], [0.], [0.], [.7], speed=SPEED, mass=MASS, - charge=CHARGE, tmax=1e-7, timestep=1e-8, n_save=2, - perturbation=wave, method="rk4", progress=False, devices=jax.devices()[:1]) - assert out.failed[0] and not out.lost[0] - with pytest.raises(RuntimeError, match="trajectories fail"): - out.loss_fractions() + assert ad == pytest.approx(float((objective(2e4+1.)-objective(2e4-1.))/2), rel=2e-5, abs=1e-13) + # A mode may also be constructed inside the differentiated function. + xyz = jnp.array([.4, .2, .3]) + evaluate = lambda a: mode(amplitude=a).potentials(field, xyz, 1e-6)[1] + np.testing.assert_allclose(jax.jit(jax.grad(evaluate))(2e4), evaluate(1.), rtol=1e-13) -@pytest.mark.parametrize("kwargs", [dict(omega=0.), dict(m=1.5), dict(n=True), dict(radial_width=-1.)]) +@pytest.mark.parametrize("kwargs", [dict(omega=0.), dict(m=1.5), dict(n=True), dict(radial_width=-1.), + dict(axis_stop_s=0.), dict(axis_stop_s=np.nan), dict(axis_stop_s=1.)]) def test_invalid_mode_parameters_are_rejected(kwargs): with pytest.raises(ValueError): mode(**kwargs) -def test_per_marker_birth_speeds_and_zero_mode_trace(): +def test_per_marker_speeds_zero_amplitude_and_collision_rules(): field = equilibrium() - kwargs = dict(speed=[.8*SPEED, SPEED], mass=MASS, charge=CHARGE, tmax=2e-7, - timestep=1e-8, n_save=4, method="rk4", compact=False, progress=False, - devices=jax.devices()[:1]) - plain = trace_boozer(field, [.3, .4], [.2, .3], [0., .1], [.7, -.7], **kwargs) - zero = trace_boozer(field, [.3, .4], [.2, .3], [0., .1], [.7, -.7], - perturbation=mode(amplitude=0.), **kwargs) + speed = [.8*SPEED, SPEED] + kwargs = {**KW, "speed": speed, "tmax": 2e-7, "timestep": 1e-8, "n_save": 4, "method": "rk4", "compact": False} + births = ([.3, .4], [.2, .3], [0., .1], [.7, -.7]) + plain = trace_boozer(field, *births, **kwargs) + zero = trace_boozer(field, *births, perturbation=mode(amplitude=0.), **kwargs) np.testing.assert_allclose(plain.states, zero.states, rtol=2e-12, atol=1e-12) - np.testing.assert_allclose(plain.states[:, 0, 4], kwargs["speed"]) + np.testing.assert_allclose(plain.states[:, 0, 4], speed) + with pytest.raises(ValueError, match="fixed RK"): + trace_boozer(field, [.3], [0.], [0.], [.7], tmax=1e-6, perturbation=mode(), species=object(), + method="adaptive8", **KW) -@pytest.mark.parametrize("method", ["rk4", "adaptive8"]) +# Dopri5 shares the chunked-interval code of Dopri8 and compiles about twice as fast. +@pytest.mark.parametrize("method", ["rk4", "adaptive"]) def test_wave_time_is_preserved_across_progress_chunks_and_compaction(method): field, wave = equilibrium(), mode() - s = np.array([.9997, .3, .4, .45, .5, .55, .6]) - kwargs = dict(speed=SPEED, mass=MASS, charge=CHARGE, tmax=2e-6, - timestep=2e-8, n_save=11, method=method, tolerance=1e-10, - perturbation=wave, devices=jax.devices()[:1]) + s = np.array([.9997, .45, .6]) + kwargs = dict(tmax=2e-6, timestep=2e-8, n_save=11, method=method, tolerance=1e-10, perturbation=wave) births = (s, np.full(s.size, np.pi/2), np.zeros(s.size), np.full(s.size, .7)) - reference = trace_boozer(field, *births, progress=False, compact=False, **kwargs) + reference = trace_boozer(field, *births, compact=False, **kwargs, **KW) reports = [] - compact = trace_boozer(field, *births, progress=lambda done, total: reports.append(done), - compact=True, **kwargs) + compact = trace_boozer(field, *births, **kwargs, **{**KW, "progress": lambda done, total: reports.append(done)}) assert reference.lost.any() and (~reference.lost).any() assert reports[-1] == 10 np.testing.assert_allclose(compact.states, reference.states, rtol=1e-10, atol=1e-9) np.testing.assert_allclose(compact.loss_times, reference.loss_times, atol=1e-14) -def test_mode_can_be_constructed_inside_an_amplitude_gradient(): - field = equilibrium() - xyz = jnp.array([.4, .2, .3]) - evaluate = lambda amplitude: mode(amplitude=amplitude).potentials(field, xyz, 1e-6)[1] - np.testing.assert_allclose(jax.jit(jax.grad(evaluate))(1.e4), evaluate(1.), rtol=1e-13) - - -def test_combined_collisions_require_fixed_steps(): - with pytest.raises(ValueError, match="fixed RK"): - trace_boozer(equilibrium(), [.3], [0.], [0.], [.7], speed=SPEED, mass=MASS, - charge=CHARGE, tmax=1e-6, perturbation=mode(), species=object(), method="adaptive8") +# --- singular (radially uniform) modes and their inner boundary ------------------------------ + +def test_only_nonzero_singular_angular_modes_request_axis_stops(): + assert float(singular().axis_stop_threshold()) == 1e-8 + assert float(singular(amplitude=0.).axis_stop_threshold()) == 0. + assert mode().axis_stop_threshold() is None + assert singular(axis_stop_s=None).axis_stop_threshold() is None + assert AnalyticalAlfvenMode(0, N, OMEGA, 2000., regularize_axis=False).axis_stop_threshold() is None + assert float(AlfvenSpectrum(singular(), singular(axis_stop_s=1e-7)).axis_stop_threshold()) == 1e-7 + + +def test_axis_segment_intersection_detects_entry_and_pass_through(): + hit, fraction = _axis_intersection(jnp.array([-.2, 0., 0., 1.]), jnp.array([.2, 0., 0., 1.]), .01) + assert bool(hit) and float(fraction) == pytest.approx(.25) + # A tangentially displaced chord misses the disk; a disabled cutoff or nonfinite end never hits. + assert not bool(_axis_intersection(jnp.array([-.2, .2]), jnp.array([.2, .2]), .01)[0]) + assert not bool(_axis_intersection(jnp.array([-.2, 0.]), jnp.array([.2, 0.]), 0.)[0]) + assert not bool(_axis_intersection(jnp.array([.2, 0.]), jnp.array([jnp.nan, 0.]), .01)[0]) + + +@pytest.mark.parametrize("compact", [False, True]) +def test_births_inside_axis_boundary_stop_and_survive_compaction(compact): + out = trace_boozer(equilibrium(), [0., 5e-9, .3], [0., 0., .2], [0., 0., 0.], [1., 1., 1.], + tmax=1e-10, timestep=1e-11, n_save=4, method="rk4", perturbation=singular(), + compact=compact, **KW) + np.testing.assert_array_equal(out.axis_stopped, [True, True, False]) + np.testing.assert_allclose(out.axis_stop_times[:2], 0.) + assert not out.failed.any() and not out.lost.any() and np.isfinite(out.states).all() + np.testing.assert_allclose(out.states[:2], np.broadcast_to(out.states[:2, :1], out.states[:2].shape)) + np.testing.assert_allclose(out.loss_fractions(), 0.) + np.testing.assert_allclose(out.loss_fractions(include_axis=True), 2/3) + + +@pytest.mark.parametrize("method", ["rk4", "adaptive"]) +def test_incoming_orbit_stops_at_the_configured_boundary_with_a_finite_frozen_state(method): + cutoff = 1e-8 + out = trace_boozer(equilibrium(), [4*cutoff], [np.pi], [0.], [0.], tmax=2e-9, timestep=2e-11, n_save=6, + method=method, tolerance=1e-10, perturbation=singular(axis_stop_s=cutoff), + compact=False, **KW) + assert out.axis_stopped[0] and not out.lost[0] and not out.failed[0] + assert 0 < out.axis_stop_times[0] < out.times[-1] + assert out.states[0, -1, 0] == pytest.approx(cutoff, rel=1e-10) + frozen = out.states[0, out.times >= out.axis_stop_times[0]] + np.testing.assert_allclose(frozen, np.broadcast_to(frozen[0], frozen.shape)) + assert out.loss_fractions()[-1] == 0. and out.loss_fractions(include_axis=True)[-1] == 1. + + +def test_zero_amplitude_singular_mode_neither_stops_nor_fails_on_axis(): + out = trace_boozer(equilibrium(), [0., 1e-10], [0., .3], [0., 0.], [1., 1.], tmax=1e-10, timestep=1e-11, + n_save=3, method="rk4", perturbation=singular(amplitude=0.), compact=False, **KW) + assert not out.axis_stopped.any() and not out.failed.any() and np.isfinite(out.states).all() diff --git a/tests/test_vmec_boozer_map.py b/tests/test_vmec_boozer_map.py deleted file mode 100644 index b590fd40..00000000 --- a/tests/test_vmec_boozer_map.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Check the prescribed wave against booz_xform's independent output map.""" - -from pathlib import Path - -import jax -import jax.numpy as jnp -import numpy as np -import pytest - -from essos.dynamics import GuidingCenterMu, Particles, Tracing -from essos.electric_field import Electric_field_zero -from essos.fields import Vmec -from essos.gc_perturbations import MappedBoozerPerturbation, VmecBoozerMap -from essos.perturbations import AnalyticalAlfvenMode -from essos.boozer import BoozerField, psi0_from_vmec - - -WOUT = Path(__file__).resolve().parents[1]/"examples/input_files/wout_LandremanPaul2021_QA_reactorScale_lowres.nc" - - -@pytest.fixture(scope="module") -def transformed(): - Booz_xform = pytest.importorskip("booz_xform_jax").Booz_xform - from netCDF4 import Dataset - booz = Booz_xform(verbose=0, mboz=16, nboz=16) - booz.read_wout(str(WOUT), flux=False) - booz.run() - with Dataset(WOUT) as nc: - psi = psi0_from_vmec(nc.variables["phi"][-1]) - return booz, VmecBoozerMap.from_booz_xform(booz), BoozerField.from_booz_xform(booz, psi, angle_grid=None) - - -def test_map_agrees_with_booz_xform_inverse_output_and_chain_rule(transformed): - booz, mapping, background = transformed - j = len(booz.s_b)//2 - point = jnp.array([booz.s_b[j], .7, .3]) - mapped = mapping(point) - nu = np.sin(float(mapped[1])*np.asarray(booz.xm_b) - -float(mapped[2])*np.asarray(booz.xn_b))@np.asarray(booz.numns_b)[:, j] - assert float(mapped[2]-point[2]) == pytest.approx(nu, abs=2e-6) - np.testing.assert_allclose(mapping.inverse(mapped), point, atol=2e-13) - adapter = MappedBoozerPerturbation(background, AnalyticalAlfvenMode(15, 7, 399000., 1e4, - regularize_axis=False), mapping) - assert adapter.axis_stop_threshold() == 1e-8 - t = 1e-6 - derivative = jax.jit(lambda x, t: adapter.derivatives(None, x, t))(point, t)[1] - z = np.append(point, t) - columns = [] - for i, step in enumerate([1e-6, 1e-6, 1e-6, 1e-11]): - plus, minus = z+np.eye(4)[i]*step, z-np.eye(4)[i]*step - columns.append((adapter.potentials(None, plus[:3], plus[3]) - -adapter.potentials(None, minus[:3], minus[3]))/(2*step)) - np.testing.assert_allclose(derivative, np.stack(columns, axis=1), rtol=2e-6, atol=1e-6) - - -def test_vmec_wave_inner_cutoff_is_separate_from_lcfs_loss_and_failure(transformed): - _, mapping, background = transformed - field = Vmec(str(WOUT), ntheta=8, nphi=8, mode_tolerance=.01) - # Enlarge the cutoff to exercise both t=0 stopping and a root-found crossing - # without a long transport run or evaluating the potential on the axis. - wave = AnalyticalAlfvenMode(3, 2, 9e5, 1e3, regularize_axis=False, axis_stop_s=.36) - adapter = MappedBoozerPerturbation(background, wave, mapping) - particles = Particles(initial_xyz=jnp.array([[.35, .7, .3]]), - initial_vparallel_over_v=jnp.array([.65])) - speed = particles.total_speed - - def radial_speed(theta): - point = jnp.array([.36, theta, .3]) - mu = particles.mass*speed**2*(1-.65**2)/(2*field.AbsB(point)) - state = jnp.concatenate([point, jnp.array([.65*speed, mu])]) - return GuidingCenterMu(0., state, (field, particles, Electric_field_zero()), perturbation=adapter)[0] - - angles = jnp.linspace(0., 2*jnp.pi, 9)[:-1] - speeds = jax.jit(jax.vmap(radial_speed))(angles) - inward = int(jnp.argmin(speeds)) - assert speeds[inward] < 0 - moving = jnp.array([.36-float(speeds[inward])*5e-9, angles[inward], .3]) - particles = Particles(initial_xyz=jnp.vstack([particles.initial_xyz, moving]), - initial_vparallel_over_v=jnp.array([.65, .65])) - trace = Tracing(field=field, particles=particles, model="GuidingCenterAdaptative", - perturbation=adapter, maxtime=2e-8, timestep=1e-9, times_to_trace=3, - max_steps=32, progress=False, devices=jax.devices()[:1]) - assert trace.status[0] == 6 - assert trace.axis_stopped[0] and trace.axis_stop_times[0] == 0. - assert trace.status[1] == 6 and 0 < trace.axis_stop_times[1] < 2e-8 - assert trace.axis_stop_states[1, 0] == pytest.approx(.36, abs=1e-9) - assert not trace.failed.any() and not trace.boundary_hits.any() - np.testing.assert_allclose(trace.axis_stop_states[0, :3], particles.initial_xyz[0])