From 78020ca51ec2d332d24d7a376c87cef1c37cacff Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 4 Nov 2026 17:13:25 +0100 Subject: [PATCH 01/27] ForceFreeStates.Galerkin - FEATURE! - Prepare Galerkin results for inner-layer matching and publish their plasma response MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Groundwork for Galerkin inner-layer matching for PE, with the abstraction changes it needs on the Galerkin, Δ′ and matching side. Galerkin results now carry the solution, plasma energy matrix and free-boundary energies a Forward result does, and drive the perturbed-equilibrium response. Galerkin plasma response - The solve records edge_response, the edge momentum FΞ′ + KΞ of every solution column, from the edge rows of the stiffness before the boundary conditions replace them. On the error-field (EF) columns (a unit edge displacement per mode, no big-solution drive) it is W_P·ψ₀² [Glasser 2016, Eq. 66]; it agrees with Forward and Riccati to 2e-7 and converges at fourth order in nx. - With error_field_response (renamed from rpec_flag) the EF columns are published as the ideal-closed solution and wp, and with vac_flag the free-boundary energies, so plasma_response accepts the result. Both flags now default to true. MatchProblem's ideal keyword and the [Match] ideal key are removed: the Galerkin solve is itself the ideal solution. - A matched Galerkin result publishes its complex edge response W_eff = (F_EF + F_plasma·cout)/ψ₀² and its free-boundary energies; the anti-Hermitian part is the torque absorbed in the inner layers. plasma_response refuses every :matched result until matched singular coupling is defined. - free_run takes the plasma energy matrix wp, so Forward, Galerkin and matched results share it, and FreeBoundaryStability/W_plasma is written from result.wp. Δ′ payload - DeltaPrimeData has one meaning per field: raw_freeboundary, raw_fixedboundary, ef (Δ_EF, the response to a unit edge displacement with the edge otherwise fixed) and the PEST-3 blocks of both boundaries (PEST3Blocks, from pest3_decompose). Consumers read fields, not the integrator. - Galerkin and Riccati both compute both boundaries. Galerkin re-solves its big-solution columns with the vacuum edge for the free-boundary Δ′ (free_boundary_delta_prime, default true); Riccati takes the fixed-boundary Δ′ and Δ_EF from one Dirichlet-edge BVP and gains the same error_field_response flag. - With error_field_response the Galerkin tearing Δ′ was the fixed-boundary one; it is now free-boundary. - Matching pairs Δ_EF with raw_fixedboundary. Riccati paired it with its free-boundary Δ′, which gave matched coefficients and bpen wrong by order one at low rotation (4% at 1 kHz on the LAR deck); they now agree with Galerkin to ~1e-3. The [Match] deck guard checks error_field_response alone. - TearingProblem takes fixed_boundary=true for the fixed-boundary Δ′ (a conformal wall on the plasma); tearing refuses a result that lacks the requested boundary instead of falling back to a stub. Renames (clean break) - [Galerkin] rpec_flag → error_field_response; Delta_coil → Delta_EF (DeltaPrimeData.ef, SingularSurfaces/Delta_EF); MatchResult.rpec_eig → forced_eigenvalue (Match/forced_eigenvalue). - SingularSurfaces/Delta_prime_raw → Delta_prime_raw_freeboundary, plus Delta_prime_raw_fixedboundary and the *_fixedboundary PEST-3 blocks; Riccati now also writes pest3_A/B/Gamma. - Harness cases diiid_n1_riccati and gal_resistive_diiid follow the new paths and track the fixed-boundary Δ′ diagonal. --- docs/development/architecture.md | 2 +- docs/development/hdf5-conventions.md | 4 +- docs/src/api.md | 6 +- docs/src/galerkin.md | 16 +- docs/src/index.md | 2 +- docs/src/inner_layer.md | 2 +- docs/src/perturbed_equilibrium.md | 2 +- docs/src/stability.md | 6 +- docs/src/workflow.md | 12 +- .../gpec.toml | 8 +- examples/LAR_ideal_match_test/gpec.toml | 15 +- examples/LAR_resistive_match_test/gpec.toml | 4 +- .../cases/diiid_n1_riccati.toml | 17 +- .../cases/gal_resistive_diiid.toml | 27 ++- src/Deck.jl | 11 +- src/ForceFreeStates/CoreTypes.jl | 25 +-- src/ForceFreeStates/EulerLagrange.jl | 2 +- src/ForceFreeStates/Free.jl | 26 +-- .../Galerkin/GalerkinAssembly.jl | 13 +- src/ForceFreeStates/Galerkin/GalerkinSolve.jl | 149 +++++++------ .../Galerkin/GalerkinStructs.jl | 3 + src/ForceFreeStates/Integrators.jl | 11 +- src/ForceFreeStates/Matching/DeltaPrime.jl | 81 ++++--- src/ForceFreeStates/Matching/MatchProblem.jl | 202 ++++++++---------- src/ForceFreeStates/Matching/ResonantMatch.jl | 40 ++-- src/ForceFreeStates/Output.jl | 30 ++- src/ForceFreeStates/Result.jl | 63 ++++-- src/ForceFreeStates/Riccati/Crossings.jl | 2 +- src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 136 ++++-------- src/ForceFreeStates/Run.jl | 9 +- src/ForceFreeStates/Surfaces/Types.jl | 2 +- .../PerturbedEquilibrium.jl | 20 +- src/Tearing/Dispersion/CoupledFullMatch.jl | 4 +- src/Tearing/GGJTearing.jl | 26 ++- src/Tearing/HDF5Output.jl | 3 +- src/Tearing/TearingProblem.jl | 10 +- src/Utilities/HDF5Schema.jl | 24 ++- test/runtests_galerkin_cholesky.jl | 2 +- test/runtests_parallel_integration.jl | 11 +- test/runtests_result_struct.jl | 73 +++---- test/runtests_riccati.jl | 4 +- test/runtests_slayer_runner.jl | 4 +- test/runtests_solve_api.jl | 109 +++++++--- 43 files changed, 637 insertions(+), 581 deletions(-) diff --git a/docs/development/architecture.md b/docs/development/architecture.md index 781f0b1559..c54e02c8df 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -210,7 +210,7 @@ The complete GPEC analysis pipeline: ### Stability - `SingType` - Singular surface data including: - Rational surface location (ψ, ρ, q = m/n, dq/dψ) - - Δ' (tearing stability parameter) — **stub**; the valid Δ' is `ForceFreeStatesResult.delta_prime.matrix` + - Δ' (tearing stability parameter) — **stub**; the valid Δ' is `ForceFreeStatesResult.delta_prime` (`DeltaPrimeData`) - Asymptotic solution bases at the inner-layer boundaries - `ForceFreeStatesResult` - Published product of a solve: mode space, metric/matrix fits, singular surfaces, and the per-integrator products (ξ solution and its basis, free-boundary energies, diff --git a/docs/development/hdf5-conventions.md b/docs/development/hdf5-conventions.md index 403fb7ffc5..c91493f811 100644 --- a/docs/development/hdf5-conventions.md +++ b/docs/development/hdf5-conventions.md @@ -6,7 +6,7 @@ Conventions for the structure and naming of the `gpec.h5` output file. Every wri **The schema must be intuitive to a plasma physicist who is not a developer of this code.** The top level largely mirrors the TOML sections / major `src/` modules — which are themselves organized along physics lines — but **physics intuition wins whenever the two diverge**. Worked examples of that rule: -- All per-rational-surface stability results consolidate under `SingularSurfaces/`, regardless of which algorithm produced them: the GGJ coefficients sit beside the Δ′/PEST-3 matching results, and the Riccati BVP and the Galerkin outer-region solve write the *same* `Delta_prime_matrix`/`Delta_prime_raw`/`Delta_coil`/`pest3_*` paths rather than each owning a producer-named subgroup. +- All per-rational-surface stability results consolidate under `SingularSurfaces/`, regardless of which algorithm produced them: the GGJ coefficients sit beside the Δ′/PEST-3 matching results, and the Riccati BVP and the Galerkin outer-region solve write the *same* `Delta_prime_*`/`Delta_EF`/`pest3_*` paths rather than each owning a producer-named subgroup. - `EulerLagrangeMatrices` over a bare `Matrices` — group names must say what the data *is*, not which array it came from. Same reasoning renamed `matrices_/` → `KineticMatrices/`. Physics-topic groups elevated to top level (rather than nested under their producer): `Info/`, `Input/`, `SingularSurfaces/`, `LocalStability/`, `SurfaceGeometries/`. @@ -42,7 +42,7 @@ Top level (11 groups): | `Equilibrium/` | Scalars (`beta_N`, `q_axis`, `q_95`, `I_p`, …) plus `Profiles/` (1-D on `psi`: 2piF, mu0p, dVdpsi, q) and `Geometry/` (2-D on `psi`×`theta`: rcoords, offset, nu, jac) | | `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (closed ξ profiles in the shared layout, the gal surface list, `gal_basis_output`-gated `Basis/`), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | -| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_matrix`/`Delta_prime_raw`/`Delta_coil`/`pest3_A`/`pest3_B`/`pest3_Gamma` (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | +| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_raw_freeboundary`/`Delta_prime_raw_fixedboundary`/`Delta_EF`, the free-boundary `Delta_prime_matrix`/`pest3_A`/`pest3_B`/`pest3_Gamma` and their `_fixedboundary` counterparts (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | | `PerturbedEquilibrium/` | `ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | | `KineticForces/` | `/` (torque/energy profiles, `dTdpsi_ell` resolved by bounce harmonic on the `ell` scale, `KineticMatrices/`); multi-ion runs add `PerSpecies///` with the same per-method layout, summing to the top-level total | | `ErrorFields/` | `CoilSensitivities/` (per-coil-set control-surface spectra and their rigid shift/tilt derivatives, `DominantMode/` full-window projection); `MonteCarlo/` (intrinsic and corrected `\|δ\|` histograms over the sampled tolerances, per batch and averaged); `Risk/` (threshold density, `P(lock\|δ)`, locking probabilities, `ToleranceScan/`); `NTV/` (correction-coil overlap and NTV torque couplings per kAt) | diff --git a/docs/src/api.md b/docs/src/api.md index c520cf44b5..895be534c4 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -86,7 +86,7 @@ ffs = solve(eq, Riccati(; nchunks=40); nn=1, vac_flag=true) ffs = solve(eq, Galerkin(; nx=512); nn=1) # finite-element outer-region Δ′ ``` -A result carries `nothing` in the fields its integrator does not produce, and consumers warn and skip rather than erroring; `plasma_response` in particular needs a `Forward()` solve with `wall=nothing` (it errors on a wall or a Galerkin result and skips with a warning on a Riccati one), see [Stability](stability.md). +A result carries `nothing` in the fields its integrator does not produce, and consumers warn and skip rather than erroring; `plasma_response` in particular needs a `Forward()` solve, or a `Galerkin(; error_field_response=true)` solve with `vac_flag=true`, with `wall=nothing` (it errors on a wall, any other Galerkin result or a matched one, and skips with a warning on a Riccati one), see [Stability](stability.md). A kinetic solve takes `Forward()` with the problem's `kinetic` keyword: `kinetic=KineticForcesControl(; ...)` evaluates the drift-kinetic matrices on the equilibrium's kinetic profiles, `kinetic=TestKineticMatrices(; scale)` uses synthetic matrices, `kinetic_factor` scales either, and `km = kinetic_matrices(prob)` evaluates the source once for reuse in later solves ([`KineticMatrices`](@ref GeneralizedPerturbedEquilibrium.ForceFreeStates.KineticMatrices)). ## Inner-layer matching @@ -94,13 +94,13 @@ A kinetic solve takes `Forward()` with the problem's `kinetic` keyword: `kinetic A `MatchProblem` holds the outer Δ′ a solve published plus per-surface layer parameters, and the inner-layer model passed to `solve` computes the layer response at the prescribed rotation; the result is a new `ForceFreeStatesResult` with the closure changed from `:ideal` to `:matched` and the eigenfunctions replaced, so layer-parameter scans cost one cheap match per point: ```julia -ffs = solve(eq, Galerkin(; rpec_flag=true, cut_solution=true); nn=1) +ffs = solve(eq, Galerkin(; error_field_response=true, cut_solution=true); nn=1) matched = solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=0.0), GGJModel()) bpens = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).bpen for f in 0.0:50.0:500.0] ``` A scalar applies to every surface and a vector gives one value per entry of `ffs.surfaces`, core to edge. -The problem needs a Δ′ payload with coil-response columns, so it accepts Galerkin (`rpec_flag=true`) and Riccati (`vac_flag=true`) results; a Riccati-fed match fills `bpen` and the resonant data but keeps `solution === nothing`. +The problem needs a Δ′ payload with error-field (EF) columns, so it accepts Galerkin and Riccati results with `error_field_response=true` (the default; Riccati also needs `vac_flag=true`); a Riccati-fed match fills `bpen` and the resonant data but keeps `solution === nothing`. `GGJModel()` is the closure-capable model; `SLAYERModel()` is slab-only and drives the tearing solve instead. ## Tearing stability diff --git a/docs/src/galerkin.md b/docs/src/galerkin.md index b3e59a745b..52778708e5 100644 --- a/docs/src/galerkin.md +++ b/docs/src/galerkin.md @@ -23,24 +23,24 @@ integrator = "Galerkin" [Galerkin] nx = 256 # Hermite-cubic elements per interval between singular surfaces pfac = 0.03 # grid packing ratio toward the singular surfaces -rpec_flag = true # edge coil-response columns (Delta_coil), needed by [Match] and [Tearing] +error_field_response = true # error-field (EF) columns (Delta_EF): the ideal ξ solution and W_plasma, needed by [Match] ``` `cut_solution = true` (default `false`) adds the cut solution that composite inner-region profiles need. -It replaces the radial integration rather than supplementing it: the run computes its own vacuum response at the control surface (with `vac_flag`) but produces no free-boundary energies, no ODE trace and no `crit` scan, it does not support the kinetic solve, and its result cannot drive `[PerturbedEquilibrium]`, which needs the free-boundary δW of a `"Forward"` solve. -A `[Match]` section matches the inner layer to its Δ′ and gives a driven ``\xi`` solution; the composite inner-region profiles need `cut_solution = true` (`Galerkin(; cut_solution=true)` followed by `solve(MatchProblem(ffs))` in a script). +It replaces the radial integration rather than supplementing it: the run computes its own vacuum response at the control surface (with `vac_flag`), produces no ODE trace and no `crit` scan, and does not support the kinetic solve. With `error_field_response = true` and `vac_flag = true` it also produces the free-boundary energies of its ideal solution, so it can drive `[PerturbedEquilibrium]` like a `"Forward"` solve; a `[Match]`ed result cannot yet. +With `error_field_response = true` the error-field (EF) columns, one per edge mode with unit edge displacement and no inner-layer drive, are solved with the edge held fixed; their small-solution coefficients are `Delta_EF`, they are the ideal (perfectly shielded) ``\xi`` solution, and the force they exert on the edge is the fixed-boundary plasma energy matrix ``W_P`` of Eq. 66 of [Glasser (2016)](citations.md#ForceFreeStates). +A `[Match]` section matches the inner layer to its Δ′ and replaces them with the driven ``\xi`` solution, whose edge response ``W_P`` is complex: its anti-Hermitian part is the torque absorbed in the layers. The composite inner-region profiles need `cut_solution = true` (`Galerkin(; cut_solution=true)` followed by `solve(MatchProblem(ffs))` in a script). ## Outputs | Dataset | Meaning | |---|---| -| `SingularSurfaces/Delta_prime_matrix` | the Δ′ matrix in the PEST-3 convention, on the same path as the Riccati result, so downstream stages never branch on which formalism ran | -| `SingularSurfaces/Delta_prime_raw`, `Delta_coil` | the side-major matching matrix and the coil-response columns (`rpec_flag = true`) | -| `SingularSurfaces/pest3_A`, `pest3_B`, `pest3_Gamma` | the PEST-3 interchange and mixed blocks ``A'``, ``B'``, ``\Gamma'`` | +| `SingularSurfaces/Delta_prime_matrix` | the Δ′ matrix in the PEST-3 convention, on the same path as the Riccati result, so downstream stages never branch on which formalism ran; free-boundary with `vac_flag = true` (with `error_field_response = true` a second factorization re-solves the big-solution columns with the vacuum edge, so the EF columns never enter it; `free_boundary_delta_prime = false` skips it for matching-only scans, leaving no tearing Δ′) and fixed-boundary otherwise | +| `SingularSurfaces/Delta_prime_raw_freeboundary`, `Delta_prime_raw_fixedboundary`, `Delta_EF` | the side-major matching matrices with the vacuum and the fixed edge, and the error-field (EF) response (`error_field_response = true`) | +| `SingularSurfaces/pest3_A`, `pest3_B`, `pest3_Gamma` (and `_fixedboundary`) | the PEST-3 interchange and mixed blocks ``A'``, ``B'``, ``\Gamma'`` | | `ForceFreeStates/Solutions/GalerkinIntegration/` | the closed ``\xi`` profiles on the Galerkin grid, the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | - -Nothing is written under `ForceFreeStates/FreeBoundaryStability/`. +| `ForceFreeStates/FreeBoundaryStability/` | `W_plasma`, the plasma energy matrix ``W_P`` of the closed solution (`error_field_response = true`), and with `vac_flag = true` the vacuum and free-boundary energies and eigenmodes as for a `"Forward"` solve | ## Numerical notes diff --git a/docs/src/index.md b/docs/src/index.md index aa6f53553e..65c06a44c7 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -24,7 +24,7 @@ The [Workflow](workflow.md) page maps every stage to its physics, deck sections | `ForceFreeStates` — ideal (or drift-kinetic) MHD stability by the Newcomb criterion, with the `Vacuum` response of the `[Wall]` (a wall case is a separate deck from a response case) | `[ForceFreeStates]` | `ForceFreeStates/FreeBoundaryStability/`, `SingularSurfaces/Delta_prime_matrix` | | `LocalStability` — Mercier, resistive-interchange and ballooning criteria | `[LocalStability]` | `LocalStability/` | | `Match` — the resistive inner layer matched to the outer-region Δ′ | `[Match]` | `SingularSurfaces/Match/` | -| `PerturbedEquilibrium` — the plasma response to the field of `[ForcingTerms]`: resonant fields, islands, overlap; needs a `"Forward"` solve without a wall | `[PerturbedEquilibrium]` | `PerturbedEquilibrium/SingularCoupling/` | +| `PerturbedEquilibrium` — the plasma response to the field of `[ForcingTerms]`: resonant fields, islands, overlap; needs a `"Forward"` (or `error_field_response` `"Galerkin"`) solve without a wall | `[PerturbedEquilibrium]` | `PerturbedEquilibrium/SingularCoupling/` | | `KineticForces` — the neoclassical toroidal viscosity torque of that response | `[KineticForces]` | `KineticForces/` | | `ErrorFields` — coil tolerances, locking risk and correction limits | `[ErrorFields]` | `ErrorFields/Risk/` | | `Tearing` — tearing growth rates and critical resonant fields from an inner-layer model | `[Tearing]` | `Tearing/Roots/` | diff --git a/docs/src/inner_layer.md b/docs/src/inner_layer.md index e67b984ffd..fd2fa7374b 100644 --- a/docs/src/inner_layer.md +++ b/docs/src/inner_layer.md @@ -50,7 +50,7 @@ Penetration is the first resolved saddle-node bifurcation on the path from ``Q_0 ## Running it -From `examples/DIIID-like_SLAYER_example/gpec.toml`, after a `[ForceFreeStates]` solve with `integrator = "Riccati"` and `vac_flag = true` (or `"Galerkin"` with `rpec_flag = true`), which provides the Δ′ matrix, and with a kinetic file on the equilibrium: +From `examples/DIIID-like_SLAYER_example/gpec.toml`, after a `[ForceFreeStates]` solve with `integrator = "Riccati"` or `"Galerkin"` and `vac_flag = true`, which provides the Δ′ matrix, and with a kinetic file on the equilibrium: ```toml [Tearing] diff --git a/docs/src/perturbed_equilibrium.md b/docs/src/perturbed_equilibrium.md index b5b9d27a93..db15d4a465 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -92,7 +92,7 @@ The coupling matrices `C_*` map the applied ``\tilde b`` to each of these quanti ## Running it The response needs a force-free-states solve with `integrator = "Forward"` and no `[Wall]`. -`"Forward"` is the only integrator that retains the dense ``\xi`` solution the operators are built from: a `"Riccati"` solve (the deck default) makes `plasma_response` warn that the response is skipped and return empty operators, so the failure surfaces only when a field is applied, and a `"Galerkin"` or `[Match]`ed solve, which publishes no free-boundary δW, is an error. +The operators are built from a dense ``\xi`` solution with its free-boundary δW, which a `"Forward"` solve and a `"Galerkin"` solve with `error_field_response = true` and `vac_flag = true` both provide: a `"Riccati"` solve (the deck default) makes `plasma_response` warn that the response is skipped and return empty operators, so the failure surfaces only when a field is applied, while a `"Galerkin"` solve without those flags or a `[Match]`ed solve, whose singular coupling is not defined yet, is an error. The ψ-resolved torque response (`compute_torque_response`) needs a `"Forward"` kinetic solve. A solve with a wall is an error too, because the surface inductance is the free-space one and ``\Lambda`` from a wall run would mix two vacuum models; the wall case of a stability study is therefore a separate deck. From `examples/DIIID-like_ideal_example/gpec.toml`, after the `[ForceFreeStates]` solve and a `[ForcingTerms]` drive: diff --git a/docs/src/stability.md b/docs/src/stability.md index aa86df2ecb..706b89725d 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -59,7 +59,7 @@ qlow = 1.02 # inner edge of the integration domain qhigh = 1e3 # outer bound of qlim (see Integration domain) delta_mlow = 8 # extra poloidal modes below the resonant range delta_mhigh = 8 # extra poloidal modes above it -integrator = "Forward" # "Riccati" is the default; "Forward" (and no [Wall]) is required for [PerturbedEquilibrium] +integrator = "Forward" # "Riccati" is the default; "Forward" or an error_field_response "Galerkin" (and no [Wall]) is required for [PerturbedEquilibrium] truncate_at_rational_offset = true rational_offset_fraction = 0.2 @@ -81,7 +81,7 @@ ffs = solve(eq, Riccati(; eulerlagrange_tolerance=1e-10); nn=1, delta_mlow=8, de real(ffs.free_boundary.et[1]) # least free-boundary eigenmode energy: negative is unstable for (s, sing) in enumerate(ffs.surfaces) - println("q = $(sing.m[1])/$(sing.n[1]) at ψ_N = $(sing.psifac): Δ′ = $(real(ffs.delta_prime.matrix[s, s]))") + println("q = $(sing.m[1])/$(sing.n[1]) at ψ_N = $(sing.psifac): Δ′ = $(real(ffs.delta_prime.freeboundary.Delta[s, s]))") end ``` @@ -103,7 +103,7 @@ The number of Julia threads is set at startup (`-t N` or `JULIA_NUM_THREADS`); t | `SingularSurfaces/rational_psi`, `rational_q`, `rational_m`, `rational_n`, `dqdpsi` | the rational surfaces of the domain, core to edge | | `SingularSurfaces/D_I`, `E`, `F`, `G`, `H`, `K`, `M` | the Mercier index and the Glasser–Greene–Johnson layer coefficients at each surface | | `SingularSurfaces/ca_left`, `ca_right` | the asymptotic (large, small) coefficients on either side of each surface, from ideal crossings | -| `SingularSurfaces/Delta_prime_matrix` | the Δ′ matrix in the PEST-3 convention, from `"Riccati"` or `"Galerkin"`; `Delta_prime_raw` is the side-major (left, right) matrix it is folded from, `Delta_coil` the edge coil-response columns | +| `SingularSurfaces/Delta_prime_matrix` | the free-boundary Δ′ matrix in the PEST-3 convention, from `"Riccati"` or `"Galerkin"`, with `pest3_A`, `pest3_B`, `pest3_Gamma`; `Delta_prime_raw_freeboundary` is the side-major (left, right) matrix they are folded from. The same set with a `_fixedboundary` suffix is the Δ′ with a conformal wall on the plasma, and `Delta_EF` the error-field response | | `SingularSurfaces/Kinetic/` | the surfaces of a kinetic solve | The energy matrices are power-normalized: the eigenmode energies are the generalized eigenvalues of the pencil ``W v = \lambda N v``, with ``N`` the surface-norm matrix ``\xi^\dagger N \xi = \langle|\xi|^2\rangle`` built from the Jacobian Fourier coefficients, so each is an energy per unit surface-averaged squared displacement rather than joules, and the spectrum is invariant to the working coordinate because ``W`` and ``N`` transform by the same congruence. diff --git a/docs/src/workflow.md b/docs/src/workflow.md index 38b4cdd8ba..8a491300b4 100644 --- a/docs/src/workflow.md +++ b/docs/src/workflow.md @@ -29,7 +29,7 @@ Every stage after `Equilibrium` reads the force-free states, and `KineticForces` | What are the tearing growth rate and critical resonant field? | `[Tearing]` (+ `[SLAYER]` or `[GGJ]`) | `Tearing/Roots/gamma`, `Tearing/Roots/omega`, `Tearing/CriticalResonantField/` | | What does a resistive inner layer do to the response? | `[Match]` (+ `[GGJ]`) | `SingularSurfaces/Match/` | -`[PerturbedEquilibrium]` and the stages built on it need a `[ForceFreeStates]` solve with `integrator = "Forward"` and no `[Wall]`, while the Δ′ matrix, `[Tearing]` and wall stability need `"Riccati"` or `"Galerkin"` or a `[Wall]`, so one deck cannot do both: run the response and the Δ′ or wall cases as separate decks (`DIIID-like_ideal_example` and `DIIID-like_riccati_deltaprime_example` are such a pair). +`[PerturbedEquilibrium]` and the stages built on it need a `[ForceFreeStates]` solve with `integrator = "Forward"`, or `"Galerkin"` with `error_field_response = true` and `vac_flag = true`, and no `[Wall]`, while the Δ′ matrix, `[Tearing]` and wall stability need `"Riccati"` or `"Galerkin"` or a `[Wall]`. Only a `"Galerkin"` deck without a `[Wall]` does both; otherwise run the response and the Δ′ or wall cases as separate decks (`DIIID-like_ideal_example` and `DIIID-like_riccati_deltaprime_example` are such a pair). ### Headline outputs @@ -68,7 +68,7 @@ Page: [Local Stability](ballooning.md). ### Match -Matches the outer-region Δ′ to a resistive inner layer (`inner_model = "GGJ"`, the only model, with its options in an optional `[GGJ]` section) and rebuilds the force-free states with the resulting layer response, writing the matched solution and the penetrated resonant fields to `SingularSurfaces/Match/`; `ideal = true` keeps the shielded limit for comparison. +Matches the outer-region Δ′ to a resistive inner layer (`inner_model = "GGJ"`, the only model, with its options in an optional `[GGJ]` section) and rebuilds the force-free states with the resulting layer response, writing the matched solution and the penetrated resonant fields to `SingularSurfaces/Match/`; the Galerkin solve without `[Match]` is the shielded limit for comparison. Outputs: `SingularSurfaces/Match/`. Page: [Tearing](inner_layer.md). @@ -76,7 +76,7 @@ Page: [Tearing](inner_layer.md). Computes the plasma response to an external non-axisymmetric field: `plasma_response` builds the permeability, inductance and reluctance operators on the control surface from the force-free states and the vacuum matrices, and `perturbed_equilibrium` applies them to the drive that `ForcingTerms` supplies, either a normal-field spectrum from a file or the Biot–Savart field of `[[ForcingTerms.coil_set]]` coils. The resonant fields, island half-widths and Chirikov parameter at each rational surface follow from the singular coupling (`compute_singular_coupling`), and `regularization_width` controls the regularization of the ideal response there. -The response is built only from a `"Forward"` solve without a wall: a `"Riccati"` result (the default) makes `plasma_response` skip the operators with a warning, and a `"Galerkin"` or matched result or a wall is an error. +The response is built from a `"Forward"` solve, or a `"Galerkin"` solve with `error_field_response = true` and `vac_flag = true`, without a wall: a `"Riccati"` result (the default) makes `plasma_response` skip the operators with a warning, and any other `"Galerkin"` result, a matched result or a wall is an error. Outputs: `PerturbedEquilibrium/ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`. Key references: [Park et al. (2007a)](citations.md#PerturbedEquilibrium), [Park et al. (2009)](citations.md#PerturbedEquilibrium). Pages: [Forcing Terms](forcing_terms.md), [Perturbed Equilibrium](perturbed_equilibrium.md). @@ -100,7 +100,7 @@ Page: [Error Fields](error_fields.md). Solves the tearing dispersion relation of each rational surface by matching the outer-region Δ′ to an inner-layer model: the two-fluid slab `SLAYER` (`[SLAYER]`) or the toroidal resistive-MHD `GGJ` (`[GGJ]`), selected by `[Tearing] inner_model`. `[Tearing.search]` sets the root search in the complex frequency plane, and `[Tearing.CriticalResonantField]` adds the resonant field at which the layer's shielding is overcome. -Needs the Δ′ matrix of `"Riccati"` with `vac_flag = true` or `"Galerkin"` with `[Galerkin] rpec_flag = true`, and the kinetic profiles of `[Equilibrium] kinetic_file` (`SLAYER` reads its densities, temperatures, rotation and diffusivities there). +Needs the free-boundary Δ′ matrix of `"Riccati"` or `"Galerkin"` with `vac_flag = true` (or the fixed-boundary one with `fixed_boundary = true`), and the kinetic profiles of `[Equilibrium] kinetic_file` (`SLAYER` reads its densities, temperatures, rotation and diffusivities there). Outputs: `Tearing/PerSurface/`, `Roots/`, `LayerWidths/`, `Diagnostics/`, `CriticalResonantField/`. Key references: [Glasser, Wang and Park (2016)](citations.md#Tearing), [Park (2022)](citations.md#Tearing). Page: [Tearing](inner_layer.md). @@ -127,7 +127,7 @@ alpha_boundary_scan = true [ForceFreeStates] nn = 1 vac_flag = true -integrator = "Forward" # "Forward": [PerturbedEquilibrium] needs the dense ξ solution and no [Wall] ("Riccati" is the default) +integrator = "Forward" # "Forward": [PerturbedEquilibrium] needs a dense ξ solution and no [Wall] ("Riccati" is the default) [ForcingTerms] forcing_data_format = "coil" @@ -191,7 +191,7 @@ From Julia, the same pipeline is `GeneralizedPerturbedEquilibrium.main(["example | `Solovev_ideal_example_3D` | the same plasma with the vacuum response on a toroidal grid | | `Solovev_ideal_example_multi_n` | the same plasma swept over n = 1 and 2 in one run, with single-n cross-checks | | `LAR_reversed_shear_example` | a `[LargeAspectRatio]` equilibrium with reversed shear, q = 2 crossed twice | -| `LAR_ideal_match_test` | a `[TJAnalytic]` equilibrium with `[Match] ideal = true`, the shielded reference for the resistive case | +| `LAR_ideal_match_test` | a `[TJAnalytic]` equilibrium solved by Galerkin without `[Match]`, the shielded reference for the resistive case | | `LAR_resistive_match_test` | the same equilibrium with resistive GGJ matching | | `LAR_beta_scan`, `LAR_epsilon_scan` | `run_scan.jl` sweeps of the `[TJAnalytic]` pressure factor and inverse aspect ratio | | `TJ_ideal_example` | a `[TJAnalytic]` equilibrium: n = 1 stability and a file-driven perturbed equilibrium | diff --git a/examples/DIIID-like_gal_resistive_example/gpec.toml b/examples/DIIID-like_gal_resistive_example/gpec.toml index 0abc47dc1c..909d79cc43 100644 --- a/examples/DIIID-like_gal_resistive_example/gpec.toml +++ b/examples/DIIID-like_gal_resistive_example/gpec.toml @@ -1,6 +1,6 @@ # DIII-D-like H-mode resistive-MHD example: outer-region singular Galerkin Δ′ solve. # n=1 tearing stability on the bundled geqdsk: the gal solver computes the Δ′ -# matching matrix (PEST-3 convention) plus rpec coil-response columns (delta_coil). +# matching matrix (PEST-3 convention) plus error-field (EF) columns (Delta_EF). # The core_edge_packed radial grid is densest at the axis and edge; psihigh = 0.993 # stays clear of the separatrix. No forcing and no PerturbedEquilibrium stage. [Run] @@ -53,8 +53,8 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati frobenius_order = 6 # Order of singular layer (Frobenius) expansion at rational surfaces -# Outer-region singular Galerkin Δ′ solver with rpec coil columns. -# This case exercises the gal solve AND the rpec coil/edge path (delta_coil) for regression tracking. +# Outer-region singular Galerkin Δ′ solver with error-field (EF) columns. +# This case exercises the gal solve AND the EF/edge path (Delta_EF) for regression tracking. [Galerkin] nx = 256 # Hermite-cubic elements per interval between singular surfaces nq = 6 # Gauss-Lobatto quadrature order per element @@ -67,7 +67,7 @@ tol = 1e-10 # Resonant-cell adaptive-quadrature (QuadGK) tole gnstep = 5000 # Maximum resonant-integration steps dx1dx2_flag = true # Enable the special dx1/dx2 element sizing for resonant/extension cells frobenius_order_ceiling = true # Auto-raise the series order by ceil(2·Re(α)) on high-Mercier-index surfaces -rpec_flag = true # Append mpert coil-response columns (unit edge sources) to the solve → delta_coil block +error_field_response = true # Add the error-field (EF) columns, a unit edge displacement per mode: gives Delta_EF, the ideal solution and wp # Driven inner-layer matching on the finished solve. Per-surface resistive inputs (core→edge) for a DIII-D-like case: # η=8e-8, ρ=3.3e-7 kg/m³ (ni≈1e20 m^-3), rotation=1 Hz, Γ=5/3. 4 surfaces. diff --git a/examples/LAR_ideal_match_test/gpec.toml b/examples/LAR_ideal_match_test/gpec.toml index d266d6af90..5717eaa9e1 100644 --- a/examples/LAR_ideal_match_test/gpec.toml +++ b/examples/LAR_ideal_match_test/gpec.toml @@ -1,9 +1,8 @@ # LAR ideal-limit reference: large-aspect-ratio analytic TJ equilibrium, epsilon = a/R0 = 0.2, n = 1. # -# The ideal-limit companion to LAR_resistive_match_test, identical except that [Match] ideal = true skips -# the resistive inner layer entirely and builds the bare (perfectly shielded) coil columns. Running -# the two side by side isolates what the inner layer contributes on this geometry. The per-surface -# resistivity, density and rotation inputs are omitted here because the ideal limit never reads them. +# The ideal-limit companion to LAR_resistive_match_test, identical except that it has no [Match] section: +# the Galerkin solve's EF columns are already the perfectly shielded solution. Running the two side by +# side isolates what the inner layer contributes on this geometry. # This run terminates after the stability stage. [Run] @@ -63,7 +62,7 @@ integrator = "Galerkin" # Integration formalism, whose numerical settings are it truncate_at_rational_offset = false # Keep psilim at psihigh (do not truncate at last_rational_q + rational_offset_fraction) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n (only used when truncate_at_rational_offset = true) -# Outer-region singular Galerkin Delta-prime solver with rpec coil columns. +# Outer-region singular Galerkin Delta-prime solver with error-field (EF) columns. [Galerkin] nx = 256 # Hermite-cubic elements per interval between singular surfaces nq = 6 # Gauss-Lobatto quadrature order per element @@ -76,8 +75,4 @@ tol = 1e-10 # Resonant-cell adaptive-quadrature (QuadGK) tole gnstep = 5000 # Maximum resonant-integration steps dx1dx2_flag = true # Enable the special dx1/dx2 element sizing for resonant/extension cells frobenius_order_ceiling = true # Auto-raise the series order by ceil(2*Re(alpha)) on high-Mercier-index surfaces -rpec_flag = true # Append mpert coil-response columns (unit edge sources) to the solve, giving the delta_coil block - -# Driven inner-layer matching on the finished solve in the ideal limit: the inner layer is skipped entirely. -[Match] -ideal = true # true = build the IDEAL solution (skip the inner layer, bare coil columns) +error_field_response = true # Add the error-field (EF) columns, a unit edge displacement per mode: gives Delta_EF, the ideal solution and wp diff --git a/examples/LAR_resistive_match_test/gpec.toml b/examples/LAR_resistive_match_test/gpec.toml index 248f1cd143..4fb3f0da0e 100644 --- a/examples/LAR_resistive_match_test/gpec.toml +++ b/examples/LAR_resistive_match_test/gpec.toml @@ -64,7 +64,7 @@ integrator = "Galerkin" # Integration formalism, whose numerical settings are it truncate_at_rational_offset = false # Keep psilim at psihigh (do not truncate at last_rational_q + rational_offset_fraction) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n (only used when truncate_at_rational_offset = true) -# Outer-region singular Galerkin Delta-prime solver with rpec coil columns. +# Outer-region singular Galerkin Delta-prime solver with error-field (EF) columns. [Galerkin] nx = 256 # Hermite-cubic elements per interval between singular surfaces nq = 6 # Gauss-Lobatto quadrature order per element @@ -77,7 +77,7 @@ tol = 1e-10 # Resonant-cell adaptive-quadrature (QuadGK) tole gnstep = 5000 # Maximum resonant-integration steps dx1dx2_flag = true # Enable the special dx1/dx2 element sizing for resonant/extension cells frobenius_order_ceiling = true # Auto-raise the series order by ceil(2*Re(alpha)) on high-Mercier-index surfaces -rpec_flag = true # Append mpert coil-response columns (unit edge sources) to the solve, giving the delta_coil block +error_field_response = true # Add the error-field (EF) columns, a unit edge displacement per mode: gives Delta_EF, the ideal solution and wp # Driven inner-layer matching on the finished solve. Per-surface resistive inputs (core to edge) for the two # rational surfaces q = 2 and q = 3: eta=8e-8, rho=3.3e-7 kg/m^3, rotation=1 Hz, Gamma=5/3. diff --git a/regression-harness/cases/diiid_n1_riccati.toml b/regression-harness/cases/diiid_n1_riccati.toml index f41d9ed0a7..40ce046ab3 100644 --- a/regression-harness/cases/diiid_n1_riccati.toml +++ b/regression-harness/cases/diiid_n1_riccati.toml @@ -21,18 +21,27 @@ noise_threshold = 1e-8 order = 10 [quantities.delta_prime_raw] -h5path = "SingularSurfaces/Delta_prime_raw" +h5path = "SingularSurfaces/Delta_prime_raw_freeboundary" type = "complex_matrix" extract = "all_complex" label = "delta prime (raw side-major)" noise_threshold = 1e-8 order = 11 -[quantities.delta_coil] -h5path = "SingularSurfaces/Delta_coil" +# Fixed-boundary (conformal wall on the plasma) PEST-3 Δ′ diagonal +[quantities.delta_prime_fixedboundary_diag] +h5path = "SingularSurfaces/Delta_prime_matrix_fixedboundary" +type = "complex_matrix" +extract = "diagonal_complex" +label = "delta prime fixed boundary (BVP diagonal)" +noise_threshold = 1e-8 +order = 13 + +[quantities.delta_ef] +h5path = "SingularSurfaces/Delta_EF" type = "complex_matrix" extract = "all_complex" -label = "edge coil response delta_coil" +label = "edge coil response delta_ef" noise_threshold = 1e-8 order = 12 diff --git a/regression-harness/cases/gal_resistive_diiid.toml b/regression-harness/cases/gal_resistive_diiid.toml index 691b9c949b..8b8dceecd7 100644 --- a/regression-harness/cases/gal_resistive_diiid.toml +++ b/regression-harness/cases/gal_resistive_diiid.toml @@ -1,12 +1,12 @@ # Regression case: DIII-D-like n=1 outer-region singular Galerkin Δ′ solve. # Tracks the resonant-surface inventory, the PEST-3 Δ matching-matrix diagonal # (the physics-meaningful tearing Δ′), norms of the full outer Δ′ matrix and the -# rpec coil-response (Δ_coil) block, and the inner-layer matching outputs. +# error-field (Δ_EF) block, and the inner-layer matching outputs. # Each [quantities.*] block names an HDF5 path in the run output, how to extract it, # and the noise floor below which a difference is treated as zero. [case] name = "gal_resistive_diiid" -description = "DIII-D-like, n=1, RDCON outer-region Galerkin Δ′ with rpec coil columns (delta_coil)" +description = "DIII-D-like, n=1, RDCON outer-region Galerkin Δ′ with error-field (EF) columns (Delta_EF)" example_dir = "examples/DIIID-like_gal_resistive_example" # Number of resonant surfaces in the gal domain @@ -37,19 +37,28 @@ order = 20 # Raw outer Δ′ matrix (2·msing × 2·msing) — Frobenius norm catches any element drift [quantities.gal_delta_norm] -h5path = "SingularSurfaces/Delta_prime_raw" +h5path = "SingularSurfaces/Delta_prime_raw_freeboundary" type = "complex_matrix" extract = "norm" label = "||gal Δ′ matrix||" noise_threshold = 1e-6 order = 21 -# rpec coil-response block (edge mode × surface-side) — Frobenius norm -[quantities.gal_delta_coil_norm] -h5path = "SingularSurfaces/Delta_coil" +# Fixed-boundary (conformal wall on the plasma) PEST-3 Δ′ diagonal +[quantities.gal_pest3_delta_fixedboundary_diag] +h5path = "SingularSurfaces/Delta_prime_matrix_fixedboundary" +type = "complex_matrix" +extract = "diagonal_complex" +label = "gal PEST3 Δ diagonal, fixed boundary" +noise_threshold = 1e-6 +order = 24 + +# error-field (Δ_EF) block (edge mode × surface-side) — Frobenius norm +[quantities.gal_delta_ef_norm] +h5path = "SingularSurfaces/Delta_EF" type = "complex_matrix" extract = "norm" -label = "||gal Δ_coil block||" +label = "||gal Δ_EF block||" noise_threshold = 1e-6 order = 22 @@ -85,7 +94,7 @@ label = "||gal inner-layer Δ||" noise_threshold = 1e-6 order = 41 -# Outer-region matched coefficients cout (2·msing × mcoil) — the 4·msing matching assembly + solve. +# Outer-region matched coefficients cout (2·msing × nef) — the 4·msing matching assembly + solve. [quantities.gal_match_cout_norm] h5path = "SingularSurfaces/Match/cout" type = "complex_matrix" @@ -94,7 +103,7 @@ label = "||gal match cout||" noise_threshold = 1e-6 order = 42 -# Penetrated resonant field at each layer center (msing × mcoil) — the headline matching output. +# Penetrated resonant field at each layer center (msing × nef) — the headline matching output. [quantities.gal_match_bpen_norm] h5path = "SingularSurfaces/Match/bpen" type = "complex_matrix" diff --git a/src/Deck.jl b/src/Deck.jl index ea0f4b17ce..1a91b0a005 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -32,13 +32,14 @@ const _MOVED_KEYS = Dict{String,Dict{String,String}}( "extended_precision_bvp" => "moved to [Riccati]", "nchunks" => "moved to [Riccati]", "gal_match_flag" => "add a [Match] section to match the inner layer", - "gal_ideal_flag" => "moved to [Match] as ideal", + "gal_ideal_flag" => "removed: a Galerkin solve with [Galerkin] error_field_response = true is the ideal solution", "gal_inner_solver" => "moved to [GGJ] as solver", (k => "moved to the integrator's section, [Forward] or [Riccati]" for k in _ODE_DECK_KEYS)..., ("gal_$k" => "moved to [Match] as $k" for k in ("eta", "rho", "rotation", "gamma"))..., ("gal_inner_$k" => "moved to [GGJ] as $k" for k in ("xfac", "nx", "nq", "cutoff", "kmax"))..., ("gal_$k" => "moved to [Galerkin] as $k" for k in ("nx", "nq", "pfac", "dx0", "dx1", "dx2", "cutoff", "tol", "gnstep", - "dx1dx2_flag", "rpec_flag", "edge_onesided"))..., + "dx1dx2_flag", "edge_onesided"))..., + "gal_rpec_flag" => "moved to [Galerkin] as error_field_response", "gal_sing_order_ceiling" => "moved to [Galerkin] as frobenius_order_ceiling"), "LocalStability" => Dict{String,String}( k => "moved to [Ballooning]" for k in ("ode_tol", "n_scan", "max_alpha_scale", "alpha_tol", "psi_window")), @@ -344,7 +345,7 @@ end """ function match_from_deck(inputs::AbstractDict) haskey(inputs, "Match") || return nothing - fields = Dict{Symbol,Any}(:eta => Any, :rho => Any, :rotation => Any, :gamma => Any, :ideal => Bool, :inner_model => String) + fields = Dict{Symbol,Any}(:eta => Any, :rho => Any, :rotation => Any, :gamma => Any, :inner_model => String) problem = section_keywords(inputs["Match"], "Match", fields) _selector(inputs["Match"], "Match", "inner_model", ("GGJ",), "GGJ") delete!(problem, :inner_model) @@ -467,8 +468,8 @@ function parse_deck(inputs::AbstractDict, path::AbstractString) if match !== nothing (; keywords, algorithm) = force_balance first(keywords[:nn]) == last(keywords[:nn]) || error("[Match] is single-n: set [ForceFreeStates] nn to one toroidal mode number") - (algorithm isa Galerkin && algorithm.rpec_flag) || (algorithm isa Riccati && get(keywords, :vac_flag, false)) || - error("[Match] needs Δ′: use integrator = \"Galerkin\" with [Galerkin] rpec_flag = true, or \"Riccati\" with vac_flag = true") + hasproperty(algorithm, :error_field_response) && algorithm.error_field_response || + error("[Match] needs Δ_EF: use the \"Galerkin\" or \"Riccati\" integrator with error_field_response = true") end tearing = tearing_from_deck(inputs) perturbed_equilibrium = perturbed_equilibrium_from_deck(inputs) diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 1cb794f65c..325251ff6f 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -60,25 +60,12 @@ Solve-time scratch state for a force-balance solve: the resolved mode space, sin wall_settings::Union{Nothing,Vacuum.WallSettings} = nothing verbose::Bool = false """ - Inter-surface Δ' matrix, `msing × msing`, PEST3 convention: the odd-parity projection of - `delta_prime_raw`, set by `compute_delta_prime_matrix!` (Riccati path only). + Riccati Δ' BVP results (`compute_delta_prime_matrix!`): raw side-major `2msing × 2msing` D' with the vacuum edge + and with ξ(edge) = 0, and Δ_EF (`2msing × numpert_total`). Empty when not computed. """ - delta_prime_matrix::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) - - """ - Edge coil-response matrix, `2msing × numpert_total`: column k is the resonant small-solution - response at each surface side to a unit source on edge mode k (Eq. 37 rpec edge condition, - `_solve_bvp_edge_coil`). Empty unless the S-axis vacuum-edge BVP was assembled. - """ - delta_coil::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) - - """ - Raw `2msing × 2msing` outer-region matching matrix D' (Pletzer–Dewar 1991, before parity - rotation), side-major ordering `[L_s1, R_s1, …, L_sm, R_sm]`. `pest3_decompose` recovers the - A', B', Γ', Δ' blocks. No ½ prefactor (matches Fortran rdcon; the paper applies ½). - Empty unless the Riccati integrator was used. - """ - delta_prime_raw::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) + delta_prime_raw_freeboundary::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) + delta_prime_raw_fixedboundary::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) + delta_ef::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) end """ @@ -124,7 +111,7 @@ Physical and workflow controls for a force-balance solve, together with its sele """ @kwdef struct ForceFreeStatesControl{A<:AbstractIntegrator} algorithm::A = Riccati() - vac_flag::Bool = false + vac_flag::Bool = true mtheta_vacuum::Int = 480 nzeta_vacuum::Int = 1 nn_low::Int = 0 diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index d407000592..e4fb180832 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -135,7 +135,7 @@ OdeState(numpert_total::Int, numsteps_init::Int, numunorms_init::Int, msing::Int **Stub, not physically valid.** Per-surface Δ' estimate `(ca_r[i,i,2,s] - ca_l[i,i,2,s]) / (4π²·psio)` from the asymptotic coefficients. It ignores inter-surface coupling and the vacuum, so it does not -agree with the physical `ForceFreeStatesInternal.delta_prime_matrix`. Used only by tests. +agree with the physical the BVP Δ' (`DeltaPrimeData`). Used only by tests. """ function compute_delta_prime_from_ca!(odet::OdeState, intr::ForceFreeStatesInternal, equil::Equilibrium.PlasmaEquilibrium) denom = (2π)^2 * equil.psio # = twopi * chi1 in SingularCoupling.jl diff --git a/src/ForceFreeStates/Free.jl b/src/ForceFreeStates/Free.jl index 0d971fa07f..7625389715 100644 --- a/src/ForceFreeStates/Free.jl +++ b/src/ForceFreeStates/Free.jl @@ -87,7 +87,7 @@ downstream code consumes the stored ξ profiles. end """ - compute_scaled_wv(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) -> (wv, vac) + compute_scaled_wv(ctrl, equil, modes) -> (wv, vac) Vacuum response matrix at the control surface `intr.psilim`, scaled by the singular factors `(m - n·q)(m' - n'·q)` [Chance Phys. Plasmas 1997 2161 eq. 126]. Handles 2D single-n, 2D @@ -98,7 +98,7 @@ share it. Returns the scaled `wv` alongside the full vacuum response `vac`, whos point clouds the free-boundary result carries to HDF5. `wv` aliases `vac.wv`, which is scaled in place. """ -function compute_scaled_wv(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) +function compute_scaled_wv(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ModeSpace) (; mlow, mhigh, nlow, nhigh, psilim, qlim, wall_settings) = intr vac_inputs = Vacuum.VacuumInput(equil, psilim, ctrl.mtheta_vacuum, ctrl.nzeta_vacuum, mlow:mhigh, nlow:nhigh) vac = Vacuum.compute_vacuum_response(vac_inputs, wall_settings) @@ -109,16 +109,18 @@ function compute_scaled_wv(ctrl::ForceFreeStatesControl, equil::Equilibrium.Plas end """ - free_run(odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) -> FreeBoundaryResult + free_run(wp, ctrl, equil, mats, modes) -> FreeBoundaryResult -Free-boundary energies at `intr.psilim`: the plasma response from the ODE edge state plus the -singfac-scaled vacuum matrix, diagonalized as the pencil (W, N). Returns the eigenmodes and their -plasma/vacuum/total energies as a [`FreeBoundaryResult`](@ref). +Free-boundary energies and eigenmodes of `W = wp + wv` at `modes.psilim`, for a plasma energy matrix `wp` +(Hermitian or not) and the singfac-scaled vacuum matrix `wv` of `ctrl`'s wall. """ -@with_pool pool function free_run(odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) +@with_pool pool function free_run(wp::Matrix{ComplexF64}, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, + mats::MatrixSplines, modes::ModeSpace; verbose::Bool=false) + + wv, vac = compute_scaled_wv(ctrl, equil, modes) # Initializations and allocations - (; mpert, numpert_total, psilim, npert) = intr + (; mpert, numpert_total, psilim, npert) = modes wpt = zeros!(pool, ComplexF64, numpert_total, numpert_total) wvt = zeros!(pool, ComplexF64, numpert_total, numpert_total) tmp_mat = zeros!(pool, ComplexF64, numpert_total, numpert_total) @@ -126,12 +128,6 @@ plasma/vacuum/total energies as a [`FreeBoundaryResult`](@ref). # Evaluate dV/dpsi at the plasma edge dV_dpsi = equil.profiles.dVdpsi_spline(psilim) - # Compute plasma response matrix W = U₂ * U₁⁻¹ - wp = zeros(ComplexF64, numpert_total, numpert_total) - @views wp .= (odet.u[:, :, 2] / odet.u[:, :, 1]) ./ equil.psio^2 - - wv, vac = compute_scaled_wv(ctrl, equil, intr) - # Power-normalization matrix N at the plasma edge: ξ†·N·ξ = ⟨|ξ|²⟩ (see power_norm_matrix!). # The Jacobian band is evaluated at psilim (same surface as W), not at the last grid surface. Nmat = zeros!(pool, ComplexF64, numpert_total, numpert_total) @@ -187,7 +183,7 @@ plasma/vacuum/total energies as a [`FreeBoundaryResult`](@ref). ev = diag(wvt) # Write energies to screen - if intr.verbose + if verbose @info "Least Stable Eigenmode Energies:\n" * " Plasma = $((@sprintf "%+.3e %+.3ei" real(ep[1]) imag(ep[1])))\n" * " Vacuum = $((@sprintf "%+.3e %+.3ei" real(ev[1]) imag(ev[1])))\n" * diff --git a/src/ForceFreeStates/Galerkin/GalerkinAssembly.jl b/src/ForceFreeStates/Galerkin/GalerkinAssembly.jl index 55d0931940..5c453a1c89 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinAssembly.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinAssembly.jl @@ -409,21 +409,20 @@ function gal_assemble_rhs!(ws::GalWorkspace, mpert::Int) end """ - gal_set_boundary!(ws, mpert, wv_edge) + gal_set_boundary!(ws, mpert, wv_edge; nef=ws.nsol - 2msing) Apply the axis (`u(0)=0` identity) and edge boundary conditions to the boundary cells' `mat`, plus the -rpec coil-source RHS injection, before global assembly. Port of `gal_set_boundary` (gal.f). The edge +error-field (EF) source RHS injection, before global assembly. Port of `gal_set_boundary` (gal.f). The edge branch is one of: - - rpec (`ncoil = ws.nsol - 2*msing > 0`): identity edge and a unit source at the edge value DOF of coil + - EF columns (`nef > 0`, `error_field_response`): identity edge and a unit source at the edge value DOF of EF column `2*msing+ipert` for each poloidal mode `ipert`. `gal_assemble_rhs!` only fills columns `1:2*msing`, so the injection is not clobbered. - free boundary (`wv_edge !== nothing`): add the vacuum block `wvac·psio²` at the edge value DOF. - fixed boundary (else): identity edge. """ -function gal_set_boundary!(ws::GalWorkspace, mpert::Int, wv_edge::Union{Nothing,Matrix{ComplexF64}}) +function gal_set_boundary!(ws::GalWorkspace, mpert::Int, wv_edge::Union{Nothing,Matrix{ComplexF64}}; nef::Int=ws.nsol - 2 * (length(ws.intvl) - 1)) msing = length(ws.intvl) - 1 - ncoil = ws.nsol - 2 * msing # axis u(0): first cell of interval 0, Hermite value DOF ip=0 (Julia index 1) cell = ws.intvl[1].cells[1] @@ -434,8 +433,8 @@ function gal_set_boundary!(ws::GalWorkspace, mpert::Int, wv_edge::Union{Nothing, # edge u(1): last cell of last interval, edge-value DOF ip=3 (Julia index 4, see gauss_quad swap) cell = ws.intvl[msing+1].cells[ws.nx] - if ncoil > 0 - # rpec: identity edge + unit coil sources (gal.f) + if nef > 0 + # EF columns: identity edge + unit EF sources (gal.f) cell.mat[:, :, 4, :] .= 0 for idx in 1:mpert cell.mat[idx, idx, 4, 4] = 1 diff --git a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl index 5d4f6d2df5..d03e977d76 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl @@ -1,20 +1,21 @@ # GalerkinSolve.jl # # Top-level driver for the RDCON outer-region singular Galerkin Δ′ solve, plus the per-cell assembly -# orchestration, the banded solve, Δ′ extraction, PEST-3 blocks, and HDF5 output. -# Ports gal_make_arrays (gal.f), gal_solve (gal.f), and gal_write_pest3_data +# orchestration, the banded solve, Δ′ extraction, and HDF5 output. Ports gal_make_arrays and gal_solve # (gal.f). Inner-layer matching is applied afterwards by MatchProblem. """ - gal_make_arrays!(ws, ctrl, equil, mats, intr, asymps, sings, nn, wv_edge) + gal_make_arrays!(ws, ctrl, equil, mats, intr, asymps, sings, nn) -Assemble the global banded matrix and RHS. For each cell: Gauss-Lobatto Hermite stiffness -(`gal_gauss_quad!`), then the resonant (`gal_resonant!`) or extension (`gal_extension!`) contributions; -then the boundary conditions and the scatter into `ws.mat`/`ws.rhs`. Port of `gal_make_arrays`. +Assemble the global banded matrix and RHS with the fixed edge (plus the EF sources): per-cell stiffness and +resonant/extension contributions, the boundary conditions, and the scatter into `ws.mat`/`ws.rhs`. Port of +`gal_make_arrays`. + +Returns the edge cell's stiffness before the boundary conditions, `(mpert, mpert, np+1, np+1)`. """ function gal_make_arrays!(ws::GalWorkspace, ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines, intr::ForceFreeStatesInternal, asymps::Vector{GalSingAsymp}, sings::Vector{SingType}, - nn::Int, wv_edge::Union{Nothing,Matrix{ComplexF64}}) + nn::Int) mpert = intr.numpert_total msing = length(ws.intvl) - 1 @@ -33,17 +34,61 @@ function gal_make_arrays!(ws::GalWorkspace, ctrl::ForceFreeStatesControl, equil, end end - gal_set_boundary!(ws, mpert, wv_edge) + edge_mat = copy(ws.intvl[msing+1].cells[ws.nx].mat) + gal_set_boundary!(ws, mpert, nothing) gal_assemble_mat!(ws, mpert) gal_assemble_rhs!(ws, mpert) - return ws + return edge_mat +end + +""" + gal_vacuum_edge_solve(ws, edge_mat, wv_edge, mpert) -> Matrix{ComplexF64} + +Solve the 2·msing big-solution columns of an assembled workspace again with the vacuum edge `wv_edge` +instead of the fixed edge, restoring the edge cell from `edge_mat`. Returns the `(ndim, 2msing)` +solution, which gives the free-boundary Δ′. +""" +function gal_vacuum_edge_solve(ws::GalWorkspace, edge_mat::Array{ComplexF64,4}, wv_edge::Matrix{ComplexF64}, mpert::Int) + msing = length(ws.intvl) - 1 + ws.intvl[msing+1].cells[ws.nx].mat .= edge_mat + gal_set_boundary!(ws, mpert, wv_edge; nef=0) + fill!(ws.mat, 0) + gal_assemble_mat!(ws, mpert) + sol = ws.rhs[:, 1:(2msing)] + gal_banded_solve!(ws.mat, sol, ws.kl, ws.ku, "auto") + return sol +end + +""" + gal_small_coefficients(ws, sol) -> Matrix{ComplexF64} + +Small-solution coefficients of the columns of `sol`, `(ncol, 2msing)`, surface sides in side-major order. +""" +function gal_small_coefficients(ws::GalWorkspace, sol::AbstractMatrix{ComplexF64}) + rows = [cell.emap for intvl in ws.intvl for cell in intvl.cells if cell.etype == GCT_RES] + return permutedims(sol[rows, :]) +end + +""" + gal_edge_response(edge_rows, edge_map, sol) -> Matrix{ComplexF64} + +Edge momentum FΞ′ + KΞ, `(mpert, nsol)`, of each column of `sol`, from the unconstrained edge rows +`edge_rows` of the edge cell mapped by `edge_map`. On the columns with `ξ(edge) = eⱼ` it is `W_P·ψ₀²` +[Glasser 2016 PoP 23 072505, Eq. 66]. +""" +function gal_edge_response(edge_rows::Array{ComplexF64,3}, edge_map::Matrix{Int}, sol::Matrix{ComplexF64}) + force = zeros(ComplexF64, size(edge_rows, 1), size(sol, 2)) + for jp in axes(edge_rows, 3) + mul!(force, @view(edge_rows[:, :, jp]), @view(sol[edge_map[:, jp], :]), true, true) + end + return force end """ Empty `GalerkinResult` for a domain with no resonant surfaces. """ function empty_galerkin_result() - return GalerkinResult(0, Float64[], Float64[], Int[], Int[], Float64[], ComplexF64[], nothing, "none") + return GalerkinResult(0, Float64[], Float64[], Int[], Int[], Float64[], ComplexF64[], nothing, "none", Matrix{ComplexF64}(undef, 0, 0)) end """ @@ -55,9 +100,9 @@ Compute the outer-region Δ′ matching matrix by the singular Galerkin method. `GalerkinResult` alongside the Δ′ payload as the shared [`DeltaPrimeData`](@ref); if there are no resonant surfaces in the domain it returns an empty result and `nothing`. -`wv` is the vacuum energy matrix from `free_run`, which supplies the free-boundary edge term -`wv_edge = wv · psio²`; pass `nothing` for a fixed-boundary edge. `cut_solution` also keeps the -cut solution, for a later `MatchProblem`'s composite inner profiles. +The fixed-boundary Δ′ is always computed; `wv`, the singfac-scaled vacuum matrix, adds the free-boundary +Δ′ unless `free_boundary_delta_prime` is off. `cut_solution` also keeps the cut solution, for a later +`MatchProblem`'s composite inner profiles. """ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines, intr::ForceFreeStatesInternal; wv=nothing, cut_solution::Bool=false) @@ -99,10 +144,10 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines kl = mpert * (np + 1) ku = kl ldab = 2kl + ku + 1 - # rpec_flag (RDCON, gal.f): append mpert coil-response columns. Each is a unit source at - # the edge value DOF in one poloidal mode; the recorded plasma response is the coil block of Δ_gw. - ncoil = ctrl.algorithm.rpec_flag ? mpert : 0 - nsol = 2 * msing + ncoil + # error_field_response (RDCON rpec_flag, gal.f): append mpert error-field (EF) columns, each a unit edge displacement in one + # poloidal mode with no big-solution drive; their small coefficients are the Δ_EF block. + nef = ctrl.algorithm.error_field_response ? mpert : 0 + nsol = 2 * msing + nef intvl = [GalInterval(zeros(Float64, nx + 1), zeros(Float64, nx + 1), [GalCell(mpert) for _ in 1:nx]) for _ in 0:msing] ws = GalWorkspace("auto", nx, ctrl.algorithm.nq, np, 0, kl, ku, ldab, nsol, @@ -117,15 +162,7 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines ws.rhs = zeros(ComplexF64, ws.ndim, nsol) ws.sol = zeros(ComplexF64, ws.ndim, nsol) - # Free-boundary edge term wvac·psio² (wv is already singfac-scaled at qlim in free_run). - # rpec passes wv_edge=nothing; gal_set_boundary! then applies the identity edge AND injects the coil - # unit sources (its three-way branch). The vacuum block is only built for the non-rpec free case. - wv_edge = nothing - if ctrl.vac_flag && wv !== nothing && ncoil == 0 - wv_edge = Matrix{ComplexF64}(wv .* equil.psio^2) - end - - gal_make_arrays!(ws, ctrl, equil, mats, intr, asymps, sings, nn, wv_edge) + edge_mat = gal_make_arrays!(ws, ctrl, equil, mats, intr, asymps, sings, nn) if intr.verbose offdbg = ws.kl + ws.ku + 1 @@ -143,43 +180,37 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines ws.sol .= ws.rhs ws.solver = gal_banded_solve!(ws.mat, ws.sol, ws.kl, ws.ku, "auto") intr.verbose && @info "Galerkin banded solve: $(ws.solver)" + edge_response = gal_edge_response(edge_mat[:, :, 4, :], ws.intvl[msing+1].cells[ws.nx].map, ws.sol) # --- extract Δ′ from the small resonant coefficients (gal.f) --- - delta = zeros(ComplexF64, nsol, 2 * msing) - jsol = 0 - for ising in 0:msing - for cell in ws.intvl[ising+1].cells - if cell.etype == GCT_RES - jsol += 1 - @views delta[:, jsol] .= ws.sol[cell.emap, :] - end - end - end - - Ap, Bp, Gammap, Deltap = gal_pest3_blocks(delta, msing) + delta = gal_small_coefficients(ws, ws.sol) # Mercier index D_I = -Re(α²). α is the half-separation of the resonant exponents. di = [real(-asymps[i].right.alpha[1]^2) for i in 1:msing] alpha = [asymps[i].right.alpha[1] for i in 1:msing] - # Pack the Δ′ payload in the shared layout: the raw D′ is the leading 2msing×2msing side-major - # block, and the coil-response rows 2*msing+1 : 2*msing+mpert (rpec_flag) transpose into the - # (surface-side × edge mode) orientation the Riccati BVP also produces. - dp_raw = delta[1:(2*msing), 1:(2*msing)] - dp_coil = ncoil > 0 ? permutedims(delta[(2*msing+1):(2*msing+ncoil), :]) : Matrix{ComplexF64}(undef, 0, 0) - dp = DeltaPrimeData(Deltap, dp_raw, dp_coil, Ap, Bp, Gammap) - # Reconstruct ξ(ψ) AND analytic ξ′(ψ) on the gal-native grid (gal_output_solution); the cut # solution only when a later match needs the composite inner profiles. intr.verbose && @info "Reconstructing outer-region ξ and analytic ξ′ on the gal grid" solution = gal_output_solution(ws, asymps, sings, intr, equil.profiles, psihigh; delta=(cut_solution ? delta : nothing)) + # The fixed-edge solve gives the fixed-boundary D′ and, in the (surface-side × edge mode) orientation, Δ_EF. + # The free-boundary D′ comes from re-solving the big-solution columns with the vacuum edge. + raw_fixed = delta[1:(2msing), :] + ef = nef > 0 ? permutedims(delta[(2msing+1):end, :]) : Matrix{ComplexF64}(undef, 0, 0) + raw_free = Matrix{ComplexF64}(undef, 0, 0) + if ctrl.vac_flag && wv !== nothing && ctrl.algorithm.free_boundary_delta_prime + # wv is singfac-scaled at qlim; the Galerkin edge term is wv·ψ₀². + raw_free = gal_small_coefficients(ws, gal_vacuum_edge_solve(ws, edge_mat, Matrix{ComplexF64}(wv .* equil.psio^2), mpert)) + end + dp = DeltaPrimeData(raw_free, raw_fixed, ef) + sing_psi = [s.psifac for s in sings] sing_q = [s.q for s in sings] sing_m = [s.m[1] for s in sings] sing_n = [s.n[1] for s in sings] - return GalerkinResult(msing, sing_psi, sing_q, sing_m, sing_n, di, alpha, solution, ws.solver), dp + return GalerkinResult(msing, sing_psi, sing_q, sing_m, sing_n, di, alpha, solution, ws.solver, edge_response), dp end """ @@ -204,30 +235,6 @@ function gal_scaled_lu_solve!(mat::Matrix{ComplexF64}, sol::AbstractVecOrMat{Com return sol end -""" - gal_pest3_blocks(delta, msing) -> (Ap, Bp, Gammap, Deltap) - -PEST-3 matching blocks (each `msing×msing`) as ± combinations of the left/right Δ′ entries. Port of -`gal_write_pest3_data`. Row index `2i-1`/`2i` = left/right of surface `i`. -""" -function gal_pest3_blocks(delta::Matrix{ComplexF64}, msing::Int) - Ap = zeros(ComplexF64, msing, msing) - Bp = zeros(ComplexF64, msing, msing) - Gammap = zeros(ComplexF64, msing, msing) - Deltap = zeros(ComplexF64, msing, msing) - for i in 1:msing, j in 1:msing - d11 = delta[2i-1, 2j-1] - d12 = delta[2i-1, 2j] - d21 = delta[2i, 2j-1] - d22 = delta[2i, 2j] - Ap[i, j] = d22 + d21 + d12 + d11 - Bp[i, j] = d22 - d21 + d12 - d11 - Gammap[i, j] = d22 + d21 - d12 - d11 - Deltap[i, j] = d22 - d21 - d12 + d11 - end - return Ap, Bp, Gammap, Deltap -end - """ write_galerkin!(out_h5, result::GalerkinResult; basis_output=false) @@ -350,7 +357,7 @@ end gal_cholesky_solve!(mat, sol, kl, ku) -> Bool Banded Cholesky solve of the full-band system `mat`, leaving `mat` untouched. Rows that are -identity rows (Dirichlet DOFs: axis, fixed or coil edge) have their columns moved to the +identity rows (Dirichlet DOFs: axis, fixed or EF edge) have their columns moved to the right-hand side. The free block's off-diagonal entries must agree with their conjugate partners within `1e-10 * sqrt(abs(A_ii)) * sqrt(abs(A_jj))`. Cholesky uses the lower band and deliberately projects the diagonal onto its real part. Returns `false`, with `sol` diff --git a/src/ForceFreeStates/Galerkin/GalerkinStructs.jl b/src/ForceFreeStates/Galerkin/GalerkinStructs.jl index e0cb88afc9..db0c31fc82 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinStructs.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinStructs.jl @@ -150,6 +150,8 @@ Solver internals and FEM diagnostics of the outer-region Galerkin solve. The Δ - `solution::Union{Nothing,GalerkinSolution}` — reconstructed radial ξ(ψ) and analytic ξ′(ψ) on the gal-native grid; `nothing` if no resonant surfaces. - `solver::String` — factorization actually used: `"cholesky"`, `"LU"`, or `"none"` when no resonant surfaces were present. + - `edge_response::Matrix{ComplexF64}` — `(mpert, nsol)` edge momentum FΞ′ + KΞ of every solution column + (`gal_edge_response`); the EF columns give `W_P·ψ₀²`. Empty if no resonant surfaces. """ struct GalerkinResult msing::Int @@ -161,4 +163,5 @@ struct GalerkinResult alpha::Vector{ComplexF64} solution::Union{Nothing,GalerkinSolution} solver::String + edge_response::Matrix{ComplexF64} end diff --git a/src/ForceFreeStates/Integrators.jl b/src/ForceFreeStates/Integrators.jl index 8210f4f8cc..e6cd24f3bb 100644 --- a/src/ForceFreeStates/Integrators.jl +++ b/src/ForceFreeStates/Integrators.jl @@ -41,6 +41,8 @@ Chunked Riccati integration and the singular-surface boundary-value solve. - `save_interval::Int` - Save every Nth ODE step; always retain steps near rational surfaces. - `nchunks::Int` - Target chunk count; zero derives the count from the singular surfaces. - `extended_precision_bvp::Bool` - Use Complex{Double64} for the Delta-prime BVP and PEST3 combination to reduce cancellation error. + - `error_field_response::Bool` - Compute `Delta_EF`, the response to a unit edge displacement per mode (needs `vac_flag`). + Required by `MatchProblem`. """ @kwdef struct Riccati <: AbstractIntegrator eulerlagrange_tolerance::Float64 = 1e-8 @@ -50,6 +52,7 @@ Chunked Riccati integration and the singular-surface boundary-value solve. save_interval::Int = 1 nchunks::Int = 0 extended_precision_bvp::Bool = true + error_field_response::Bool = true end """ @@ -73,7 +76,10 @@ corresponding discretization setting. Factorization is selected automatically. - `gnstep::Int` - Maximum resonant-quadrature evaluations. - `dx1dx2_flag::Bool` - Enable the special dx1/dx2 treatment of resonant and extension elements. - `frobenius_order_ceiling::Bool` - Auto-raise the order per surface for a high Mercier index. - - `rpec_flag::Bool` - Append the mpert coil-response columns to the Δ′ solve. Required for a later `MatchProblem` solve on the result. + - `error_field_response::Bool` - Add the error-field (EF) columns, a unit edge displacement per mode: gives `Delta_EF`, the ideal solution + and `wp`. Required by `MatchProblem`. + - `free_boundary_delta_prime::Bool` - With `error_field_response` and `vac_flag`, compute the free-boundary (tearing) Δ′ by a second solve + (about a quarter of the solve time). Off: no tearing Δ′. - `edge_onesided::Bool` - Pack the two end intervals one-sided toward their single rational end instead of the Fortran symmetric pack. - `basis_output::Bool` - Save the raw Galerkin basis for development diagnostics. - `cut_solution::Bool` - Also keep the cut solution, for a later `MatchProblem`'s composite inner profiles. @@ -90,7 +96,8 @@ corresponding discretization setting. Factorization is selected automatically. gnstep::Int = 20000 dx1dx2_flag::Bool = true frobenius_order_ceiling::Bool = true - rpec_flag::Bool = false + error_field_response::Bool = true + free_boundary_delta_prime::Bool = true edge_onesided::Bool = false cut_solution::Bool = false basis_output::Bool = false diff --git a/src/ForceFreeStates/Matching/DeltaPrime.jl b/src/ForceFreeStates/Matching/DeltaPrime.jl index 7358dceee5..9c594a613c 100644 --- a/src/ForceFreeStates/Matching/DeltaPrime.jl +++ b/src/ForceFreeStates/Matching/DeltaPrime.jl @@ -1,35 +1,64 @@ """ - DeltaPrimeData + PEST3Blocks -The solve's Δ′/outer-region matching payload, in the PEST-3 convention shared by the Riccati -boundary-value problem and the Galerkin solve, so consumers never branch on which integrator ran. +PEST-3 parity blocks of a raw D′ [Glasser-Kolemen 2018 PoP 25, 032501, Eq. 31], each (msing × msing). -Matrices are indexed by the surfaces the formalism solved across, core→edge: `result.surfaces` for -Riccati, its in-domain in-band subset for Galerkin (`gal_resonant_surfaces`). Side-major orderings -run `[L_s1, R_s1, L_s2, R_s2, …]`. +## Fields + + - `A` - Interchange↔interchange block. + - `B` - Interchange↔tearing block. + - `Gamma` - Tearing↔interchange block. + - `Delta` - Tearing↔tearing block, the tearing Δ′. +""" +struct PEST3Blocks + A::Matrix{ComplexF64} + B::Matrix{ComplexF64} + Gamma::Matrix{ComplexF64} + Delta::Matrix{ComplexF64} +end + +""" + pest3_decompose(raw) -> PEST3Blocks + +PEST-3 parity blocks of the side-major raw D′ `raw` (2msing × 2msing). No Pletzer–Dewar ½ prefactor, as in +Fortran RDCON. +""" +function pest3_decompose(raw::AbstractMatrix{ComplexF64}) + m = size(raw, 1) ÷ 2 + size(raw) == (2m, 2m) || throw(ArgumentError("pest3_decompose: raw must be 2m × 2m, got $(size(raw))")) + LL = raw[1:2:end, 1:2:end] + LR = raw[1:2:end, 2:2:end] + RL = raw[2:2:end, 1:2:end] + RR = raw[2:2:end, 2:2:end] + return PEST3Blocks(RR + RL + LR + LL, RR - RL + LR - LL, RR + RL - LR - LL, RR - RL - LR + LL) +end + +""" + DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef) + +The solve's Δ′/outer-region matching payload. Matrices are indexed by the surfaces the formalism solved +across, core→edge; side-major orderings run `[L_s1, R_s1, L_s2, R_s2, …]`. An empty matrix (or `nothing`) +means the solve did not compute it. The PEST-3 blocks are built from the raw matrices. ## Fields - - `matrix::Matrix{ComplexF64}` - Inter-surface Δ′ of shape (msing × msing) in PEST3 - convention, the tearing↔tearing parity projection of `raw`. Same as `Delta` of the - PEST-3 block set. Both formalisms. - - `raw::Matrix{ComplexF64}` - Raw outer-region matching matrix D′ of shape - (2msing × 2msing), side-major on both axes. Both formalisms. - - `coil::Matrix{ComplexF64}` - Edge coil-response matrix of shape - (2msing × numpert_total); column k is the resonant small-solution response at each - surface side to a unit source on edge poloidal mode k. Riccati fills it from the - vacuum-edge BVP, Galerkin from its `rpec_flag` columns. Empty when neither ran. - - `A::Union{Nothing,Matrix{ComplexF64}}` - PEST-3 interchange↔interchange block - (msing × msing). Galerkin only; `nothing` for Riccati, which persists only `raw` and - recovers the blocks on demand via `pest3_decompose`. - - `B::Union{Nothing,Matrix{ComplexF64}}` - PEST-3 interchange↔tearing block; see `A`. - - `Gamma::Union{Nothing,Matrix{ComplexF64}}` - PEST-3 tearing↔interchange block; see `A`. + - `raw_freeboundary::Matrix{ComplexF64}` - Raw D′ (2msing × 2msing) with the vacuum (or wall) at the edge. + - `raw_fixedboundary::Matrix{ComplexF64}` - Raw D′ (2msing × 2msing) with ξ(edge) = 0, a conformal wall on the plasma. + - `ef::Matrix{ComplexF64}` - Error-field response Δ_EF (2msing × numpert_total): column k is the small-solution + coefficient at each surface side for a unit edge displacement in mode k with the edge otherwise fixed. It pairs + with `raw_fixedboundary` in matching. + - `freeboundary::Union{Nothing,PEST3Blocks}` - PEST-3 blocks of `raw_freeboundary`. + - `fixedboundary::Union{Nothing,PEST3Blocks}` - PEST-3 blocks of `raw_fixedboundary`. """ struct DeltaPrimeData - matrix::Matrix{ComplexF64} - raw::Matrix{ComplexF64} - coil::Matrix{ComplexF64} - A::Union{Nothing,Matrix{ComplexF64}} - B::Union{Nothing,Matrix{ComplexF64}} - Gamma::Union{Nothing,Matrix{ComplexF64}} + raw_freeboundary::Matrix{ComplexF64} + raw_fixedboundary::Matrix{ComplexF64} + ef::Matrix{ComplexF64} + freeboundary::Union{Nothing,PEST3Blocks} + fixedboundary::Union{Nothing,PEST3Blocks} end + +DeltaPrimeData(raw_freeboundary::AbstractMatrix, raw_fixedboundary::AbstractMatrix, ef::AbstractMatrix) = + DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef, + isempty(raw_freeboundary) ? nothing : pest3_decompose(raw_freeboundary), + isempty(raw_fixedboundary) ? nothing : pest3_decompose(raw_fixedboundary)) diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index f80f52eb46..76b5c18597 100644 --- a/src/ForceFreeStates/Matching/MatchProblem.jl +++ b/src/ForceFreeStates/Matching/MatchProblem.jl @@ -3,13 +3,13 @@ # Driven inner-layer matching on a finished solve (rmatch match_rpec + match_output_solution, match.f). """ - MatchProblem(ffs; eta=nothing, rho=nothing, rotation=nothing, gamma=5/3, ideal=false) + MatchProblem(ffs; eta=nothing, rho=nothing, rotation=nothing, gamma=5/3) Driven inner-layer matching on a finished force-free-states solve `ffs`: each rational surface is matched at the forced eigenvalue γ = 2πi·n·f, with f the plasma rotation frequency there. `solve(prob, GGJModel())` returns a copy of `ffs` with the matched solution and the penetrated -field `bpen`. `ffs` needs the Δ′ coil block, from `Galerkin(; rpec_flag=true)` or `Riccati()` -with `vac_flag=true`. +field `bpen`. `ffs` needs `Delta_EF`, from `Galerkin()` or `Riccati()` with `error_field_response` (Riccati +also needs `vac_flag`). # Keywords @@ -17,17 +17,16 @@ with `vac_flag=true`. in Hz, a scalar for every surface or one value per `ffs.surfaces` entry (core to edge). Each one not given comes from the equilibrium's kinetic data, as the tearing problem's do: η from [`InnerLayer.layer_eta`](@ref), ρ from [`InnerLayer.layer_rho`](@ref), and the - rotation f = Ω_E/2π from the E×B rotation of [`InnerLayer.layer_omega_E`](@ref). Unused - with `ideal=true`. + rotation f = Ω_E/2π from the E×B rotation of [`InnerLayer.layer_omega_E`](@ref). - `gamma`: ratio of specific heats. - - `ideal`: skip the inner layer and return the perfectly shielding solution. + +The perfectly shielding (ideal) solution needs no match: it is the Galerkin solve's own result. ## Fields - `ffs` - The outer solve being matched; held by reference, not copied. - `eta`, `rho`, `rotation` - Per-surface η in Ω·m, ρ in kg/m³ and rotation frequency in Hz, following `ffs.surfaces`. - `gamma` - Ratio of specific heats. - - `ideal` - Whether the inner layer is skipped. Ref: Fortran rmatch `match_rpec` (match.f). """ @@ -37,7 +36,6 @@ struct MatchProblem{R<:ForceFreeStatesResult} rho::Vector{Float64} rotation::Vector{Float64} gamma::Float64 - ideal::Bool end function MatchProblem( @@ -45,16 +43,15 @@ function MatchProblem( eta::Union{Nothing,Real,AbstractVector{<:Real}}=nothing, rho::Union{Nothing,Real,AbstractVector{<:Real}}=nothing, rotation::Union{Nothing,Real,AbstractVector{<:Real}}=nothing, - gamma::Real=5 / 3, - ideal::Bool=false + gamma::Real=5 / 3 ) ffs.npert == 1 || error("MatchProblem: matching is single-n; the result spans n = $(ffs.nlow):$(ffs.nhigh)") ffs.closure === :matched && error("MatchProblem: the result is already matched; pose the match on the outer solve") dp = ffs.delta_prime dp === nothing && - error("MatchProblem: the $(ffs.integrator) result has no Δ′; solve with Galerkin(; rpec_flag=true), or Riccati() with vac_flag=true") - isempty(dp.coil) && - error("MatchProblem: the Δ′ coil block is empty; solve with Galerkin(; rpec_flag=true), or Riccati() with vac_flag=true") + error("MatchProblem: the $(ffs.integrator) result has no Δ′; solve with Galerkin() or Riccati() (Riccati needs vac_flag=true)") + (isempty(dp.ef) || isempty(dp.raw_fixedboundary)) && + error("MatchProblem: needs Δ_EF and the fixed-boundary Δ′; solve with error_field_response=true (Riccati also needs vac_flag=true)") msing = length(ffs.surfaces) if ffs.galerkin !== nothing @@ -62,10 +59,9 @@ function MatchProblem( isempty(dropped) || error("MatchProblem: the Galerkin solve dropped the surfaces at ψ = $dropped (on the domain edge or " * "outside mlow:mhigh); matching needs every surface") end - size(dp.raw, 1) == 2msing || - error("MatchProblem: Δ′ raw block is $(size(dp.raw, 1))×$(size(dp.raw, 2)) but the result carries $msing surfaces") + size(dp.raw_fixedboundary, 1) == 2msing || + error("MatchProblem: Δ′ raw block is $(size(dp.raw_fixedboundary, 1))×$(size(dp.raw_fixedboundary, 2)) but the result carries $msing surfaces") - ideal && return MatchProblem(ffs, zeros(msing), zeros(msing), zeros(msing), Float64(gamma), true) InnerLayer._require_layer_inputs("MatchProblem", ffs.equil; eta, rho, rotation) eta === nothing && (eta = InnerLayer.layer_eta(ffs.equil, ffs.surfaces)) rho === nothing && (rho = InnerLayer.layer_rho(ffs.equil, ffs.surfaces)) @@ -78,7 +74,7 @@ function MatchProblem( v isa Real ? fill(Float64(v), msing) : length(v) == msing ? collect(Float64, v) : error("MatchProblem: $name has length $(length(v)), expected $msing (one per surface, core to edge)") - return MatchProblem(ffs, per_surface("eta", eta), per_surface("rho", rho), per_surface("rotation", rotation), Float64(gamma), false) + return MatchProblem(ffs, per_surface("eta", eta), per_surface("rho", rho), per_surface("rotation", rotation), Float64(gamma)) end """ @@ -94,16 +90,17 @@ closure_capable(::InnerLayer.SLAYERModel) = false """ solve(prob::MatchProblem, model) -> ForceFreeStatesResult -Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched` (`:ideal` -with `ideal=true`), `bpen`, the [`MatchResult`](@ref) in `result.match` and, for a Galerkin -solve, the matched ξ. A `:matched` result drops the ideal δW (`wp`, `free_boundary`), so -PerturbedEquilibrium skips its response rather than mixing ideal and matched physics. +Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched`, `bpen`, the +[`MatchResult`](@ref) in `result.match` and, for a Galerkin solve, the matched ξ, its edge response +`wp` (see [`ForceFreeStatesResult`](@ref)) and, when the solve had `vac_flag`, the free-boundary energies +of that response. A Riccati-fed match drops `wp` and `free_boundary`, so PerturbedEquilibrium refuses +it rather than mixing ideal and matched physics. """ function CommonSolve.solve(prob::MatchProblem, model::InnerLayer.InnerLayerModel) closure_capable(model) || error("$(nameof(typeof(model))) cannot solve a MatchProblem (use GGJModel(); SLAYERModel is for TearingProblem)") match = _compute_match(prob, model) - return _matched_result(prob.ffs, match, prob.ideal) + return _matched_result(prob.ffs, match) end # Inner-layer Δ per surface, the matching system, then the matched outer and inner profiles. @@ -112,88 +109,74 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) dp = ffs.delta_prime sings = ffs.surfaces msing = length(sings) - mcoil = size(dp.coil, 2) + nef = size(dp.ef, 2) nn = ffs.nlow equil = ffs.equil chi1 = 2π * equil.psio gal_sol = ffs.galerkin === nothing ? nothing : ffs.galerkin.solution - if prob.ideal - # Ideal limit (rmatch coil%ideal_flag): no inner layer, cout = 0. - cout = zeros(ComplexF64, 2msing, mcoil) - cin = zeros(ComplexF64, 2msing, mcoil) - deltar = zeros(ComplexF64, msing, 2) - bpen = zeros(ComplexF64, msing, mcoil) - inner_psi = Vector{Float64}[] - inner_xi = Matrix{ComplexF64}[] - inner_b = Matrix{ComplexF64}[] - inner_params = InnerLayer.GGJParameters[] - rpec_eig = zeros(ComplexF64, msing) - residual = 0.0 - else - # Inner-layer Δ and profiles per surface (match.f deltac_run, intotsol). - deltar = zeros(ComplexF64, msing, 2) - rpec_eig = zeros(ComplexF64, msing) - # Layer-center field weight per parity (match.f intotsol_b). - pen = zeros(ComplexF64, msing, 2) - inner_psi = Vector{Vector{Float64}}(undef, msing) # ψ_s ± X·dψdx, ascending - inner_odd = Vector{Vector{ComplexF64}}(undef, msing) # Ξ₋, odd about ψ_s - inner_even = Vector{Vector{ComplexF64}}(undef, msing) # Ξ₊, even - inner_bodd = Vector{Vector{ComplexF64}}(undef, msing) # b^ψ from Ψ₋, even - inner_beven = Vector{Vector{ComplexF64}}(undef, msing) # b^ψ from Ψ₊, odd - inner_params = Vector{InnerLayer.GGJParameters}(undef, msing) - profiles = true - for i in 1:msing - params = ggj_parameters(sings[i], equil; eta=prob.eta[i], rho=prob.rho[i], - gamma=prob.gamma, ising=i) - inner_params[i] = params - γ = 2π * im * nn * prob.rotation[i] # forced eigenvalue, f in Hz - rpec_eig[i] = γ - inner = InnerLayer.solve_inner_profile(model, params, γ) # parity columns (Δ₊, Δ₋) - deltar[i, 1] = inner.Δ[1] - deltar[i, 2] = inner.Δ[2] - profΨ, profΞ, xg = inner.Ψ, inner.Ξ, inner.x - resc = inner.rescale # inner big-branch amplitude → outer δψ normalization - # b_m = 2πi·χ₁·(m−nq)·ξ_m with m−nq = −n·q′·dψdx·X and Ψ = XΞ at leading order (GWP2016 Eqs. 16, 27; Ψ normalization Eq. A17) ⇒ b_m = scale·resc·Ψ. - scale = -2π * chi1 * im * nn * sings[i].q1 * inner.dψdx - pen[i, 1] = scale * profΨ[1, 1] * resc # X = 0, even parity (Ψ(0) = 0) - pen[i, 2] = scale * profΨ[1, 2] * resc # odd parity - # A backend returning only layer-center values (real-ψ profiles not requested) skips the inner profiles. - if length(xg) == 1 - profiles = false - continue - end - xvar = xg .* inner.dψdx # X → ψ distance - inner_psi[i] = vcat(reverse(sings[i].psifac .- xvar), sings[i].psifac .+ xvar) - inner_odd[i] = resc .* vcat(reverse(.-profΞ[:, 2]), profΞ[:, 2]) - inner_even[i] = resc .* vcat(reverse(profΞ[:, 1]), profΞ[:, 1]) - inner_bodd[i] = (scale * resc) .* vcat(reverse(profΨ[:, 2]), profΨ[:, 2]) - inner_beven[i] = (scale * resc) .* vcat(reverse(.-profΨ[:, 1]), profΨ[:, 1]) + # Inner-layer Δ and profiles per surface (match.f deltac_run, intotsol). + deltar = zeros(ComplexF64, msing, 2) + forced_eigenvalue = zeros(ComplexF64, msing) + # Layer-center field weight per parity (match.f intotsol_b). + pen = zeros(ComplexF64, msing, 2) + inner_psi = Vector{Vector{Float64}}(undef, msing) # ψ_s ± X·dψdx, ascending + inner_odd = Vector{Vector{ComplexF64}}(undef, msing) # Ξ₋, odd about ψ_s + inner_even = Vector{Vector{ComplexF64}}(undef, msing) # Ξ₊, even + inner_bodd = Vector{Vector{ComplexF64}}(undef, msing) # b^ψ from Ψ₋, even + inner_beven = Vector{Vector{ComplexF64}}(undef, msing) # b^ψ from Ψ₊, odd + inner_params = Vector{InnerLayer.GGJParameters}(undef, msing) + profiles = true + for i in 1:msing + params = ggj_parameters(sings[i], equil; eta=prob.eta[i], rho=prob.rho[i], + gamma=prob.gamma, ising=i) + inner_params[i] = params + γ = 2π * im * nn * prob.rotation[i] # forced eigenvalue, f in Hz + forced_eigenvalue[i] = γ + inner = InnerLayer.solve_inner_profile(model, params, γ) # parity columns (Δ₊, Δ₋) + deltar[i, 1] = inner.Δ[1] + deltar[i, 2] = inner.Δ[2] + profΨ, profΞ, xg = inner.Ψ, inner.Ξ, inner.x + resc = inner.rescale # inner big-branch amplitude → outer δψ normalization + # b_m = 2πi·χ₁·(m−nq)·ξ_m with m−nq = −n·q′·dψdx·X and Ψ = XΞ at leading order (GWP2016 Eqs. 16, 27; Ψ normalization Eq. A17) ⇒ b_m = scale·resc·Ψ. + scale = -2π * chi1 * im * nn * sings[i].q1 * inner.dψdx + pen[i, 1] = scale * profΨ[1, 1] * resc # X = 0, even parity (Ψ(0) = 0) + pen[i, 2] = scale * profΨ[1, 2] * resc # odd parity + # A backend returning only layer-center values (real-ψ profiles not requested) skips the inner profiles. + if length(xg) == 1 + profiles = false + continue end + xvar = xg .* inner.dψdx # X → ψ distance + inner_psi[i] = vcat(reverse(sings[i].psifac .- xvar), sings[i].psifac .+ xvar) + inner_odd[i] = resc .* vcat(reverse(.-profΞ[:, 2]), profΞ[:, 2]) + inner_even[i] = resc .* vcat(reverse(profΞ[:, 1]), profΞ[:, 1]) + inner_bodd[i] = (scale * resc) .* vcat(reverse(profΨ[:, 2]), profΨ[:, 2]) + inner_beven[i] = (scale * resc) .* vcat(reverse(.-profΨ[:, 1]), profΨ[:, 1]) + end - cout, cin, residual = _match_system(dp.raw, dp.coil, deltar) + cout, cin, residual = _match_system(dp.raw_fixedboundary, dp.ef, deltar) - # Penetrated field at each layer center (match.f intotsol_b); cin rows per surface are (d₊, d₋). - bpen = zeros(ComplexF64, msing, mcoil) - for i in 1:msing, j in 1:mcoil - bpen[i, j] = pen[i, 1] * cin[2i-1, j] + pen[i, 2] * cin[2i, j] - end + # Penetrated field at each layer center (match.f intotsol_b); cin rows per surface are (d₊, d₋). + bpen = zeros(ComplexF64, msing, nef) + for i in 1:msing, j in 1:nef + bpen[i, j] = pen[i, 1] * cin[2i-1, j] + pen[i, 2] * cin[2i, j] + end - # Matched inner ξ_ψ and b^ψ per coil: odd parity × cin[2i], even × cin[2i-1] (match.f intotsol). - if profiles - inner_xi = [inner_odd[i] * transpose(cin[2i, :]) .+ inner_even[i] * transpose(cin[2i-1, :]) for i in 1:msing] - inner_b = [inner_bodd[i] * transpose(cin[2i, :]) .+ inner_beven[i] * transpose(cin[2i-1, :]) for i in 1:msing] - else - inner_psi = Vector{Float64}[] - inner_xi = Matrix{ComplexF64}[] - inner_b = Matrix{ComplexF64}[] - end + # Matched inner ξ_ψ and b^ψ per EF column: odd parity × cin[2i], even × cin[2i-1] (match.f intotsol). + if profiles + inner_xi = [inner_odd[i] * transpose(cin[2i, :]) .+ inner_even[i] * transpose(cin[2i-1, :]) for i in 1:msing] + inner_b = [inner_bodd[i] * transpose(cin[2i, :]) .+ inner_beven[i] * transpose(cin[2i-1, :]) for i in 1:msing] + else + inner_psi = Vector{Float64}[] + inner_xi = Matrix{ComplexF64}[] + inner_b = Matrix{ComplexF64}[] end - reconnected_flux = Matrix{ComplexF64}(dp.coil .+ transpose(dp.raw) * cout) + reconnected_flux = Matrix{ComplexF64}(dp.ef .+ transpose(dp.raw_fixedboundary) * cout) - # Matched outer ξ per coil: coil column + Σ cout·plasma columns (needs the Galerkin basis). + # Matched outer ξ per EF column: EF column + Σ cout·plasma columns (needs the Galerkin basis). if gal_sol === nothing xi = Array{ComplexF64,3}(undef, 0, 0, 0) xi_deriv = Array{ComplexF64,3}(undef, 0, 0, 0) @@ -205,9 +188,9 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) sols_deriv = gal_sol.xi_deriv mpert = size(sols, 1) ngrid = size(sols, 2) - xi = zeros(ComplexF64, mpert, ngrid, mcoil) - xi_deriv = zeros(ComplexF64, mpert, ngrid, mcoil) - for j in 1:mcoil + xi = zeros(ComplexF64, mpert, ngrid, nef) + xi_deriv = zeros(ComplexF64, mpert, ngrid, nef) + for j in 1:nef csol = 2msing + j @views xi[:, :, j] .= sols[:, :, csol] @views xi_deriv[:, :, j] .= sols_deriv[:, :, csol] @@ -247,16 +230,16 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) inner_xi[i] = inner_xi[i][inside, :] inner_b[i] = inner_b[i][inside, :] - # Cut outer background of the resonant harmonic, per coil. - cutmn = Matrix{ComplexF64}(undef, length(psi_keep), mcoil) - for j in 1:mcoil + # Cut outer background of the resonant harmonic, per EF column. + cutmn = Matrix{ComplexF64}(undef, length(psi_keep), nef) + for j in 1:nef @views cutmn[:, j] .= sols_cut[ires, keep, 2msing+j] for isol in 1:2msing @views cutmn[:, j] .+= cout[isol, j] .* sols_cut[ires, keep, isol] end end itp = cubic_interp(psi_keep, Series(cutmn); extrap=ExtendExtrap()) - buf = Vector{ComplexF64}(undef, mcoil) + buf = Vector{ComplexF64}(undef, nef) hint = Ref(1) for (ip, psi_p) in enumerate(inner_psi[i]) itp(buf, psi_p; hint=hint) @@ -269,19 +252,24 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) end end - return MatchResult(cout, cin, deltar, rpec_eig, residual, bpen, reconnected_flux, + return MatchResult(cout, cin, deltar, forced_eigenvalue, residual, bpen, reconnected_flux, xi, xi_deriv, inner_psi, inner_xi, inner_b, inner_params, model, prob) end -# Copy of ffs with the match applied; the ideal reference keeps closure :ideal, its zero bpen and δW. -function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult, ideal::Bool) +# Copy of ffs with the match applied. A Galerkin match publishes the matched ξ, its edge response (the matched +# columns are EF + plasma·cout, so their edge response is too) and the free-boundary energies of that response with +# the solve's own vacuum. For Riccati match these remain TODO. +function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult) gal = ffs.galerkin - solution = (gal !== nothing && gal.solution !== nothing && !isempty(match.xi)) ? - _matched_gal_profiles(gal, match, ffs.mats, ffs) : ffs.solution - ideal && return _with(ffs; match=match, solution=solution) - # The ideal δW does not describe the matched plasma; PE gates on its absence. - return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, - wp=nothing, free_boundary=nothing) + solution = nothing + wp = nothing + free_boundary = nothing + if gal !== nothing && gal.solution !== nothing && !isempty(match.xi) + solution = _gal_profiles(gal.solution, match.xi, match.xi_deriv, ffs.mats, ffs) + wp = gal_wp(gal, ffs.equil.psio; cout=match.cout) + ffs.free_boundary === nothing || (free_boundary = free_run(wp, ffs.control, ffs.equil, ffs.mats, ffs)) + end + return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, wp=wp, free_boundary=free_boundary) end # A copy of the immutable `x` with the named fields replaced. diff --git a/src/ForceFreeStates/Matching/ResonantMatch.jl b/src/ForceFreeStates/Matching/ResonantMatch.jl index 3c542f3327..80e8a74e5b 100644 --- a/src/ForceFreeStates/Matching/ResonantMatch.jl +++ b/src/ForceFreeStates/Matching/ResonantMatch.jl @@ -6,17 +6,17 @@ MatchResult Matching coefficients and matched profiles, found in `result.match`. The profile -fields are empty when the solve kept no Galerkin basis; the inner fields are empty with `ideal`. +fields are empty when the solve kept no Galerkin basis. ## Fields - - `cout`, `cin`: `(2msing, ncoil)` outer and inner coefficients. + - `cout`, `cin`: `(2msing, nef)` outer and inner coefficients. - `deltar`: `(msing, 2)` inner-layer Δ per surface, columns (Δ₊, Δ₋) = (interchange, tearing). - - `rpec_eig`: forced eigenvalue γ = 2πi·n·f per surface. + - `forced_eigenvalue`: forced eigenvalue γ = 2πi·n·f per surface. - `residual`: relative residual of the linear solve. - - `bpen`: `(msing, ncoil)` penetrated resonant field at each layer center. - - `reconnected_flux`: `(2msing, ncoil)` `Δ_coil + Δ_outᵀ·cout`. - - `xi`, `xi_deriv`: `(mpert, ngrid, ncoil)` matched outer ξ and ξ′, one column per coil. + - `bpen`: `(msing, nef)` penetrated resonant field at each layer center. + - `reconnected_flux`: `(2msing, nef)` `Δ_EF + Δ_outᵀ·cout`. + - `xi`, `xi_deriv`: `(mpert, ngrid, nef)` matched outer ξ and ξ′, one column per EF column. - `inner_psi`, `inner_xi`, `inner_b`: per surface, the inner ψ grid and the composite ξ_ψ and b^ψ on it; empty unless the inner model returns real-ψ profiles (`GGJModel(; solver=:galerkin)` or `GGJModel(; real_profiles=true)`). - `inner_params`: per-surface `GGJParameters` used. @@ -27,7 +27,7 @@ struct MatchResult{P} cout::Matrix{ComplexF64} cin::Matrix{ComplexF64} deltar::Matrix{ComplexF64} - rpec_eig::Vector{ComplexF64} + forced_eigenvalue::Vector{ComplexF64} residual::Float64 bpen::Matrix{ComplexF64} reconnected_flux::Matrix{ComplexF64} @@ -42,13 +42,13 @@ struct MatchResult{P} end # Solve the 4·msing system mat·[cout; cin] = rmat (rmatch match_rpec). -function _match_system(dp_raw::AbstractMatrix, dp_coil::AbstractMatrix, deltar::AbstractMatrix) +function _match_system(dp_raw::AbstractMatrix, dp_ef::AbstractMatrix, deltar::AbstractMatrix) msing = size(dp_raw, 1) ÷ 2 - ncoil = size(dp_coil, 2) + nef = size(dp_ef, 2) mat = zeros(ComplexF64, 4msing, 4msing) - rmat = zeros(ComplexF64, 4msing, ncoil) + rmat = zeros(ComplexF64, 4msing, nef) @views mat[(2msing+1):4msing, 1:2msing] .= transpose(dp_raw) # Δ_out - @views rmat[(2msing+1):4msing, :] .= .-dp_coil # −Δ_coil + @views rmat[(2msing+1):4msing, :] .= .-dp_ef # −Δ_EF for ising in 1:msing idx1 = 2ising - 1 idx2 = 2ising @@ -82,7 +82,7 @@ function save_to_hdf5(out_h5::Union{HDF5.File,HDF5.Group}, m::MatchResult) out_h5["$g/Delta_r"] = m.deltar out_h5["$g/bpen"] = m.bpen out_h5["$g/reconnected_flux"] = m.reconnected_flux - out_h5["$g/rpec_eig"] = m.rpec_eig + out_h5["$g/forced_eigenvalue"] = m.forced_eigenvalue # Per-surface inner-layer ξ_ψ(ψ) (match.f intotsol); ragged grids → one dataset pair per surface. for i in eachindex(m.inner_psi) out_h5["$g/Inner/psi_$i"] = m.inner_psi[i] @@ -107,20 +107,20 @@ function save_to_hdf5(out_h5::Union{HDF5.File,HDF5.Group}, m::MatchResult) return nothing end -# Matching quantities are per unit coil-response column (the Δ′ coil block's normalization). +# Matching quantities are per unit EF column (the Δ′ EF block's normalization). const _MATCH_SURF = (; dims=("surface",)) const MATCH_H5_ANNOTATIONS = [ "SingularSurfaces/Match/cout" => - (; long_name="outer-region matching coefficients per surface parity, per unit coil-response column", dims=("surface_parity", "coil")), + (; long_name="outer-region matching coefficients per surface parity, per unit EF column", dims=("surface_parity", "ef")), "SingularSurfaces/Match/cin" => - (; long_name="inner-region matching coefficients per surface parity, per unit coil-response column", dims=("surface_parity", "coil")), + (; long_name="inner-region matching coefficients per surface parity, per unit EF column", dims=("surface_parity", "ef")), "SingularSurfaces/Match/Delta_r" => (; long_name="inner-layer Δ per surface and parity, (Δ₊ interchange, Δ₋ tearing)", dims=("surface", "parity")), "SingularSurfaces/Match/bpen" => - (; long_name="penetrated resonant field b^ψ at each layer center, per unit coil-response column", dims=("surface", "coil")), + (; long_name="penetrated resonant field b^ψ at each layer center, per unit EF column", dims=("surface", "ef")), "SingularSurfaces/Match/reconnected_flux" => - (; long_name="reconnected flux Δ_coil + Δ_outᵀ·cout per surface parity, per unit coil-response column", dims=("surface_parity", "coil")), - "SingularSurfaces/Match/rpec_eig" => (; long_name="forced eigenvalue γ = 2πi·n·f at each surface", units="rad/s", _MATCH_SURF...), + (; long_name="reconnected flux Δ_EF + Δ_outᵀ·cout per surface parity, per unit EF column", dims=("surface_parity", "ef")), + "SingularSurfaces/Match/forced_eigenvalue" => (; long_name="forced eigenvalue γ = 2πi·n·f at each surface", units="rad/s", _MATCH_SURF...), "SingularSurfaces/Match/residual" => (; long_name="relative residual of the matching linear solve"), "SingularSurfaces/Match/InnerParams/E" => (; long_name="Glasser-Greene-Johnson coefficient E per surface", _MATCH_SURF...), "SingularSurfaces/Match/InnerParams/F" => (; long_name="Glasser-Greene-Johnson coefficient F per surface", _MATCH_SURF...), @@ -134,6 +134,6 @@ const MATCH_H5_ANNOTATIONS = [ ] const _MATCH_INNER_H5_ANNOTATIONS = [ "psi" => (; long_name="normalized poloidal flux ψ_N grid across the inner layer of this surface", dims=("inner_psi",)), - "xi" => (; long_name="composite inner-layer ξ^ψ per unit coil-response column", dims=("inner_psi", "coil")), - "b" => (; long_name="composite inner-layer b^ψ per unit coil-response column", dims=("inner_psi", "coil")) + "xi" => (; long_name="composite inner-layer ξ^ψ per unit EF column", dims=("inner_psi", "ef")), + "b" => (; long_name="composite inner-layer b^ψ per unit EF column", dims=("inner_psi", "ef")) ] diff --git a/src/ForceFreeStates/Output.jl b/src/ForceFreeStates/Output.jl index ba8480148c..da3c400165 100644 --- a/src/ForceFreeStates/Output.jl +++ b/src/ForceFreeStates/Output.jl @@ -180,22 +180,18 @@ function save_to_hdf5( # Galerkin is the in-domain in-band subset of `SingularSurfaces/`. dp = result.delta_prime if msing > 0 && dp !== nothing - # Inter-surface Δ' matrix, shape [msing × msing] — PEST3-convention deltap. - out_h5["SingularSurfaces/Delta_prime_matrix"] = dp.matrix - - # Edge coil-response matrix, stored (numpert_total × 2msing) = (edge mode, surface-side) - # so H5Web heatmaps read x = edge mode, y = surface-side. The carried matrix stays - # (2msing × numpert_total); transpose only at write. - isempty(dp.coil) || (out_h5["SingularSurfaces/Delta_coil"] = permutedims(dp.coil)) - - # Raw 2msing×2msing outer-region D' matrix, side-major [L_s1, R_s1, L_s2, R_s2, …]; pest3_decompose recovers (A', B', Γ', Δ'). - isempty(dp.raw) || (out_h5["SingularSurfaces/Delta_prime_raw"] = dp.raw) - - # Remaining PEST-3 parity blocks, when the formalism persisted them (Galerkin); - # Riccati recovers them from Delta_prime_raw via pest3_decompose. - dp.A === nothing || (out_h5["SingularSurfaces/pest3_A"] = dp.A) - dp.B === nothing || (out_h5["SingularSurfaces/pest3_B"] = dp.B) - dp.Gamma === nothing || (out_h5["SingularSurfaces/pest3_Gamma"] = dp.Gamma) + ss = "SingularSurfaces" + isempty(dp.raw_freeboundary) || (out_h5["$ss/Delta_prime_raw_freeboundary"] = dp.raw_freeboundary) + isempty(dp.raw_fixedboundary) || (out_h5["$ss/Delta_prime_raw_fixedboundary"] = dp.raw_fixedboundary) + # Δ_EF stored (edge mode × surface-side) so H5Web heatmaps read x = edge mode. + isempty(dp.ef) || (out_h5["$ss/Delta_EF"] = permutedims(dp.ef)) + for (blocks, suffix) in ((dp.freeboundary, ""), (dp.fixedboundary, "_fixedboundary")) + blocks === nothing && continue + out_h5["$ss/Delta_prime_matrix$suffix"] = blocks.Delta + out_h5["$ss/pest3_A$suffix"] = blocks.A + out_h5["$ss/pest3_B$suffix"] = blocks.B + out_h5["$ss/pest3_Gamma$suffix"] = blocks.Gamma + end end result.match === nothing || save_to_hdf5(out_h5, result.match) @@ -213,7 +209,7 @@ function save_to_hdf5( # Jacobian-invariant); eigenmode columns are sorted most-unstable first, unit power norm, largest entry real-positive. fbs = "ForceFreeStates/FreeBoundaryStability" out_h5["$fbs/W_freeboundary"] = free_energies !== nothing ? free_energies.wt0 : ComplexF64[] - out_h5["$fbs/W_plasma"] = free_energies !== nothing ? free_energies.wp : ComplexF64[] + out_h5["$fbs/W_plasma"] = result.wp !== nothing ? result.wp : ComplexF64[] out_h5["$fbs/W_vacuum"] = free_energies !== nothing ? free_energies.wv : ComplexF64[] out_h5["$fbs/W_freeboundary_eigenmodes"] = free_energies !== nothing ? free_energies.wt : ComplexF64[] out_h5["$fbs/eigenmode_energies"] = free_energies !== nothing ? free_energies.et : ComplexF64[] diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index 207d2f6a34..4c0865e203 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -8,7 +8,7 @@ formalism produced the solution. ## Fields - `basis::Symbol` - Which formalism's basis the profiles are in: `:el_axis` (forward - integrator, axis Euler-Lagrange basis) or `:gal_native` (inner-layer-matched Galerkin + integrator, axis Euler-Lagrange basis) or `:gal_native` (ideal or inner-layer-matched Galerkin solution, identity-at-edge basis). - `step::Int` - Number of stored radial nodes. - `psi_store::Vector{Float64}` - ψ at each node. @@ -40,10 +40,10 @@ Optional fields are `Union{Nothing,T}` and follow a presence-equals-capability r consumer that needs one gates on [`require`](@ref) (or [`require_solution`](@ref) for the ξ profiles) and warns-and-skips rather than erroring, so a result from an integrator that cannot supply a given product still flows through the pipeline. PerturbedEquilibrium refuses -Galerkin and `:matched` results instead, since they publish no `wp` or `free_boundary` yet. +Galerkin and `:matched` results instead, since they publish no `free_boundary` yet. -A jump condition at the rational surfaces is always applied before a final result is built, -so bpen and closure are always present. +A Forward or Riccati solve applies the ideal jump condition at the rationals; a Galerkin solve +is ideal-closed by its EF columns (`error_field_response`), and is unclosed without them. ## Fields @@ -58,17 +58,20 @@ so bpen and closure are always present. - `surfaces::Vector{SingType}` - Ideal singular surfaces in the integration domain, with asymptotic bases and GGJ coefficients. - `kinetic::NamedTuple` - Kinetic singular-surface scan (`kmsing`, `kinsing`, `scan_psi`, `scan_cond`, `scan_threshold`); empty unless the finder ran. - `closure::Symbol` - How the basis is closed at the rationals: `:ideal` (the ideal jump - condition was imposed) or `:matched` (an inner-layer solution was matched in). A - `:matched` result carries no ideal δW: `wp` and `free_boundary` are `nothing`. + condition was imposed) or `:matched` (an inner-layer solution was matched in). A matched + Galerkin result carries the matched edge response as `wp`; a matched Riccati result none. - `bpen::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated resonant field from the inner layer, per surface (rows follow `surfaces`) and driving mode; all zeros under `:ideal` closure. - `match::Union{Nothing,MatchResult}` - The [`MatchResult`](@ref) of a `MatchProblem` solve; `nothing` otherwise. - `solution::Union{Nothing,SolutionProfiles}` - THE solve's ξ solution; `nothing` when the - formalism produced none (Riccati, and Galerkin without a match). + formalism produced none (Riccati, and Galerkin without `error_field_response`). - `diagnostics::Union{Nothing,OdeState}` - The integrator's raw ODE state (ψ trace, `crit`, edge scan, asymptotic coefficients). Written to HDF5; not a consumable solution. - - `wp::Union{Nothing,Matrix{ComplexF64}}` - Fixed-boundary plasma energy matrix `W_p = (U₂·U₁⁻¹)/ψ₀²` at - `psilim`. Present for any Euler-Lagrange sweep regardless of `vac_flag`; equals `free_boundary.wp` when that ran. + - `wp::Union{Nothing,Matrix{ComplexF64}}` - Fixed-boundary plasma energy matrix at `psilim`, the edge + displacement → edge momentum map over ψ₀² [Glasser 2016 PoP 23 072505, Eq. 66]: `(U₂·U₁⁻¹)/ψ₀²` for an + Euler-Lagrange sweep (regardless of `vac_flag`; equals `free_boundary.wp` when that ran), the EF-column + edge response over ψ₀² for Galerkin. Under `:matched` closure it is the complex matched edge response, whose + anti-Hermitian part is the torque the inner layers absorb [Logan 2013, eq. 19]. - `free_boundary::Union{Nothing,FreeBoundaryResult}` - Free-boundary energies and eigenmodes; `nothing` when the vacuum step was skipped or the formalism computes none. - `delta_prime::Union{Nothing,DeltaPrimeData}` - Δ′/outer-region matching payload from whichever formalism ran (Riccati BVP or Galerkin); `nothing` when neither produced one. @@ -144,17 +147,27 @@ function require_solution(result::ForceFreeStatesResult, calc::AbstractString) return false end -# Pack the matched Galerkin solution into `SolutionProfiles`: on-surface `issing` points are dropped, Ξ′ is the -# analytic Galerkin derivative, and Ξ_s = −A⁻¹(B·Ξ′ + C·Ξ) as in `sing_der!`. Grid runs inner→edge. -function _matched_gal_profiles(gal_result::GalerkinResult, m::MatchResult, mats::MatrixSplines, intr::ModeSpace) - sol = gal_result.solution +# Columns of the Galerkin error-field (EF) drives (error_field_response). +gal_ef_columns(gal::GalerkinResult) = (2gal.msing+1):size(gal.edge_response, 2) + +# Plasma energy matrix W_P of the ideal (no `cout`) or matched Galerkin solution, in the units of `(U₂·U₁⁻¹)/ψ₀²`. +function gal_wp(gal::GalerkinResult, psio::Float64; cout::Union{Nothing,Matrix{ComplexF64}}=nothing) + F = gal.edge_response + W = F[:, gal_ef_columns(gal)] + cout === nothing || mul!(W, @view(F[:, 1:(2gal.msing)]), cout, true, true) + return W ./ psio^2 +end + +# `SolutionProfiles` of closed Galerkin columns `xi`, `xi_deriv` (npert, ngrid, ncol) on the grid of `sol`, without on-surface points. +function _gal_profiles(sol::GalerkinSolution, xi::AbstractArray{ComplexF64,3}, xi_deriv::AbstractArray{ComplexF64,3}, mats::MatrixSplines, + intr::ModeSpace) npert = intr.numpert_total keep = .!sol.issing psi_f = sol.psi[keep] q_f = sol.q[keep] - xi_f = m.xi[:, keep, :] # (npert, ngrid_f, mcoil) - dxi_f = m.xi_deriv[:, keep, :] + xi_f = xi[:, keep, :] # (npert, ngrid_f, ncol) + dxi_f = xi_deriv[:, keep, :] ngrid_f = length(psi_f) # u_store[:, :, 2] stays zero: the conjugate momentum has no consumer on this path and no @@ -180,8 +193,9 @@ end -> ForceFreeStatesResult Assemble the published result once the solve is finished, with the ideal closure (a `MatchProblem` -solve transforms it afterwards). Materializes the forward path's derivative stores and forms `W_p` -when the free-boundary stage did not run; everything else is copied or aliased. +solve transforms it afterwards). Materializes the forward path's derivative stores, packs the Galerkin +EF columns as the solution, and forms `W_p` when the free-boundary stage did not run; everything else +is copied or aliased. `odet` is the ODE state (`nothing` for Galerkin); `gal_data`/`gal_dp` are the Galerkin internals and its Δ′ payload (`nothing` otherwise). @@ -198,22 +212,27 @@ function build_result( gal_data::Union{Nothing,GalerkinResult}, gal_dp::Union{Nothing,DeltaPrimeData} ) + # The Galerkin EF columns (ξ = eⱼ at the edge, no big-solution drive) are its ideal closure. + gal_ef = gal_data === nothing || gal_data.solution === nothing ? (1:0) : gal_ef_columns(gal_data) + # The forward sweep is the only formalism whose stores need materializing; doing it here # keeps `SolutionProfiles.du_store`/`xi_s_store` populated by construction. solution = if integrator === :forward && odet !== nothing materialize_derivative_stores!(odet, equil, mats, intr) SolutionProfiles(:el_axis, odet.step, odet.psi_store, odet.q_store, odet.u_store, odet.du_store, odet.xi_s_store) + elseif !isempty(gal_ef) + gs = gal_data.solution + _gal_profiles(gs, @view(gs.xi[:, :, gal_ef]), @view(gs.xi_deriv[:, :, gal_ef]), mats, intr) else nothing end - # One Δ′ payload whichever formalism produced it; Riccati leaves the PEST-3 blocks unfilled - # because it persists only the raw D′ and recovers them on demand via `pest3_decompose`. + # One Δ′ payload whichever formalism produced it. delta_prime = if gal_dp !== nothing gal_dp - elseif !isempty(intr.delta_prime_matrix) - DeltaPrimeData(intr.delta_prime_matrix, intr.delta_prime_raw, intr.delta_coil, nothing, nothing, nothing) + elseif !isempty(intr.delta_prime_raw_freeboundary) || !isempty(intr.delta_prime_raw_fixedboundary) + DeltaPrimeData(intr.delta_prime_raw_freeboundary, intr.delta_prime_raw_fixedboundary, intr.delta_ef) else nothing end @@ -229,6 +248,8 @@ function build_result( free_energies.wp elseif odet !== nothing (odet.u[:, :, 2] / odet.u[:, :, 1]) ./ equil.psio^2 + elseif !isempty(gal_ef) + gal_wp(gal_data, equil.psio) else nothing end diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index d0b157d4aa..7d9644e92c 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -106,7 +106,7 @@ function _capture_right_crossing_data!(odet::OdeState, singp::SingType, sing_asy end # STUB: per-surface ca-based Δ' (not physically valid; see SingType.delta_prime docstring). -# The canonical Δ' is intr.delta_prime_matrix from compute_delta_prime_matrix!. +# The canonical Δ' is the BVP Δ' (`DeltaPrimeData`) from compute_delta_prime_matrix!. function _stash_per_surface_delta_prime_stub!(odet::OdeState, intr::ForceFreeStatesInternal, ising::Int, ipert_res, sing_asymp_right, equil::Equilibrium.PlasmaEquilibrium, diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index fcac7b1151..0aca3b5182 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -26,22 +26,17 @@ which requires forward crossing chunks. ## Output: PEST3-convention Δ' (deltap) -The raw BVP solution is a 2·msing × 2·msing matrix `dp` with left/right -sub-indices at each surface, stored in `intr.delta_prime_raw`. The PEST3-convention Δ' is -[Chance, PPPL-2527]: - -``` - deltap(i,j) = dp(2i,2j) - dp(2i,2j-1) - dp(2i-1,2j) + dp(2i-1,2j-1) -``` - -stored in `intr.delta_prime_matrix` (msing × msing). +The raw BVP solution is a 2·msing × 2·msing matrix with left/right sub-indices at each surface: +`intr.delta_prime_raw_freeboundary` with the vacuum edge, `intr.delta_prime_raw_fixedboundary` with +ξ(edge) = 0 (from the vacuum-edge matrix with a Dirichlet edge, which also gives `intr.delta_ef`, or +directly when `wv = nothing`). `pest3_decompose` gives the PEST-3 blocks [Chance, PPPL-2527]. ## Limitations Assumes one resonant mode per surface: if any surface carries several (a multi-`n` run where one q satisfies two `(m, n)`, e.g. q = 2 with (2, 1) and (4, 2)), it warns and skips the BVP. -`intr.delta_prime_matrix` is the only physically valid Δ'; the per-surface ca-based +The BVP Δ' is the only physically valid one; the per-surface ca-based `intr.sing[*].delta_prime` is a diagnostic placeholder and need not agree with it. """ function compute_delta_prime_matrix!( @@ -106,18 +101,18 @@ function compute_delta_prime_matrix!( @info "Δ' BVP: nMat=$nMat, rank(M)=$(rank(M)), cond(M)=$(@sprintf("%.2e", cond(M)))" end - # rpec coil-response block: needs the S-axis row layout that `_solve_bvp_edge_coil` assumes - # for its edge rows, and a vacuum edge in the assembled matrix (col_edge in junc_rows). - if use_S_axis && wv !== nothing - intr.delta_coil = _solve_bvp_edge_coil(M, col_edge, msing, N, ipert_all) + raw = _solve_bvp_raw(M, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) + if wv === nothing + intr.delta_prime_raw_fixedboundary = raw + else + intr.delta_prime_raw_freeboundary = raw + # The fixed edge and the EF block need the S-axis row layout of the edge rows. + if use_S_axis + Mc = _fixed_edge_bvp(M, msing, N, col_edge) + intr.delta_prime_raw_fixedboundary = _solve_bvp_raw(Mc, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) + (ctrl === nothing || ctrl.algorithm.error_field_response) && (intr.delta_ef = _solve_bvp_edge_ef(Mc, msing, N, ipert_all)) + end end - - deltap, dp_raw_persisted = _solve_bvp_and_combine_pest3( - M, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) - - # The raw side-major D' (Fortran gal_write_delta layout) feeds `pest3_decompose`. - intr.delta_prime_matrix = deltap - intr.delta_prime_raw = dp_raw_persisted end # Column index helpers for the BVP matrix. j is the 1-based singular-surface index, @@ -393,26 +388,33 @@ function _assemble_bvp_S_axis(uShootR::Vector{Matrix{ComplexF64}}, return M, nMat, col_edge end -# Coil-response block for the Eq. (37) edge [Glasser-Kolemen 2018 PoP 25, 032501]: impose the rpec edge BC -# (RDCON `gal_set_boundary`, unit source per poloidal mode) and read the small-solution coefficient at each -# surface side, solving all N modes with one factorization. Returns delta_coil (2·msing × N). -function _solve_bvp_edge_coil(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int, ipert_all::Vector{Int}) +# The S-axis BVP matrix `M` with its Eq. (38) vacuum-edge rows [Glasser-Kolemen 2018 PoP 25, 032501] replaced by a +# Dirichlet edge, whose edge coefficients equal the right-hand side (0 for the fixed-boundary D′). +function _fixed_edge_bvp(M::Matrix{ComplexF64}, msing::Int, N::Int, col_edge) nMat = size(M, 1) - bot = (nMat-2msing-N+1):(nMat-2msing) # Eq. (38) bottom rows, carrying the W_V block + bot = (nMat-2msing-N+1):(nMat-2msing) Mc = copy(M) Mc[bot, :] .= 0 - Mc[bot, col_edge] .= I(N) # Dirichlet edge: the edge coefficients equal the source + Mc[bot, col_edge] .= I(N) + return Mc +end + +# Δ_EF (2·msing × N) from the fixed-edge BVP matrix `Mc`: the small-solution coefficient at each surface side for a +# unit edge displacement in each poloidal mode. +function _solve_bvp_edge_ef(Mc::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}) + nMat = size(Mc, 1) + bot = (nMat-2msing-N+1):(nMat-2msing) B = zeros(ComplexF64, nMat, N) B[bot, :] .= I(N) # unit drive, one column per edge poloidal mode X = lu(Mc) \ B - delta_coil = zeros(ComplexF64, 2msing, N) + delta_ef = zeros(ComplexF64, 2msing, N) for j in 1:msing row_left = _col_left(j, N)[ipert_all[j]+N] row_right = _col_right(j, N)[ipert_all[j]+N] - @views delta_coil[2j-1, :] .= X[row_left, :] - @views delta_coil[2j, :] .= X[row_right, :] + @views delta_ef[2j-1, :] .= X[row_left, :] + @views delta_ef[2j, :] .= X[row_right, :] end - return delta_coil + return delta_ef end # Fallback BVP assembly with FM-based axis BC (used when no Riccati S matrices are available). @@ -468,8 +470,8 @@ function _assemble_bvp_FM_axis(Phi_L_mats::Vector{Matrix{ComplexF64}}, return M, nMat, col_edge end -# Solve the BVP and apply the PEST3 four-term combination. -function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, +# Solve the BVP for the raw side-major D′ (2·msing × 2·msing). +function _solve_bvp_raw(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, use_S_axis::Bool, ipert_all::Vector{Int}, col_edge, ctrl, debug::Bool) s2 = 2 * msing @@ -501,15 +503,8 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, end end - # PEST3 four-term combination [Chance PPPL-2527; Glasser-Kolemen 2018 PoP 25, 032501 Eq. 31]. - # Δ'[i,j] = (NW − NE − SW + SE) on each 2×2 block of dp_raw. - deltap = zeros(Tc, msing, msing) - for i in 1:msing, j in 1:msing - deltap[i, j] = dp_raw[2i, 2j] - dp_raw[2i, 2j-1] - dp_raw[2i-1, 2j] + dp_raw[2i-1, 2j-1] - end - - debug && _log_bvp_pest3(dp_raw, deltap, s2, msing) - return ComplexF64.(deltap), ComplexF64.(dp_raw) + debug && _log_bvp_pest3(dp_raw, pest3_decompose(ComplexF64.(dp_raw)).Delta, s2, msing) + return ComplexF64.(dp_raw) end # Logging helpers for `compute_delta_prime_matrix!`. Called only when debug=true. @@ -617,60 +612,3 @@ function _log_bvp_pest3(dp_raw, deltap, s2, msing) @info "Δ' BVP: Raw dp diagonal = $([@sprintf("%.4f%+.4fi", Float64(real(dp_raw[i,i])), Float64(imag(dp_raw[i,i]))) for i in 1:s2])" @info "Δ' BVP: deltap diagonal = $([@sprintf("%.4f%+.4fi", real(deltap[i,i]), imag(deltap[i,i])) for i in 1:msing])" end - -""" - pest3_decompose(dp_raw::AbstractMatrix) -> NamedTuple{(:A, :B, :Γ, :Δ)} - -Rotate the raw 2m×2m outer-region matching matrix `dp_raw` (side-major -ordering `[L_s1, R_s1, L_s2, R_s2, …]`) into the Pletzer–Dewar 1991 parity -blocks. Given rows and columns paired by surface (odd index = left, even -index = right), the Fortran RDCON parity combination is - -``` -A'(i,j) = RR + RL + LR + LL (even-i, even-j) — interchange↔interchange -B'(i,j) = RR − RL + LR − LL (even-i, odd-j) — interchange↔tearing -Γ'(i,j) = RR + RL − LR − LL (odd-i, even-j) — tearing↔interchange -Δ'(i,j) = RR − RL − LR + LL (odd-i, odd-j) — tearing↔tearing -``` - -where `RR = dp_raw[2i, 2j]`, `RL = dp_raw[2i, 2j−1]`, -`LR = dp_raw[2i−1, 2j]`, `LL = dp_raw[2i−1, 2j−1]`. Each block is m×m. - -No Pletzer–Dewar ½ prefactor, matching Fortran RDCON; it cancels in `det(D' − D(γ)) = 0`. - -The Δ' block returned here equals `intr.delta_prime_matrix` (the m×m PEST3 -tearing projection computed inside `compute_delta_prime_matrix!`). - -# Arguments - - - `dp_raw` — 2m×2m complex matrix (typically `intr.delta_prime_raw`). - -# Returns - -Named tuple `(A, B, Γ, Δ)` of m×m matrices, the blocks of `D' = [[A' B'] [Γ' Δ']]` in the -`det(D' − D(γ)) = 0` problem (interchange upper-left, tearing lower-right). -""" -function pest3_decompose(dp_raw::AbstractMatrix) - s2 = size(dp_raw, 1) - size(dp_raw, 2) == s2 || - throw(ArgumentError("pest3_decompose: dp_raw must be square, got $(size(dp_raw))")) - iseven(s2) || - throw(ArgumentError("pest3_decompose: dp_raw side must be 2m for integer m, got $s2")) - m = s2 ÷ 2 - Tc = eltype(dp_raw) - Ap = zeros(Tc, m, m) - Bp = zeros(Tc, m, m) - Gp = zeros(Tc, m, m) - Dp = zeros(Tc, m, m) - for i in 1:m, j in 1:m - LL = dp_raw[2i-1, 2j-1] - LR = dp_raw[2i-1, 2j] - RL = dp_raw[2i, 2j-1] - RR = dp_raw[2i, 2j] - Ap[i, j] = RR + RL + LR + LL - Bp[i, j] = RR - RL + LR - LL - Gp[i, j] = RR + RL - LR - LL - Dp[i, j] = RR - RL - LR + LL - end - return (A=Ap, B=Bp, Γ=Gp, Δ=Dp) -end diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 7e440b1f59..f004b72d5e 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -56,8 +56,8 @@ function run_force_free_states( nstring = _mode_range_label(intr) # The three formalisms are exclusive. Galerkin solves the same Euler-Lagrange system - # variationally rather than by radial ODE integration, so it replaces both the integration - # and the free-boundary energies, and supplies its own vacuum response at psilim. + # variationally rather than by radial ODE integration, and supplies its own vacuum response at + # psilim; its EF columns (error_field_response) give the plasma response the free-boundary energies need. odet = nothing free_energies = nothing gal_data = nothing @@ -70,6 +70,9 @@ function run_force_free_states( gal_data, gal_dp = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) gal_dt = time() - gal_start @info "Galerkin solve completed in $(@sprintf("%.3f", gal_dt)) s" + if ctrl.vac_flag && gal_data.solution !== nothing && !isempty(gal_ef_columns(gal_data)) + free_energies = free_run(gal_wp(gal_data, equil.psio), ctrl, equil, mats, intr; verbose=intr.verbose) + end else if intr.verbose @info "Integrating Euler-Lagrange equation" @@ -84,7 +87,7 @@ function run_force_free_states( wall_desc = intr.wall_settings === nothing ? "no wall" : nameof(typeof(intr.wall_settings)) @info "Computing free boundary energies ($wall_desc)" end - free_energies = free_run(odet, ctrl, equil, mats, intr) + free_energies = free_run((odet.u[:, :, 2] / odet.u[:, :, 1]) ./ equil.psio^2, ctrl, equil, mats, intr; verbose=intr.verbose) normalize_eigenfunctions!(odet, free_energies.wt, equil.psio) if real(free_energies.et[1]) < 0 if intr.verbose diff --git a/src/ForceFreeStates/Surfaces/Types.jl b/src/ForceFreeStates/Surfaces/Types.jl index 0099590ab1..447cf5a65a 100644 --- a/src/ForceFreeStates/Surfaces/Types.jl +++ b/src/ForceFreeStates/Surfaces/Types.jl @@ -14,7 +14,7 @@ A mutable struct holding data related to the singular surfaces in the equilibriu - `q::Float64` - Safety factor (= m/n) - `q1::Float64` - Derivative of safety factor with respect to ψ - `delta_prime::Vector{ComplexF64}` - **Debug stub, not physically valid.** Per-surface ca-based Δ' estimate; - use `ForceFreeStatesInternal.delta_prime_matrix` (STRIDE global BVP, Glasser 2018 PoP 25, 032501) for tearing stability. + use the BVP Δ' (`DeltaPrimeData`) (STRIDE global BVP, Glasser 2018 PoP 25, 032501) for tearing stability. - `delta_prime_col::Matrix{ComplexF64}` - **Debug stub, not physically valid.** Per-surface ca-based Δ' columns, `(numpert_total, n_res_modes)`, `delta_prime_col[j, i] = (ca_r[j,ipert_res_i,2] - ca_l[j,ipert_res_i,2]) / (4π²·psio)`; diagonal matches `delta_prime`. Riccati/parallel paths only. """ diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 2beaa59163..2595645895 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -51,9 +51,10 @@ their dominant modes (Park, Phys. Plasmas 16, 056115 (2009)), and with `compute_ with `perturbed_equilibrium(resp, rmp)` as many times as needed. Products the producing integrator could not supply (free-boundary energies, a ξ solution) leave the -corresponding operators empty: the step warns and is skipped. Galerkin and `:matched` results publish -no free-boundary δW yet, so building a response from one is an error. So is a solve with a wall: the -surface inductance is free-space, and the response needs Λ from the same no-wall vacuum. +corresponding operators empty: the step warns and is skipped. A Galerkin result carries a free-boundary +δW only with `error_field_response` and `vac_flag`, so building a response from one without it is an error. So is a +`:matched` result, whose singular coupling is not defined yet, and a solve with a wall: the surface +inductance is free-space, and the response needs Λ from the same no-wall vacuum. """ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling::Bool=true, compute_torque_response::Bool=false, verbose::Bool=false)::PlasmaResponse @@ -62,11 +63,14 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: "plasma_response needs a force-free-states solve without a wall: its surface inductance L is free-space, " * "so Λ from a wall run would mix two vacuum models. Solve with wall=nothing (no [Wall] section)." ) - # Galerkin and matched results publish no plasma edge response wp, so no operator could be built. - if ffs.free_boundary === nothing && (ffs.integrator === :galerkin || ffs.closure === :matched) - error("plasma_response needs the free-boundary δW, which a $(ffs.integrator) result with $(ffs.closure) closure " * - "does not publish yet; use a forward solve") - end + # The singular coupling evaluates ideal-closure resonant metrics off each surface, where a matched solution's + # big solution is singular. + ffs.closure === :matched && + error("plasma_response does not support a matched result yet: its singular-coupling metrics assume the ideal closure; " * + "use the unmatched solve") + ffs.free_boundary === nothing && ffs.integrator === :galerkin && + error("plasma_response needs the free-boundary δW, which this Galerkin result does not carry: solve with " * + "Galerkin(; error_field_response=true) and vac_flag=true") m_modes, n_modes = mode_arrays(ffs) # A run has at most one ξ solution, already closed at the rationals and carrying populated diff --git a/src/Tearing/Dispersion/CoupledFullMatch.jl b/src/Tearing/Dispersion/CoupledFullMatch.jl index 19e7e52ba0..91e3c877b2 100644 --- a/src/Tearing/Dispersion/CoupledFullMatch.jl +++ b/src/Tearing/Dispersion/CoupledFullMatch.jl @@ -11,7 +11,7 @@ # Eq. (36)-(40); original matching construction Pletzer & Dewar 1991, # J. Plasma Phys. **45**, 427). # -# The outer D' (`intr.delta_prime_raw`) is in the side-major L/R basis while the inner layer returns +# The outer D' (`DeltaPrimeData` raw D') is in the side-major L/R basis while the inner layer returns # Δ in the parity ± basis, so both amplitude sets are kept as unknowns and joined by the matching # identity rows, giving a 4m × 4m system instead of a basis-mixing 2m × 2m determinant. # @@ -64,7 +64,7 @@ end inner_kwargs=NamedTuple()) -> MultiSurfaceCouplingFull Construct the 4m × 4m dispersion matrix driver. `dp_raw` must be the -2m × 2m matrix in side-major ordering (the `intr.delta_prime_raw` +2m × 2m matrix in side-major ordering (the `DeltaPrimeData` raw D' field populated by `ForceFreeStates.compute_delta_prime_matrix!` on the Riccati path). Surface k's inner layer is evaluated at `Q·ratio_k` Doppler-shifted by its E×B offset `q_shift_k`, exactly as in the reduced `multi_surface_coupling`: added to Q for a diff --git a/src/Tearing/GGJTearing.jl b/src/Tearing/GGJTearing.jl index c6780aac95..b075c83980 100644 --- a/src/Tearing/GGJTearing.jl +++ b/src/Tearing/GGJTearing.jl @@ -4,18 +4,25 @@ # determinant (Dispersion.ggj_growth_rates), each surface on its own when uncoupled, # the leading `msing_max` surfaces together when coupled. -# The raw side-major Δ′ the determinant needs, after checking it is aligned with ordered surfaces. -function _ggj_delta_prime_raw(ffs) +# The raw side-major Δ′ of the problem's boundary that the determinant needs, aligned with ordered surfaces. +function _ggj_delta_prime_raw(prob::TearingProblem) + ffs = prob.ffs ffs.npert == 1 || throw(ArgumentError("GGJ tearing is single-n; the result spans n = $(ffs.nlow):$(ffs.nhigh)")) surfaces = ffs.surfaces psi = Float64[s.psifac for s in surfaces] issorted(psi; lt=<=) || throw(ArgumentError("GGJ tearing needs distinct surfaces ordered core to edge; got ψ = $psi")) dp = ffs.delta_prime - dp === nothing && throw(ArgumentError("GGJ tearing needs the raw Δ′ matrix; solve with Riccati() and vac_flag=true, or Galerkin(; rpec_flag=true)")) - size(dp.raw) == (2length(surfaces), 2length(surfaces)) || - throw(ArgumentError("GGJ tearing: Δ′ raw block is $(size(dp.raw, 1))×$(size(dp.raw, 2)) but the result carries $(length(surfaces)) surfaces")) - all(isfinite, dp.raw) || throw(ArgumentError("GGJ tearing: the raw Δ′ matrix has non-finite entries")) - return dp.raw + dp === nothing && throw(ArgumentError("GGJ tearing needs the raw Δ′ matrix; solve with Riccati() or Galerkin()")) + raw = prob.fixed_boundary ? dp.raw_fixedboundary : dp.raw_freeboundary + size(raw) == (2length(surfaces), 2length(surfaces)) || + throw( + ArgumentError( + "GGJ tearing: the $(prob.fixed_boundary ? "fixed" : "free")-boundary Δ′ raw block is " * + "$(size(raw, 1))×$(size(raw, 2)) but the result carries $(length(surfaces)) surfaces" + ) + ) + all(isfinite, raw) || throw(ArgumentError("GGJ tearing: the raw Δ′ matrix has non-finite entries")) + return raw end # η and ρ given on the problem, as MatchProblem takes them: a scalar or one value per surface, core to edge. @@ -70,7 +77,7 @@ function CommonSolve.solve(prob::TearingProblem, model::GGJModel; config::Tearin ffs = prob.ffs surfaces = ffs.surfaces isempty(surfaces) && return empty_tearing_result(prob, config, model) - raw = _ggj_delta_prime_raw(ffs) + raw = _ggj_delta_prime_raw(prob) count = length(surfaces) eta, rho = _ggj_layer_inputs(prob) params = [ggj_parameters(s, ffs.equil; eta=eta[k], rho=rho[k], gamma=prob.gamma, ising=k) for (k, s) in enumerate(surfaces)] @@ -118,7 +125,8 @@ function CommonSolve.solve(prob::TearingProblem, model::GGJModel; config::Tearin end end return TearingResult(prob, true, config, model, params, - Float64[s.psifac for s in surfaces], Float64[s.q for s in surfaces], Matrix{ComplexF64}(ffs.delta_prime.matrix), + Float64[s.psifac for s in surfaces], Float64[s.q for s in surfaces], + Matrix{ComplexF64}((prob.fixed_boundary ? ffs.delta_prime.fixedboundary : ffs.delta_prime.freeboundary).Delta), Q_root, omega, Float64[e.gamma for e in extractions], coupled ? GrowthRateResult[] : extractions, coupled ? only(extractions) : nothing, LayerWidths[], Ω_E, zeros(count), scans, empty_critical_resonant_field_result()) diff --git a/src/Tearing/HDF5Output.jl b/src/Tearing/HDF5Output.jl index dbf1ed5b9f..e64081e82e 100644 --- a/src/Tearing/HDF5Output.jl +++ b/src/Tearing/HDF5Output.jl @@ -38,7 +38,8 @@ function save_to_hdf5(parent::Union{HDF5.File,HDF5.Group}, _write_per_surface!(g, result.params, result.dp_matrix) if result.model isa GGJModel && result.problem !== nothing - g["PerSurface/Delta_prime_raw"] = result.problem.ffs.delta_prime.raw + dp = result.problem.ffs.delta_prime + g["PerSurface/Delta_prime_raw"] = result.problem.fixed_boundary ? dp.raw_fixedboundary : dp.raw_freeboundary end # E×B rotation resolved per surface, and the Doppler offset it applies to the inner-layer Q. g["PerSurface/omega_E"] = result.omega_E diff --git a/src/Tearing/TearingProblem.jl b/src/Tearing/TearingProblem.jl index 1d1b5a75d0..e62cbc6c4b 100644 --- a/src/Tearing/TearingProblem.jl +++ b/src/Tearing/TearingProblem.jl @@ -11,7 +11,7 @@ GGJ layer inputs; the SLAYER layer closures belong to [`SLAYERModel`](@ref) and Z_eff and transport defaults, confinement time and resistivity closure) is the equilibrium's kinetic data, `ffs.equil.kinetic` (see [`KineticProfileData`](@ref)), so every layer model sees one plasma. Solve with `solve(problem, GGJModel(); config)` or `solve(problem, SLAYERModel(); config)`. -GGJ needs the raw Δ′ matrix (Riccati with `vac_flag=true`, or Galerkin with `rpec_flag=true`). +Both read the free-boundary Δ′ of `ffs.delta_prime`, or the fixed-boundary one with `fixed_boundary`. Both models report lab-frame roots from each surface's E×B rotation. ## Fields @@ -24,6 +24,7 @@ Both models report lab-frame roots from each surface's E×B rotation. (core to edge), as in [`MatchProblem`](@ref GeneralizedPerturbedEquilibrium.ForceFreeStates.MatchProblem). `nothing` (default) derives them from the kinetic data: η from its resistivity closure, the one SLAYER uses, and ρ = μ·m_p·n_e as SLAYER takes it. Unused by `SLAYERModel`. - `gamma` - GGJ ratio of specific heats. + - `fixed_boundary` - Use the fixed-boundary Δ′ (a conformal wall on the plasma) instead of the free-boundary one. """ @kwdef struct TearingProblem{R,E,D} ffs::R @@ -34,6 +35,7 @@ Both models report lab-frame roots from each surface's E×B rotation. msing_max::Int = 3 omega_E_kHz::Dict{String,Float64} = Dict{String,Float64}() critical_resonant_field::Union{Nothing,CriticalResonantFieldControl} = nothing + fixed_boundary::Bool = false end TearingProblem(ffs; eta=nothing, rho=nothing, kwargs...) = @@ -90,6 +92,10 @@ function CommonSolve.solve(prob::TearingProblem, model::SLAYERModel; config::Tea validate(prob, config) isempty(surfaces) && return empty_tearing_result(prob, config, model) + dp = ffs.delta_prime + blocks = dp === nothing ? nothing : prob.fixed_boundary ? dp.fixedboundary : dp.freeboundary + dp !== nothing && blocks === nothing && + error("TearingProblem: the solve did not compute the $(prob.fixed_boundary ? "fixed" : "free")-boundary Δ′") equil.kinetic === nothing && error("TearingProblem: the equilibrium carries no kinetic profiles; set kinetic_file in [Equilibrium] or attach_kinetic_profiles!") @@ -99,7 +105,7 @@ function CommonSolve.solve(prob::TearingProblem, model::SLAYERModel; config::Tea params = _tearing_params(model, equil, surfaces, loaded) # Prefer the full inter-surface Δ' matrix; fall back to a diagonal of each surface's scalar delta_prime. - dpm = ffs.delta_prime === nothing ? Matrix{ComplexF64}(undef, 0, 0) : ffs.delta_prime.matrix + dpm = blocks === nothing ? Matrix{ComplexF64}(undef, 0, 0) : blocks.Delta dp = if !isempty(dpm) && size(dpm) == (length(params), length(params)) Matrix{ComplexF64}(dpm) else diff --git a/src/Utilities/HDF5Schema.jl b/src/Utilities/HDF5Schema.jl index c5a6de57e4..8fb5ce2cba 100644 --- a/src/Utilities/HDF5Schema.jl +++ b/src/Utilities/HDF5Schema.jl @@ -244,14 +244,22 @@ const MAIN_H5_ANNOTATIONS = [ (; long_name="μ0 × dp/dψ_N at each surface", units="T^2", dims=("surface",), attach=(1 => "SingularSurfaces/rational_psi", 1 => "SingularSurfaces/rational_q")), "SingularSurfaces/dVdpsi" => (; long_name="dV/dψ_N at each surface", units="m^3", dims=("surface",), attach=(1 => "SingularSurfaces/rational_psi", 1 => "SingularSurfaces/rational_q")), - "SingularSurfaces/Delta_prime_matrix" => - (; long_name="inter-surface Δ' matrix (PEST-3 tearing↔tearing block; STRIDE BVP or Galerkin outer region)", dims=("surface_row", "surface_col")), - "SingularSurfaces/Delta_prime_raw" => - (; long_name="raw 2msing×2msing outer-region D' matrix, side-major ordering [L_s1, R_s1, ...]", dims=("surface_side_row", "surface_side_col")), - "SingularSurfaces/Delta_coil" => (; long_name="edge coil-response matrix (edge mode × surface-side)", dims=("mode", "surface_side")), - "SingularSurfaces/pest3_A" => (; long_name="PEST-3 matching block A' (interchange↔interchange)", dims=("surface_row", "surface_col")), - "SingularSurfaces/pest3_B" => (; long_name="PEST-3 matching block B' (interchange↔tearing)", dims=("surface_row", "surface_col")), - "SingularSurfaces/pest3_Gamma" => (; long_name="PEST-3 matching block Γ' (tearing↔interchange)", dims=("surface_row", "surface_col")), + "SingularSurfaces/Delta_prime_raw_freeboundary" => + (; long_name="raw outer-region D' with the vacuum edge, side-major [L_s1, R_s1, ...]", dims=("surface_side_row", "surface_side_col")), + "SingularSurfaces/Delta_prime_raw_fixedboundary" => + (; long_name="raw outer-region D' with a fixed edge (conformal wall on the plasma), side-major [L_s1, R_s1, ...]", + dims=("surface_side_row", "surface_side_col")), + "SingularSurfaces/Delta_EF" => + (; long_name="error-field response Δ_EF: small-solution coefficient per unit edge displacement (edge mode × surface-side)", dims=("mode", "surface_side")), + "SingularSurfaces/Delta_prime_matrix" => (; long_name="free-boundary Δ' matrix (PEST-3 tearing↔tearing block)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_A" => (; long_name="free-boundary PEST-3 block A' (interchange↔interchange)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_B" => (; long_name="free-boundary PEST-3 block B' (interchange↔tearing)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_Gamma" => (; long_name="free-boundary PEST-3 block Γ' (tearing↔interchange)", dims=("surface_row", "surface_col")), + "SingularSurfaces/Delta_prime_matrix_fixedboundary" => + (; long_name="fixed-boundary Δ' matrix (PEST-3 tearing↔tearing block)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_A_fixedboundary" => (; long_name="fixed-boundary PEST-3 block A' (interchange↔interchange)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_B_fixedboundary" => (; long_name="fixed-boundary PEST-3 block B' (interchange↔tearing)", dims=("surface_row", "surface_col")), + "SingularSurfaces/pest3_Gamma_fixedboundary" => (; long_name="fixed-boundary PEST-3 block Γ' (tearing↔interchange)", dims=("surface_row", "surface_col")), # --- SingularSurfaces/Kinetic/ --- "SingularSurfaces/Kinetic/rational_count" => (; long_name="number of kinetic singular surfaces (det(F̄) near-zeros)"), "SingularSurfaces/Kinetic/rational_psi" => (; long_name="normalized poloidal flux ψ_N of kinetic singular surfaces", scale="psi_kinetic_rational"), diff --git a/test/runtests_galerkin_cholesky.jl b/test/runtests_galerkin_cholesky.jl index 11a38764f9..e1fff1e8f0 100644 --- a/test/runtests_galerkin_cholesky.jl +++ b/test/runtests_galerkin_cholesky.jl @@ -2,7 +2,7 @@ using Test using LinearAlgebra # gal_banded_solve! on a full-band (gbtrf layout) system built like the Galerkin matrix: Hermitian, with -# Dirichlet identity rows (row zeroed, column kept) and nonzero prescribed values, as in the rpec coil columns. +# Dirichlet identity rows (row zeroed, column kept) and nonzero prescribed values, as in the EF columns. @testset "Galerkin banded solve: Cholesky first, LU fallback" begin FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates @test FFS.empty_galerkin_result().solver == "none" diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 7ddba18d9f..0b70419e74 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -29,12 +29,11 @@ end x = factor \ rhs raw[row, :] = x[[3, 5]] end - delta = reshape([raw[2, 2] - raw[2, 1] - raw[1, 2] + raw[1, 1]], 1, 1) - return ComplexF64.(delta), ComplexF64.(raw) + return ComplexF64.(raw) end - default = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, nothing, false) - extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(), false) - ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(; algorithm=Riccati(; extended_precision_bvp=false)), false) + default = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, nothing, false) + extended = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(), false) + ordinary = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(; algorithm=Riccati(; extended_precision_bvp=false)), false) @test default == reference @test extended == reference @test ordinary != reference @@ -254,7 +253,7 @@ end function run_solovev(integrator) ctrl, intr, equil, metric, mats = _prepared_solovev(integrator) odet, _, _, _ = GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr) - vac = GeneralizedPerturbedEquilibrium.ForceFreeStates.free_run(odet, ctrl, equil, mats, intr) + vac = GeneralizedPerturbedEquilibrium.ForceFreeStates.free_run((odet.u[:, :, 2] / odet.u[:, :, 1]) ./ equil.psio^2, ctrl, equil, mats, intr) return real(vac.et[1]), intr end diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index 9c1597e563..fd0a9313cb 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -103,13 +103,15 @@ include("h5_metadata_check.jl") @test iszero(ffs.bpen) @test ffs.delta_prime !== nothing - @test size(ffs.delta_prime.matrix) == (length(ffs.surfaces), length(ffs.surfaces)) - @test size(ffs.delta_prime.raw) == (2 * length(ffs.surfaces), 2 * length(ffs.surfaces)) - # Riccati persists only the raw D′ and recovers the parity blocks on demand. - @test ffs.delta_prime.A === nothing - @test ffs.delta_prime.B === nothing - @test ffs.delta_prime.Gamma === nothing - @test ffs.delta_prime.matrix ≈ FFS.pest3_decompose(ffs.delta_prime.raw).Δ + dp = ffs.delta_prime + @test size(dp.raw_freeboundary) == (2 * length(ffs.surfaces), 2 * length(ffs.surfaces)) + @test size(dp.raw_fixedboundary) == size(dp.raw_freeboundary) && dp.raw_fixedboundary != dp.raw_freeboundary + # The PEST-3 blocks of both boundaries are stored, whichever formalism ran. + for (blocks, raw) in ((dp.freeboundary, dp.raw_freeboundary), (dp.fixedboundary, dp.raw_fixedboundary)) + ref = FFS.pest3_decompose(raw) + @test blocks.A ≈ ref.A && blocks.B ≈ ref.B && blocks.Gamma ≈ ref.Gamma && blocks.Delta ≈ ref.Delta + end + @test size(dp.ef) == (2 * length(ffs.surfaces), ffs.numpert_total) @test ffs.free_boundary !== nothing end end @@ -147,9 +149,9 @@ include("h5_metadata_check.jl") end end - # Standalone Galerkin with the RPEC inner-layer match: the matched outer solution becomes - # the result's ξ solution, and the closure records whether an inner layer was matched in. - @testset "matched Galerkin publishes a gal-native solution" begin + # Standalone Galerkin publishes its ideal-closed EF columns as the ξ solution; with the RPEC + # inner-layer match the matched outer solution replaces them, and the closure records which. + @testset "Galerkin publishes a gal-native solution" begin for (deck, ideal) in (("LAR_ideal_match_test", true), ("LAR_resistive_match_test", false)) @testset "$deck" begin mktempdir() do dir @@ -158,7 +160,7 @@ include("h5_metadata_check.jl") @test ffs.integrator === :galerkin @test ffs.galerkin !== nothing - @test ffs.match !== nothing + @test (ffs.match === nothing) == ideal sol = ffs.solution @test sol isa FFS.SolutionProfiles @@ -167,41 +169,37 @@ include("h5_metadata_check.jl") @test !iszero(sol.du_store) # analytic galerkin Ξ′ @test !iszero(sol.xi_s_store) - # Galerkin runs no Euler-Lagrange sweep and computes no free-boundary energies. + # Galerkin runs no Euler-Lagrange sweep; the edge response of its closed columns gives the + # free-boundary energies (vac_flag = true in both decks). @test ffs.diagnostics === nothing - @test ffs.free_boundary === nothing - @test ffs.wp === nothing + @test size(ffs.wp) == (ffs.numpert_total, ffs.numpert_total) + @test ffs.free_boundary !== nothing && ffs.free_boundary.wp == ffs.wp + @test ffs.free_boundary.wt0 ≈ ffs.wp + ffs.free_boundary.wv rtol = 1e-12 # Galerkin publishes its Δ′ through the same unified field the Riccati BVP # uses, in the same PEST-3 convention and the same shared layout. dp = ffs.delta_prime @test dp !== nothing msing = ffs.galerkin.msing - @test size(dp.matrix) == (msing, msing) - @test size(dp.raw) == (2msing, 2msing) - @test dp.matrix ≈ FFS.pest3_decompose(dp.raw).Δ - - # Unlike Riccati, the Galerkin solve persists the remaining parity blocks. - for (blk, ref) in ((dp.A, :A), (dp.B, :B), (dp.Gamma, :Γ)) - @test blk !== nothing - @test size(blk) == (msing, msing) - @test blk ≈ getfield(FFS.pest3_decompose(dp.raw), ref) + for (blocks, raw) in ((dp.freeboundary, dp.raw_freeboundary), (dp.fixedboundary, dp.raw_fixedboundary)) + @test size(raw) == (2msing, 2msing) + ref = FFS.pest3_decompose(raw) + @test blocks.A ≈ ref.A && blocks.B ≈ ref.B && blocks.Gamma ≈ ref.Gamma && blocks.Delta ≈ ref.Delta end - # The rpec coil block is normalized to the Riccati orientation at pack time. - @test size(dp.coil) == (2msing, ffs.numpert_total) - @test !iszero(dp.coil) + # The EF block is normalized to the Riccati orientation at pack time. + @test size(dp.ef) == (2msing, ffs.numpert_total) + @test !iszero(dp.ef) - # The ideal-flag match skips the inner layer, so its basis is ideal-closed. + # Without a match the EF columns are the ideal closure, with a Hermitian δW. if ideal @test ffs.closure === :ideal @test iszero(ffs.bpen) + @test norm(ffs.wp - ffs.wp') <= 1e-8 * norm(ffs.wp) else @test ffs.closure === :matched @test ffs.bpen == ffs.match.bpen @test !iszero(ffs.bpen) - # The ideal δW does not describe the matched plasma. - @test ffs.wp === nothing && ffs.free_boundary === nothing end # The closed profiles land in the shared Solutions layout: same names and @@ -215,16 +213,19 @@ include("h5_metadata_check.jl") @test read(f["$gal/xi_psi"]) == sol.u_store[:, :, 1, :] @test read(f["$gal/dxi_psidpsi"]) == sol.du_store @test read(f["$gal/xi_s"]) == sol.xi_s_store + @test read(f["ForceFreeStates/FreeBoundaryStability/W_plasma"]) == ffs.wp # Matching diagnostics sit with the other per-surface results, and the # raw outer basis is debug-gated off by default. - @test haskey(f, "SingularSurfaces/Match/cout") + @test haskey(f, "SingularSurfaces/Match/cout") != ideal @test !haskey(f, "$gal/Match") - # Match/ is self-describing: rows follow SingularSurfaces/rational_psi, and it names the model that ran. - mg = f["SingularSurfaces/Match"] - @test size(read(mg["bpen"]), 1) == length(read(f["SingularSurfaces/rational_psi"])) - @test read(mg["reconnected_flux"]) == ffs.match.reconnected_flux - @test attrs(mg)["inner_model"] == GeneralizedPerturbedEquilibrium.InnerLayer.model_name(ffs.match.model) - @test isempty(_collect_metadata_violations(mg)) + if !ideal + # Match/ is self-describing: rows follow SingularSurfaces/rational_psi, and it names the model that ran. + mg = f["SingularSurfaces/Match"] + @test size(read(mg["bpen"]), 1) == length(read(f["SingularSurfaces/rational_psi"])) + @test read(mg["reconnected_flux"]) == ffs.match.reconnected_flux + @test attrs(mg)["inner_model"] == GeneralizedPerturbedEquilibrium.InnerLayer.model_name(ffs.match.model) + @test isempty(_collect_metadata_violations(mg)) + end @test !haskey(f, "$gal/Basis") @test !haskey(f, "$gal/Solution") end diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index b3904b9702..d044eb3dcf 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -102,13 +102,13 @@ end # (which overwrites intr_ric.sing[s].delta_prime) delta_prime_inline = [copy(intr_ric.sing[s].delta_prime) for s in 1:intr_ric.msing] - vac_ric = FFS.free_run(odet_ric, ctrl, equil, mats, intr_ric) + vac_ric = FFS.free_run((odet_ric.u[:, :, 2] / odet_ric.u[:, :, 1]) ./ equil.psio^2, ctrl, equil, mats, intr_ric) et_ric = real(vac_ric.et[1]) # Forward integration (needed only for energy comparison). _, intr_fwd, _, _, _ = prepared_solovev() odet_fwd, _, _, _ = FFS.forward_eulerlagrange_integration(ctrl, equil, mats, intr_fwd) - vac_fwd = FFS.free_run(odet_fwd, ctrl, equil, mats, intr_fwd) + vac_fwd = FFS.free_run((odet_fwd.u[:, :, 2] / odet_fwd.u[:, :, 1]) ./ equil.psio^2, ctrl, equil, mats, intr_fwd) et_fwd = real(vac_fwd.et[1]) # ───────────────────────────────────────────────────────────────────────── diff --git a/test/runtests_slayer_runner.jl b/test/runtests_slayer_runner.jl index e3f205cbc7..4c8a9c1fa3 100644 --- a/test/runtests_slayer_runner.jl +++ b/test/runtests_slayer_runner.jl @@ -137,7 +137,7 @@ end # Δ′ is unified across formalisms, so a Galerkin run feeds SLAYER exactly as a Riccati one - # does: `result.delta_prime.matrix` is populated and already sized to the surface list, which + # does: `result.delta_prime.freeboundary` is populated and already sized to the surface list, which # is the predicate the tearing solve uses to accept it over the per-surface diagonal stub. @testset "Galerkin-fed SLAYER: gal Δ' drives the coupled solve" begin mktempdir() do dir @@ -156,7 +156,7 @@ ffs = GeneralizedPerturbedEquilibrium.main([dir]).ffs @test ffs.integrator === :galerkin - dpm = ffs.delta_prime.matrix + dpm = ffs.delta_prime.freeboundary.Delta @test size(dpm) == (length(ffs.surfaces), length(ffs.surfaces)) @test size(dpm, 1) == 2 diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 8dd25a951a..1b343ab4c7 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -75,18 +75,18 @@ using HDF5 @test api.solution === nothing @test api.delta_prime !== nothing msing = length(api.surfaces) - @test size(api.delta_prime.matrix) == (msing, msing) - @test api.delta_prime.matrix ≈ FFS.pest3_decompose(api.delta_prime.raw).Δ + @test size(api.delta_prime.freeboundary.Delta) == (msing, msing) + @test api.delta_prime.freeboundary.Delta ≈ FFS.pest3_decompose(api.delta_prime.raw_freeboundary).Delta # Chunking is a decomposition of the same problem, so Δ′ tracks the TOML run. - @test size(reference.delta_prime.matrix) == size(api.delta_prime.matrix) - @test api.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-6 + @test size(reference.delta_prime.freeboundary.Delta) == size(api.delta_prime.freeboundary.Delta) + @test api.delta_prime.freeboundary.Delta ≈ reference.delta_prime.freeboundary.Delta rtol = 1e-6 # With the deck's own (auto) chunking the two runs are the same computation. same = solve(prob, riccati) - @test same.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-12 - @test same.delta_prime.raw ≈ reference.delta_prime.raw rtol = 1e-12 - @test same.delta_prime.coil ≈ reference.delta_prime.coil rtol = 1e-12 + @test same.delta_prime.freeboundary.Delta ≈ reference.delta_prime.freeboundary.Delta rtol = 1e-12 + @test same.delta_prime.raw_freeboundary ≈ reference.delta_prime.raw_freeboundary rtol = 1e-12 + @test same.delta_prime.ef ≈ reference.delta_prime.ef rtol = 1e-12 end end @@ -191,13 +191,13 @@ using HDF5 @test api.integrator === :galerkin @test api.control.algorithm.nx == 32 @test api.galerkin !== nothing - @test api.free_boundary === nothing # galerkin computes no free-boundary energies + # By default the EF columns and the vacuum give the ideal solution and its free-boundary energies. + @test api.control.algorithm.error_field_response && api.free_boundary !== nothing dp = api.delta_prime @test dp !== nothing msing = api.galerkin.msing - @test size(dp.matrix) == (msing, msing) - @test dp.matrix ≈ FFS.pest3_decompose(dp.raw).Δ - @test dp.A !== nothing # the parity blocks the galerkin solve persists + @test size(dp.fixedboundary.Delta) == (msing, msing) + @test dp.fixedboundary.Delta ≈ FFS.pest3_decompose(dp.raw_fixedboundary).Delta reference = GPEC.main([ @@ -205,10 +205,13 @@ using HDF5 extra_sections=Dict{String,Any}("Galerkin" => Dict{String,Any}("nx" => 32))) ]).ffs @test reference.galerkin.msing == msing - @test dp.matrix ≈ reference.delta_prime.matrix rtol = 1e-12 - @test dp.raw ≈ reference.delta_prime.raw rtol = 1e-12 - # With no free-boundary δW, no plasma response can be built from it. - @test_throws ErrorException plasma_response(api) + @test dp.raw_fixedboundary ≈ reference.delta_prime.raw_fixedboundary rtol = 1e-12 + @test dp.raw_freeboundary ≈ reference.delta_prime.raw_freeboundary rtol = 1e-12 + # Without the EF columns there is no free-boundary δW to build a plasma response from. + noef = solve(equil, Galerkin(; nx=32, error_field_response=false); nn=1, wall=wall, ffs_kwargs...) + @test noef.free_boundary === nothing && noef.solution === nothing && isempty(noef.delta_prime.ef) + @test noef.delta_prime.raw_freeboundary == dp.raw_freeboundary + @test_throws ErrorException plasma_response(noef) end end @@ -355,7 +358,7 @@ using HDF5 @testset "solves leave their inputs untouched" begin snap = deepcopy(equil) mktempdir() do dir - gal = solve(equil, Galerkin(; nx=32, rpec_flag=true, cut_solution=true); nn=1, ffs_kwargs...) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true, cut_solution=true); nn=1, ffs_kwargs...) @test first_diff(equil, snap) === nothing # Matching reuses the outer solve: repeated match solves must not alter it. gal_snap = deepcopy(gal) @@ -370,7 +373,7 @@ using HDF5 end @testset "MatchProblem defaults its layer inputs from the kinetic data" begin - gal = solve(equil, Galerkin(; nx=32, rpec_flag=true, cut_solution=true); nn=1, ffs_kwargs...) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true, cut_solution=true); nn=1, ffs_kwargs...) # Without kinetic data the error names exactly the inputs still to give. @test_throws "MatchProblem: give eta, rho and rotation, or load kinetic profiles" MatchProblem(gal) @test_throws "MatchProblem: give rho, or load kinetic profiles" MatchProblem(gal; eta=1e-7, rotation=1.0) @@ -405,7 +408,7 @@ using HDF5 @testset "matched inner profiles: opt-in, and parity columns agree across inner models" begin mktempdir() do dir - gal = solve(equil, Galerkin(; nx=32, rpec_flag=true, cut_solution=true); nn=1, ffs_kwargs...) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true, cut_solution=true); nn=1, ffs_kwargs...) prob = MatchProblem(gal; eta=1e-7, rho=1e-7, rotation=1.0) center = solve(prob, GGJModel()).match ray = solve(prob, GGJModel(; real_profiles=true)).match @@ -429,7 +432,7 @@ using HDF5 @testset "a resistive match keeps its coefficients and drops the ideal δW" begin mktempdir() do dir ric = solve(equil, riccati; nn=1, ffs_kwargs...) - @test ric.free_boundary !== nothing && !isempty(ric.delta_prime.coil) + @test ric.free_boundary !== nothing && !isempty(ric.delta_prime.ef) matched = solve(MatchProblem(ric; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel()) @test matched.closure === :matched @test matched.match !== nothing && matched.bpen == matched.match.bpen @@ -438,7 +441,7 @@ using HDF5 # It carries no ideal δW, so no plasma response can be built from it. @test_throws ErrorException plasma_response(matched) # A matched result is a new solution, not an outer solve to match again. - @test_throws ErrorException MatchProblem(matched; ideal=true) + @test_throws ErrorException MatchProblem(matched; eta=1e-7, rho=1e-7, rotation=1.0) end end @@ -446,24 +449,62 @@ using HDF5 mktempdir() do dir # A Forward result carries no Δ′ payload, so the problem is unconstructible. fwd = solve(equil, forward; nn=1, ffs_kwargs...) - @test_throws ErrorException MatchProblem(fwd; ideal=true) + @test_throws ErrorException MatchProblem(fwd; eta=1e-7, rho=1e-7, rotation=1.0) # A slab model can never close a matched solution. - gal = solve(equil, Galerkin(; nx=32, rpec_flag=true); nn=1, ffs_kwargs...) - prob = MatchProblem(gal; ideal=true) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true); nn=1, ffs_kwargs...) + prob = MatchProblem(gal; eta=1e-7, rho=1e-7, rotation=1.0) @test_throws ErrorException solve(prob, SLAYERModel()) # A resistive match needs every layer input. @test_throws "give rho and rotation" MatchProblem(gal; eta=1e-7) @test_throws ErrorException MatchProblem(gal; eta=fill(1e-7, length(gal.surfaces) + 1), rho=1e-7, rotation=1.0) # The tearing model is the solve argument, never a TearingProblem keyword. @test_throws MethodError TearingProblem(gal; inner_model=:ggj_ray) - # The ideal reference match keeps the ideal closure and replaces the solution with - # the bare coil columns in the identity-at-edge basis. + # The Galerkin solve is itself ideal-closed: its EF columns, identity at the edge, with their δW. + @test gal.closure === :ideal + @test gal.solution !== nothing && gal.solution.basis === :gal_native + N = gal.numpert_total + @test gal.solution.u_store[:, :, 1, end] ≈ Matrix{ComplexF64}(I, N, N) atol = 1e-10 + @test size(gal.wp) == (N, N) && norm(gal.wp - gal.wp') <= 1e-8 * norm(gal.wp) + # A matched Galerkin result keeps the identity-at-edge basis and publishes its complex edge response. matched = solve(prob, GGJModel()) - @test matched.closure === :ideal - @test matched.match !== nothing - # The ideal reference keeps the ideal δW (only a :matched closure drops it). - @test matched.wp === gal.wp && matched.free_boundary === gal.free_boundary - @test matched.solution !== nothing && matched.solution.basis === :gal_native + @test matched.closure === :matched + @test matched.solution.u_store[:, :, 1, end] ≈ Matrix{ComplexF64}(I, N, N) atol = 1e-10 + ψ₀² = gal.equil.psio^2 + F = gal.galerkin.edge_response + @test matched.wp ≈ gal.wp + F[:, 1:(2length(gal.surfaces))] * matched.match.cout / ψ₀² rtol = 1e-12 + # Its free-boundary energies use the matched response with the solve's own vacuum. + @test matched.free_boundary.wt0 ≈ matched.wp + gal.free_boundary.wv rtol = 1e-12 + # The singular coupling of a matched solution is not defined yet. + @test_throws "matched" plasma_response(matched) + # The EF columns do not change either Δ′: both equal those of a solve without them. + plain = solve(equil, Galerkin(; nx=32, error_field_response=false); nn=1, ffs_kwargs...) + @test gal.delta_prime.raw_freeboundary == plain.delta_prime.raw_freeboundary + @test gal.delta_prime.raw_fixedboundary == plain.delta_prime.raw_fixedboundary + @test gal.delta_prime.raw_fixedboundary != gal.delta_prime.raw_freeboundary + # Skipping the free-boundary solve leaves only the fixed-boundary Δ′: matching is unchanged, and tearing + # runs on the fixed boundary only when asked to. + nofree = solve(equil, Galerkin(; nx=32, error_field_response=true, free_boundary_delta_prime=false); nn=1, ffs_kwargs...) + @test isempty(nofree.delta_prime.raw_freeboundary) && nofree.delta_prime.freeboundary === nothing + @test nofree.delta_prime.raw_fixedboundary == gal.delta_prime.raw_fixedboundary && nofree.delta_prime.ef == gal.delta_prime.ef + @test solve(MatchProblem(nofree; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel()).match.cout == matched.match.cout + @test_throws "free-boundary Δ′" solve(TearingProblem(nofree), SLAYERModel()) + end + end + + @testset "a Galerkin solve drives the plasma response like a forward solve" begin + mktempdir() do dir + fwd = solve(equil, forward; nn=1, ffs_kwargs...) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true); nn=1, ffs_kwargs...) + @test gal.psilim == fwd.psilim + @test gal.wp ≈ fwd.wp rtol = 1e-5 + @test gal.free_boundary.wt0 ≈ gal.wp + gal.free_boundary.wv rtol = 1e-12 + @test gal.free_boundary.et[1] ≈ fwd.free_boundary.et[1] rtol = 1e-5 + # The edge permeability P = Λ·L⁻¹ does not depend on the solution basis. + @test plasma_response(gal).permeability_flux ≈ plasma_response(fwd).permeability_flux rtol = 5e-4 + # Without the vacuum there is no free-boundary δW to build Λ from. + novac = solve(equil, Galerkin(; nx=32, error_field_response=true); nn=1, merge(ffs_kwargs, Dict{Symbol,Any}(:vac_flag => false))...) + @test novac.wp !== nothing && novac.free_boundary === nothing + @test_throws "vac_flag=true" plasma_response(novac) end end @@ -516,11 +557,11 @@ using HDF5 "Match" => Dict{String,Any}("eta" => fill(layer.eta, n), "rho" => fill(layer.rho, n), "rotation" => fill(layer.rotation, n))) mktempdir() do dir - gal = solve(equil, Galerkin(; nx=32, rpec_flag=true); nn=1, wall=wall, ffs_kwargs...) + gal = solve(equil, Galerkin(; nx=32, error_field_response=true); nn=1, wall=wall, ffs_kwargs...) # The galerkin inner model returns real-ψ profiles, so the inner profiles are compared too. api = solve(MatchProblem(gal; layer...), GGJModel(; solver=:galerkin)) n = length(gal.surfaces) - sections = merge(Dict{String,Any}("Galerkin" => Dict{String,Any}("nx" => 32, "rpec_flag" => true)), match_sections(n, "galerkin")) + sections = merge(Dict{String,Any}("Galerkin" => Dict{String,Any}("nx" => 32, "error_field_response" => true)), match_sections(n, "galerkin")) reference = GPEC.main([_stage_deck(dir; ffs_overrides=Dict{String,Any}("integrator" => "Galerkin"), extra_sections=sections)]).ffs @test reference.closure === api.closure === :matched @@ -529,7 +570,7 @@ using HDF5 @test api.match.xi ≈ reference.match.xi rtol = 1e-12 # The composite inner profiles need the cut solution, which Galerkin keeps only on request. @test isempty(reference.match.inner_xi) && isempty(api.match.inner_xi) - cut = solve(equil, Galerkin(; nx=32, rpec_flag=true, cut_solution=true); nn=1, wall=wall, ffs_kwargs...) + cut = solve(equil, Galerkin(; nx=32, error_field_response=true, cut_solution=true); nn=1, wall=wall, ffs_kwargs...) @test length(solve(MatchProblem(cut; layer...), GGJModel(; solver=:galerkin)).match.inner_xi) == n end @@ -546,7 +587,7 @@ using HDF5 # A forward solve has no Δ′ to match against, so the deck stops at parse time instead of after the solve. mktempdir() do dir - deck_dir = _stage_deck(dir; extra_sections=Dict{String,Any}("Match" => Dict{String,Any}("ideal" => true))) + deck_dir = _stage_deck(dir; extra_sections=Dict{String,Any}("Match" => Dict{String,Any}("eta" => 1e-7, "rho" => 1e-7, "rotation" => 1.0))) @test_throws "[Match] needs Δ′" GPEC.parse_deck(TOML.parsefile(joinpath(deck_dir, "gpec.toml")), deck_dir) end From f2f0befe8e50bca6fbaf50eef53513900b0e94a4 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Fri, 6 Nov 2026 11:28:38 +0100 Subject: [PATCH 02/27] ForceFreeStates.Matching - FEATURE! - Publish the matched plasma energy matrix for Riccati matches --- docs/development/hdf5-conventions.md | 2 +- docs/src/api.md | 2 +- docs/src/galerkin.md | 2 +- docs/src/stability.md | 2 +- src/ForceFreeStates/CoreTypes.jl | 4 ++- src/ForceFreeStates/Galerkin/GalerkinSolve.jl | 2 +- src/ForceFreeStates/Matching/DeltaPrime.jl | 9 ++++-- src/ForceFreeStates/Matching/MatchProblem.jl | 17 ++++++----- src/ForceFreeStates/Output.jl | 1 + src/ForceFreeStates/Result.jl | 13 +++------ src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 28 +++++++++++-------- src/Utilities/HDF5Schema.jl | 3 ++ test/runtests_parallel_integration.jl | 6 ++-- test/runtests_result_struct.jl | 2 ++ test/runtests_solve_api.jl | 12 +++++--- 15 files changed, 62 insertions(+), 43 deletions(-) diff --git a/docs/development/hdf5-conventions.md b/docs/development/hdf5-conventions.md index c91493f811..7ec9aa01c6 100644 --- a/docs/development/hdf5-conventions.md +++ b/docs/development/hdf5-conventions.md @@ -42,7 +42,7 @@ Top level (11 groups): | `Equilibrium/` | Scalars (`beta_N`, `q_axis`, `q_95`, `I_p`, …) plus `Profiles/` (1-D on `psi`: 2piF, mu0p, dVdpsi, q) and `Geometry/` (2-D on `psi`×`theta`: rcoords, offset, nu, jac) | | `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (closed ξ profiles in the shared layout, the gal surface list, `gal_basis_output`-gated `Basis/`), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | -| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_raw_freeboundary`/`Delta_prime_raw_fixedboundary`/`Delta_EF`, the free-boundary `Delta_prime_matrix`/`pest3_A`/`pest3_B`/`pest3_Gamma` and their `_fixedboundary` counterparts (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | +| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_raw_freeboundary`/`Delta_prime_raw_fixedboundary`/`Delta_EF`/`edge_response`, the free-boundary `Delta_prime_matrix`/`pest3_A`/`pest3_B`/`pest3_Gamma` and their `_fixedboundary` counterparts (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | | `PerturbedEquilibrium/` | `ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | | `KineticForces/` | `/` (torque/energy profiles, `dTdpsi_ell` resolved by bounce harmonic on the `ell` scale, `KineticMatrices/`); multi-ion runs add `PerSpecies///` with the same per-method layout, summing to the top-level total | | `ErrorFields/` | `CoilSensitivities/` (per-coil-set control-surface spectra and their rigid shift/tilt derivatives, `DominantMode/` full-window projection); `MonteCarlo/` (intrinsic and corrected `\|δ\|` histograms over the sampled tolerances, per batch and averaged); `Risk/` (threshold density, `P(lock\|δ)`, locking probabilities, `ToleranceScan/`); `NTV/` (correction-coil overlap and NTV torque couplings per kAt) | diff --git a/docs/src/api.md b/docs/src/api.md index 895be534c4..e9a9a3de22 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -100,7 +100,7 @@ bpens = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).bp ``` A scalar applies to every surface and a vector gives one value per entry of `ffs.surfaces`, core to edge. -The problem needs a Δ′ payload with error-field (EF) columns, so it accepts Galerkin and Riccati results with `error_field_response=true` (the default; Riccati also needs `vac_flag=true`); a Riccati-fed match fills `bpen` and the resonant data but keeps `solution === nothing`. +The problem needs a Δ′ payload with error-field (EF) columns, so it accepts Galerkin and Riccati results with `error_field_response=true` (the default; Riccati also needs `vac_flag=true`); a Riccati-fed match fills `bpen`, the resonant data and the matched `wp` but keeps `solution === nothing`. `GGJModel()` is the closure-capable model; `SLAYERModel()` is slab-only and drives the tearing solve instead. ## Tearing stability diff --git a/docs/src/galerkin.md b/docs/src/galerkin.md index 52778708e5..4f559e791a 100644 --- a/docs/src/galerkin.md +++ b/docs/src/galerkin.md @@ -37,7 +37,7 @@ A `[Match]` section matches the inner layer to its Δ′ and replaces them with | Dataset | Meaning | |---|---| | `SingularSurfaces/Delta_prime_matrix` | the Δ′ matrix in the PEST-3 convention, on the same path as the Riccati result, so downstream stages never branch on which formalism ran; free-boundary with `vac_flag = true` (with `error_field_response = true` a second factorization re-solves the big-solution columns with the vacuum edge, so the EF columns never enter it; `free_boundary_delta_prime = false` skips it for matching-only scans, leaving no tearing Δ′) and fixed-boundary otherwise | -| `SingularSurfaces/Delta_prime_raw_freeboundary`, `Delta_prime_raw_fixedboundary`, `Delta_EF` | the side-major matching matrices with the vacuum and the fixed edge, and the error-field (EF) response (`error_field_response = true`) | +| `SingularSurfaces/Delta_prime_raw_freeboundary`, `Delta_prime_raw_fixedboundary`, `Delta_EF`, `edge_response` | the side-major matching matrices with the vacuum and the fixed edge, the error-field (EF) response (`error_field_response = true`), and the edge momentum of each fixed-edge big-solution column | | `SingularSurfaces/pest3_A`, `pest3_B`, `pest3_Gamma` (and `_fixedboundary`) | the PEST-3 interchange and mixed blocks ``A'``, ``B'``, ``\Gamma'`` | | `ForceFreeStates/Solutions/GalerkinIntegration/` | the closed ``\xi`` profiles on the Galerkin grid, the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | | `ForceFreeStates/FreeBoundaryStability/` | `W_plasma`, the plasma energy matrix ``W_P`` of the closed solution (`error_field_response = true`), and with `vac_flag = true` the vacuum and free-boundary energies and eigenmodes as for a `"Forward"` solve | diff --git a/docs/src/stability.md b/docs/src/stability.md index 706b89725d..87f9adcc22 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -103,7 +103,7 @@ The number of Julia threads is set at startup (`-t N` or `JULIA_NUM_THREADS`); t | `SingularSurfaces/rational_psi`, `rational_q`, `rational_m`, `rational_n`, `dqdpsi` | the rational surfaces of the domain, core to edge | | `SingularSurfaces/D_I`, `E`, `F`, `G`, `H`, `K`, `M` | the Mercier index and the Glasser–Greene–Johnson layer coefficients at each surface | | `SingularSurfaces/ca_left`, `ca_right` | the asymptotic (large, small) coefficients on either side of each surface, from ideal crossings | -| `SingularSurfaces/Delta_prime_matrix` | the free-boundary Δ′ matrix in the PEST-3 convention, from `"Riccati"` or `"Galerkin"`, with `pest3_A`, `pest3_B`, `pest3_Gamma`; `Delta_prime_raw_freeboundary` is the side-major (left, right) matrix they are folded from. The same set with a `_fixedboundary` suffix is the Δ′ with a conformal wall on the plasma, and `Delta_EF` the error-field response | +| `SingularSurfaces/Delta_prime_matrix` | the free-boundary Δ′ matrix in the PEST-3 convention, from `"Riccati"` or `"Galerkin"`, with `pest3_A`, `pest3_B`, `pest3_Gamma`; `Delta_prime_raw_freeboundary` is the side-major (left, right) matrix they are folded from. The same set with a `_fixedboundary` suffix is the Δ′ with a conformal wall on the plasma, `Delta_EF` the error-field response, and `edge_response` the edge momentum of each fixed-boundary big-solution column (what matching needs for the matched `W_plasma`) | | `SingularSurfaces/Kinetic/` | the surfaces of a kinetic solve | The energy matrices are power-normalized: the eigenmode energies are the generalized eigenvalues of the pencil ``W v = \lambda N v``, with ``N`` the surface-norm matrix ``\xi^\dagger N \xi = \langle|\xi|^2\rangle`` built from the Jacobian Fourier coefficients, so each is an energy per unit surface-averaged squared displacement rather than joules, and the spectrum is invariant to the working coordinate because ``W`` and ``N`` transform by the same congruence. diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 325251ff6f..433cb4ec83 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -61,11 +61,13 @@ Solve-time scratch state for a force-balance solve: the resolved mode space, sin verbose::Bool = false """ Riccati Δ' BVP results (`compute_delta_prime_matrix!`): raw side-major `2msing × 2msing` D' with the vacuum edge - and with ξ(edge) = 0, and Δ_EF (`2msing × numpert_total`). Empty when not computed. + and with ξ(edge) = 0, Δ_EF (`2msing × numpert_total`), and the edge momentum of the ξ(edge) = 0 solutions + (`numpert_total × 2msing`). Empty when not computed. """ delta_prime_raw_freeboundary::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) delta_prime_raw_fixedboundary::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) delta_ef::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) + delta_prime_edge_response::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) end """ diff --git a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl index d03e977d76..6b7eea41d2 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl @@ -204,7 +204,7 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines # wv is singfac-scaled at qlim; the Galerkin edge term is wv·ψ₀². raw_free = gal_small_coefficients(ws, gal_vacuum_edge_solve(ws, edge_mat, Matrix{ComplexF64}(wv .* equil.psio^2), mpert)) end - dp = DeltaPrimeData(raw_free, raw_fixed, ef) + dp = DeltaPrimeData(raw_free, raw_fixed, ef, edge_response[:, 1:(2msing)]) sing_psi = [s.psifac for s in sings] sing_q = [s.q for s in sings] diff --git a/src/ForceFreeStates/Matching/DeltaPrime.jl b/src/ForceFreeStates/Matching/DeltaPrime.jl index 9c594a613c..69628a7722 100644 --- a/src/ForceFreeStates/Matching/DeltaPrime.jl +++ b/src/ForceFreeStates/Matching/DeltaPrime.jl @@ -34,7 +34,7 @@ function pest3_decompose(raw::AbstractMatrix{ComplexF64}) end """ - DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef) + DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef, edge_response) The solve's Δ′/outer-region matching payload. Matrices are indexed by the surfaces the formalism solved across, core→edge; side-major orderings run `[L_s1, R_s1, L_s2, R_s2, …]`. An empty matrix (or `nothing`) @@ -47,6 +47,8 @@ means the solve did not compute it. The PEST-3 blocks are built from the raw mat - `ef::Matrix{ComplexF64}` - Error-field response Δ_EF (2msing × numpert_total): column k is the small-solution coefficient at each surface side for a unit edge displacement in mode k with the edge otherwise fixed. It pairs with `raw_fixedboundary` in matching. + - `edge_response::Matrix{ComplexF64}` - Edge momentum Fξ′ + Kξ (numpert_total × 2msing) of the `raw_fixedboundary` + solutions: column k has unit big-solution coefficient on surface side k and ξ(edge) = 0. - `freeboundary::Union{Nothing,PEST3Blocks}` - PEST-3 blocks of `raw_freeboundary`. - `fixedboundary::Union{Nothing,PEST3Blocks}` - PEST-3 blocks of `raw_fixedboundary`. """ @@ -54,11 +56,12 @@ struct DeltaPrimeData raw_freeboundary::Matrix{ComplexF64} raw_fixedboundary::Matrix{ComplexF64} ef::Matrix{ComplexF64} + edge_response::Matrix{ComplexF64} freeboundary::Union{Nothing,PEST3Blocks} fixedboundary::Union{Nothing,PEST3Blocks} end -DeltaPrimeData(raw_freeboundary::AbstractMatrix, raw_fixedboundary::AbstractMatrix, ef::AbstractMatrix) = - DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef, +DeltaPrimeData(raw_freeboundary::AbstractMatrix, raw_fixedboundary::AbstractMatrix, ef::AbstractMatrix, edge_response::AbstractMatrix) = + DeltaPrimeData(raw_freeboundary, raw_fixedboundary, ef, edge_response, isempty(raw_freeboundary) ? nothing : pest3_decompose(raw_freeboundary), isempty(raw_fixedboundary) ? nothing : pest3_decompose(raw_fixedboundary)) diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index 76b5c18597..eb783aacf1 100644 --- a/src/ForceFreeStates/Matching/MatchProblem.jl +++ b/src/ForceFreeStates/Matching/MatchProblem.jl @@ -91,10 +91,9 @@ closure_capable(::InnerLayer.SLAYERModel) = false solve(prob::MatchProblem, model) -> ForceFreeStatesResult Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched`, `bpen`, the -[`MatchResult`](@ref) in `result.match` and, for a Galerkin solve, the matched ξ, its edge response -`wp` (see [`ForceFreeStatesResult`](@ref)) and, when the solve had `vac_flag`, the free-boundary energies -of that response. A Riccati-fed match drops `wp` and `free_boundary`, so PerturbedEquilibrium refuses -it rather than mixing ideal and matched physics. +[`MatchResult`](@ref) in `result.match`, the matched edge response `wp` (see [`ForceFreeStatesResult`](@ref)) +and, when the solve had `vac_flag`, the free-boundary energies of that response. A Galerkin solve also gives +the matched ξ. """ function CommonSolve.solve(prob::MatchProblem, model::InnerLayer.InnerLayerModel) closure_capable(model) || @@ -262,11 +261,15 @@ end function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult) gal = ffs.galerkin solution = nothing - wp = nothing - free_boundary = nothing if gal !== nothing && gal.solution !== nothing && !isempty(match.xi) solution = _gal_profiles(gal.solution, match.xi, match.xi_deriv, ffs.mats, ffs) - wp = gal_wp(gal, ffs.equil.psio; cout=match.cout) + end + # Matched edge momentum: the ideal EF response plus the big-solution columns weighted by cout. + wp = nothing + free_boundary = nothing + dp = ffs.delta_prime + if ffs.wp !== nothing && !isempty(dp.edge_response) + wp = ffs.wp + dp.edge_response * match.cout ./ ffs.equil.psio^2 ffs.free_boundary === nothing || (free_boundary = free_run(wp, ffs.control, ffs.equil, ffs.mats, ffs)) end return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, wp=wp, free_boundary=free_boundary) diff --git a/src/ForceFreeStates/Output.jl b/src/ForceFreeStates/Output.jl index da3c400165..0beea4dea5 100644 --- a/src/ForceFreeStates/Output.jl +++ b/src/ForceFreeStates/Output.jl @@ -185,6 +185,7 @@ function save_to_hdf5( isempty(dp.raw_fixedboundary) || (out_h5["$ss/Delta_prime_raw_fixedboundary"] = dp.raw_fixedboundary) # Δ_EF stored (edge mode × surface-side) so H5Web heatmaps read x = edge mode. isempty(dp.ef) || (out_h5["$ss/Delta_EF"] = permutedims(dp.ef)) + isempty(dp.edge_response) || (out_h5["$ss/edge_response"] = dp.edge_response) for (blocks, suffix) in ((dp.freeboundary, ""), (dp.fixedboundary, "_fixedboundary")) blocks === nothing && continue out_h5["$ss/Delta_prime_matrix$suffix"] = blocks.Delta diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index 4c0865e203..ef70273775 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -59,7 +59,7 @@ is ideal-closed by its EF columns (`error_field_response`), and is unclosed with - `kinetic::NamedTuple` - Kinetic singular-surface scan (`kmsing`, `kinsing`, `scan_psi`, `scan_cond`, `scan_threshold`); empty unless the finder ran. - `closure::Symbol` - How the basis is closed at the rationals: `:ideal` (the ideal jump condition was imposed) or `:matched` (an inner-layer solution was matched in). A matched - Galerkin result carries the matched edge response as `wp`; a matched Riccati result none. + result carries the matched edge response as `wp`. - `bpen::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated resonant field from the inner layer, per surface (rows follow `surfaces`) and driving mode; all zeros under `:ideal` closure. - `match::Union{Nothing,MatchResult}` - The [`MatchResult`](@ref) of a `MatchProblem` solve; `nothing` otherwise. @@ -150,13 +150,8 @@ end # Columns of the Galerkin error-field (EF) drives (error_field_response). gal_ef_columns(gal::GalerkinResult) = (2gal.msing+1):size(gal.edge_response, 2) -# Plasma energy matrix W_P of the ideal (no `cout`) or matched Galerkin solution, in the units of `(U₂·U₁⁻¹)/ψ₀²`. -function gal_wp(gal::GalerkinResult, psio::Float64; cout::Union{Nothing,Matrix{ComplexF64}}=nothing) - F = gal.edge_response - W = F[:, gal_ef_columns(gal)] - cout === nothing || mul!(W, @view(F[:, 1:(2gal.msing)]), cout, true, true) - return W ./ psio^2 -end +# Plasma energy matrix W_P of the Galerkin EF columns, in the units of `(U₂·U₁⁻¹)/ψ₀²`. +gal_wp(gal::GalerkinResult, psio::Float64) = gal.edge_response[:, gal_ef_columns(gal)] ./ psio^2 # `SolutionProfiles` of closed Galerkin columns `xi`, `xi_deriv` (npert, ngrid, ncol) on the grid of `sol`, without on-surface points. function _gal_profiles(sol::GalerkinSolution, xi::AbstractArray{ComplexF64,3}, xi_deriv::AbstractArray{ComplexF64,3}, mats::MatrixSplines, @@ -232,7 +227,7 @@ function build_result( delta_prime = if gal_dp !== nothing gal_dp elseif !isempty(intr.delta_prime_raw_freeboundary) || !isempty(intr.delta_prime_raw_fixedboundary) - DeltaPrimeData(intr.delta_prime_raw_freeboundary, intr.delta_prime_raw_fixedboundary, intr.delta_ef) + DeltaPrimeData(intr.delta_prime_raw_freeboundary, intr.delta_prime_raw_fixedboundary, intr.delta_ef, intr.delta_prime_edge_response) else nothing end diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index 0aca3b5182..fe74aaac2d 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -101,15 +101,18 @@ function compute_delta_prime_matrix!( @info "Δ' BVP: nMat=$nMat, rank(M)=$(rank(M)), cond(M)=$(@sprintf("%.2e", cond(M)))" end - raw = _solve_bvp_raw(M, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) + # With a conducting-wall edge the edge unknowns are U₂(edge) of each big-solution drive. + raw, edge = _solve_bvp_raw(M, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) if wv === nothing intr.delta_prime_raw_fixedboundary = raw + intr.delta_prime_edge_response = edge else intr.delta_prime_raw_freeboundary = raw # The fixed edge and the EF block need the S-axis row layout of the edge rows. if use_S_axis Mc = _fixed_edge_bvp(M, msing, N, col_edge) - intr.delta_prime_raw_fixedboundary = _solve_bvp_raw(Mc, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) + intr.delta_prime_raw_fixedboundary, intr.delta_prime_edge_response = + _solve_bvp_raw(Mc, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) (ctrl === nothing || ctrl.algorithm.error_field_response) && (intr.delta_ef = _solve_bvp_edge_ef(Mc, msing, N, ipert_all)) end end @@ -388,14 +391,15 @@ function _assemble_bvp_S_axis(uShootR::Vector{Matrix{ComplexF64}}, return M, nMat, col_edge end -# The S-axis BVP matrix `M` with its Eq. (38) vacuum-edge rows [Glasser-Kolemen 2018 PoP 25, 032501] replaced by a -# Dirichlet edge, whose edge coefficients equal the right-hand side (0 for the fixed-boundary D′). +# The S-axis BVP matrix `M` with its Eq. (38) vacuum-edge rows [Glasser-Kolemen 2018 PoP 25, 032501] replaced by the +# conducting-wall edge of the `wv = nothing` assembly: U₁(edge) equals the right-hand side of the first N edge rows +# (0 for the fixed-boundary D′) and the edge unknowns hold U₂(edge). function _fixed_edge_bvp(M::Matrix{ComplexF64}, msing::Int, N::Int, col_edge) nMat = size(M, 1) - bot = (nMat-2msing-N+1):(nMat-2msing) + edge_rows = (nMat-2msing-2N+1):(nMat-2msing) Mc = copy(M) - Mc[bot, :] .= 0 - Mc[bot, col_edge] .= I(N) + Mc[edge_rows, col_edge] .= 0 + Mc[edge_rows[(N+1):end], col_edge] .= -I(N) return Mc end @@ -403,9 +407,9 @@ end # unit edge displacement in each poloidal mode. function _solve_bvp_edge_ef(Mc::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}) nMat = size(Mc, 1) - bot = (nMat-2msing-N+1):(nMat-2msing) + u1_rows = (nMat-2msing-2N+1):(nMat-2msing-N) B = zeros(ComplexF64, nMat, N) - B[bot, :] .= I(N) # unit drive, one column per edge poloidal mode + B[u1_rows, :] .= I(N) # unit edge displacement, one column per edge poloidal mode X = lu(Mc) \ B delta_ef = zeros(ComplexF64, 2msing, N) for j in 1:msing @@ -470,7 +474,7 @@ function _assemble_bvp_FM_axis(Phi_L_mats::Vector{Matrix{ComplexF64}}, return M, nMat, col_edge end -# Solve the BVP for the raw side-major D′ (2·msing × 2·msing). +# Solve the BVP for the raw side-major D′ (2·msing × 2·msing) and the edge unknowns of each drive (N × 2·msing). function _solve_bvp_raw(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, use_S_axis::Bool, ipert_all::Vector{Int}, col_edge, ctrl, debug::Bool) @@ -485,6 +489,7 @@ function _solve_bvp_raw(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, end dp_raw = zeros(Tc, s2, s2) + edge = zeros(Tc, N, s2) b = zeros(Tc, nMat) for jsing in 1:msing, side in 1:2 dRow = 2jsing - (2 - side) @@ -501,10 +506,11 @@ function _solve_bvp_raw(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, dp_raw[dRow, 2ksing-1] = x[_col_left(ksing, N)[ipert_k+N]] dp_raw[dRow, 2ksing] = x[_col_right(ksing, N)[ipert_k+N]] end + edge[:, dRow] .= x[col_edge] end debug && _log_bvp_pest3(dp_raw, pest3_decompose(ComplexF64.(dp_raw)).Delta, s2, msing) - return ComplexF64.(dp_raw) + return ComplexF64.(dp_raw), ComplexF64.(edge) end # Logging helpers for `compute_delta_prime_matrix!`. Called only when debug=true. diff --git a/src/Utilities/HDF5Schema.jl b/src/Utilities/HDF5Schema.jl index 8fb5ce2cba..1c13ff357a 100644 --- a/src/Utilities/HDF5Schema.jl +++ b/src/Utilities/HDF5Schema.jl @@ -251,6 +251,9 @@ const MAIN_H5_ANNOTATIONS = [ dims=("surface_side_row", "surface_side_col")), "SingularSurfaces/Delta_EF" => (; long_name="error-field response Δ_EF: small-solution coefficient per unit edge displacement (edge mode × surface-side)", dims=("mode", "surface_side")), + "SingularSurfaces/edge_response" => + (; long_name="edge momentum Fξ′+Kξ of the fixed-edge solution with a unit big-solution coefficient on each surface side (edge mode × surface-side)", + dims=("mode", "surface_side")), "SingularSurfaces/Delta_prime_matrix" => (; long_name="free-boundary Δ' matrix (PEST-3 tearing↔tearing block)", dims=("surface_row", "surface_col")), "SingularSurfaces/pest3_A" => (; long_name="free-boundary PEST-3 block A' (interchange↔interchange)", dims=("surface_row", "surface_col")), "SingularSurfaces/pest3_B" => (; long_name="free-boundary PEST-3 block B' (interchange↔tearing)", dims=("surface_row", "surface_col")), diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 0b70419e74..f7cba83d96 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -31,9 +31,9 @@ end end return ComplexF64.(raw) end - default = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, nothing, false) - extended = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(), false) - ordinary = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(; algorithm=Riccati(; extended_precision_bvp=false)), false) + default = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], 6:6, nothing, false)[1] + extended = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], 6:6, FFS.ForceFreeStatesControl(), false)[1] + ordinary = FFS._solve_bvp_raw(M, 1, 1, 6, false, [1], 6:6, FFS.ForceFreeStatesControl(; algorithm=Riccati(; extended_precision_bvp=false)), false)[1] @test default == reference @test extended == reference @test ordinary != reference diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index fd0a9313cb..bdc76dbc6b 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -112,6 +112,7 @@ include("h5_metadata_check.jl") @test blocks.A ≈ ref.A && blocks.B ≈ ref.B && blocks.Gamma ≈ ref.Gamma && blocks.Delta ≈ ref.Delta end @test size(dp.ef) == (2 * length(ffs.surfaces), ffs.numpert_total) + @test size(dp.edge_response) == (ffs.numpert_total, 2 * length(ffs.surfaces)) && !iszero(dp.edge_response) @test ffs.free_boundary !== nothing end end @@ -190,6 +191,7 @@ include("h5_metadata_check.jl") # The EF block is normalized to the Riccati orientation at pack time. @test size(dp.ef) == (2msing, ffs.numpert_total) @test !iszero(dp.ef) + @test dp.edge_response == ffs.galerkin.edge_response[:, 1:(2msing)] # Without a match the EF columns are the ideal closure, with a Hermitian δW. if ideal diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 1b343ab4c7..801932a0f9 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -429,17 +429,21 @@ using HDF5 end end - @testset "a resistive match keeps its coefficients and drops the ideal δW" begin + @testset "a Riccati match keeps its coefficients and publishes its matched edge response" begin mktempdir() do dir ric = solve(equil, riccati; nn=1, ffs_kwargs...) @test ric.free_boundary !== nothing && !isempty(ric.delta_prime.ef) matched = solve(MatchProblem(ric; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel()) @test matched.closure === :matched @test matched.match !== nothing && matched.bpen == matched.match.bpen - @test matched.wp === nothing && matched.free_boundary === nothing @test matched.solution === nothing # no Galerkin basis to build a matched ξ from - # It carries no ideal δW, so no plasma response can be built from it. - @test_throws ErrorException plasma_response(matched) + # The edge response is W_P plus the big-solution edge momenta weighted by cout; the layers make it non-Hermitian. + ψ₀² = ric.equil.psio^2 + @test matched.wp ≈ ric.wp + ric.delta_prime.edge_response * matched.match.cout / ψ₀² rtol = 1e-12 + @test norm(matched.wp - matched.wp') > 1e-8 * norm(matched.wp) + @test matched.free_boundary.wt0 ≈ matched.wp + ric.free_boundary.wv rtol = 1e-12 + # The singular coupling of a matched solution is not defined yet. + @test_throws "matched" plasma_response(matched) # A matched result is a new solution, not an outer solve to match again. @test_throws ErrorException MatchProblem(matched; eta=1e-7, rho=1e-7, rotation=1.0) end From 0e941cdf057e98ee8190948f3da290065651bc96 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Tue, 10 Nov 2026 11:56:48 +0100 Subject: [PATCH 03/27] Analysis - FEATURE - Frame matched free-boundary energies and show the least stable eigenmode of a Galerkin solve --- ext/GPECMakieExt/forcefreestates.jl | 40 ++++++++++++++++++++++------ ext/GPECMakieExt/theme.jl | 3 +++ src/Analysis/ForceFreeStates.jl | 41 +++++++++++++++++++++++------ src/Display.jl | 7 ++--- 4 files changed, 72 insertions(+), 19 deletions(-) diff --git a/ext/GPECMakieExt/forcefreestates.jl b/ext/GPECMakieExt/forcefreestates.jl index e306f91592..d535704970 100644 --- a/ext/GPECMakieExt/forcefreestates.jl +++ b/ext/GPECMakieExt/forcefreestates.jl @@ -37,14 +37,22 @@ const _ENERGY_STYLE = Dict( :vacuum => (:ev, rich("vacuum δW", subscript("v")), :rect, 3) ) +# A matched closure's W is non-Hermitian at the layers' forcing frequencies: its complex energies get Re on the main +# axis and Im (∝ −torque) below it, with no stability verdict. function _energies!(gl, e; which=(:total, :plasma, :vacuum)) et = real.(e.et) nu = count(<(0), et) - title = nu == 0 ? rich("Free boundary: stable, least stable δW = ", _num(et[1])) : "Free boundary: $(_plural(nu, "unstable eigenmode"))" + title = if e.matched + rich("Matched free-boundary energies, λ", subscript("1"), " = ", _cnum(e.et[1])) + else + nu == 0 ? rich("Free boundary: stable, least stable δW = ", _num(et[1])) : "Free boundary: $(_plural(nu, "unstable eigenmode"))" + end vals = reduce(vcat, (real.(getfield(e, _ENERGY_STYLE[w][1])) for w in which)) lims = _symlims(vals) - ax = Axis(gl[1, 1]; xlabel="eigenmode (most unstable first)", ylabel="eigenvalue of W·v = λN·v", title, yscale=Makie.pseudolog10, limits=(nothing, lims)) - hspan!(ax, lims[1], 0; color=(:firebrick, 0.06)) + xlabel = e.matched ? "eigenmode (lowest Re λ first)" : "eigenmode (most unstable first)" + ax = Axis(gl[1, 1]; xlabel, ylabel=e.matched ? "Re λ of W·v = λN·v" : "eigenvalue of W·v = λN·v", title, yscale=Makie.pseudolog10, + limits=(nothing, lims)) + e.matched || hspan!(ax, lims[1], 0; color=(:firebrick, 0.06)) hlines!(ax, 0; color=:black, linewidth=1) for w in which field, label, marker, k = _ENERGY_STYLE[w] @@ -52,20 +60,35 @@ function _energies!(gl, e; which=(:total, :plasma, :vacuum)) scatter!(ax, 1:length(v), v; color=WONG[k], marker, markersize=k == 1 ? 9 : 7, label) end length(which) > 1 && axislegend(ax; position=:rb) + if e.matched + hidexdecorations!(ax; grid=false) + ai = Axis(gl[2, 1]; xlabel, ylabel=rich("Im λ (torque ∝ −Im λ)"), yscale=Makie.pseudolog10) + hlines!(ai, 0; color=:black, linewidth=1) + scatter!(ai, 1:length(e.et), imag.(e.et); color=WONG[1], markersize=9) + linkxaxes!(ax, ai) + rowsize!(gl, 2, Relative(0.3)) + end return ax end function _mode_displacement!(gl, d, rat; modes=nothing) amp = abs.(d.xi) + shown = ifelse.(d.keep, amp, 0.0) # each harmonic away from its resonance sets the harmonic choice and the y-range rows = if modes === nothing - sort(sortperm(vec(maximum(amp; dims=2)); rev=true)[1:min(6, size(amp, 1))]) + sort(sortperm(vec(maximum(shown; dims=2)); rev=true)[1:min(6, size(amp, 1))]) else [m - d.mlow + 1 for m in modes if 1 <= m - d.mlow + 1 <= size(amp, 1)] end isempty(rows) && throw(ArgumentError("plot_mode_displacement: no requested m lies in $(d.mlow):$(d.mlow + size(amp, 1) - 1)")) - scaled, scale = _decade(amp[rows, :]) - ax = Axis(gl[1, 1]; xlabel=PSIN, ylabel=rich("|ξ", superscript("ψ"), subscript("m"), "|", _unit(scale, "")), limits=((0, 1), (0, nothing))) - title = rich("ξ", superscript("ψ"), subscript("m"), " of the least stable free-boundary eigenmode", d.dW === nothing ? "" : ", δW = " * _num(real(d.dW))) + factor, scale = _power(shown[rows, :]) + scaled = amp[rows, :] ./ factor + ytop = 1.05 * maximum(shown[rows, :]) / factor + ax = Axis(gl[1, 1]; xlabel=PSIN, ylabel=rich("|ξ", superscript("ψ"), subscript("m"), "|", _unit(scale, "")), limits=((0, 1), (0, ytop))) + title = if d.matched + rich("ξ", superscript("ψ"), subscript("m"), " of the lowest Re λ free-boundary eigenmode", d.dW === nothing ? "" : ", λ = " * _cnum(d.dW)) + else + rich("ξ", superscript("ψ"), subscript("m"), " of the least stable free-boundary eigenmode", d.dW === nothing ? "" : ", δW = " * _num(real(d.dW))) + end _titled_rationals!(gl[1, 1], ax, rat, title) colors = Makie.resample_cmap(:viridis, length(rows) + 1) for (j, i) in enumerate(rows) @@ -79,7 +102,8 @@ function _eigenvectors!(gl, d; nmodes=12) v = abs.(d.wt) m = d.mlow .+ (0:(size(v, 1)-1)) k = min(size(v, 2), nmodes) - ax = Axis(gl[1, 1]; xlabel="poloidal harmonic m", ylabel="eigenmode", yreversed=true, title="Free-boundary eigenmodes, least stable at top", + title = d.matched ? "Free-boundary eigenmodes, lowest Re λ at top" : "Free-boundary eigenmodes, least stable at top" + ax = Axis(gl[1, 1]; xlabel="poloidal harmonic m", ylabel="eigenmode", yreversed=true, title, yticks=1:k) hm = heatmap!(ax, m, 1:k, v[:, 1:k]; colormap=:viridis) Colorbar(gl[1, 2], hm; label=rich("|v", subscript("m"), "| (unit power norm)")) diff --git a/ext/GPECMakieExt/theme.jl b/ext/GPECMakieExt/theme.jl index 05db374c53..cb22514362 100644 --- a/ext/GPECMakieExt/theme.jl +++ b/ext/GPECMakieExt/theme.jl @@ -49,6 +49,9 @@ function _num(v) return trim(string(round(v / 10.0^k; sigdigits=3))) * "×10" * _sup(k) end +# A complex number as "a + bi" with `_num` parts. +_cnum(z) = _num(real(z)) * (imag(z) < 0 ? " − " : " + ") * _num(abs(imag(z))) * "i" + sub(a, b) = rich(a, subscript(b)) sup(a, b) = rich(a, superscript(b)) const PSIN = sub("ψ", "N") diff --git a/src/Analysis/ForceFreeStates.jl b/src/Analysis/ForceFreeStates.jl index b2bd09f3d1..a0873b0b66 100644 --- a/src/Analysis/ForceFreeStates.jl +++ b/src/Analysis/ForceFreeStates.jl @@ -22,6 +22,10 @@ const _FBS = "ForceFreeStates/FreeBoundaryStability" # Least-stable total energy, or `nothing` without free-boundary energies. _first_energy(et) = isempty(et) ? nothing : et[1] +# A matched closure's energies are complex and carry no stability verdict. +_matched(r::ForceFreeStatesResult) = r.closure === :matched +_matched(fid::HDF5.File) = haskey(fid, "SingularSurfaces/Match") + # The rational surfaces as (ψ_N, "m/n" labels). _rationals(r::ForceFreeStatesResult) = (; psi=[s.psifac for s in r.surfaces], labels=["$(s.m[1])/$(s.n[1])" for s in r.surfaces]) function _rationals(h5path::AbstractString) @@ -32,30 +36,51 @@ function _rationals(h5path::AbstractString) end end +# |m − nq| below which harmonic m is left out of the mode plot's y-range and harmonic choice: it diverges there toward +# its rational, inside the domain or just past the edge. +const _RESONANCE_MASK = 0.1 + +# (harmonic × ψ) points with |m − nq| ≥ _RESONANCE_MASK, harmonics m = mlow, mlow+1, … of toroidal mode n. +_unmasked(q, mlow, nrow, n) = [abs(mlow + i - 1 - n * qj) >= _RESONANCE_MASK for i in 1:nrow, qj in q] + +# ξ^ψ of the least stable free-boundary eigenmode. Forward stores its solution already rotated into the eigenmodes +# (scaled by 2π·ψ₀·10⁻³); Galerkin stores one column per unit edge displacement, so its columns are combined by the +# least stable eigenvector with the same scaling. +_least_stable(xi, wt, psio, gal::Bool) = + gal ? reduce(hcat, [xi[:, :, i] * (wt[:, 1] .* (2π * psio * 1e-3)) for i in axes(xi, 3)]) : xi[:, 1, :] + function _mode_displacement_data(r::ForceFreeStatesResult) sol = r.solution - return (; mlow=r.mlow, psi=sol.psi_store, xi=sol.u_store[:, 1, 1, :], dW=r.free_boundary === nothing ? nothing : _first_energy(r.free_boundary.et)) + xi = _least_stable(sol.u_store[:, :, 1, :], r.free_boundary === nothing ? nothing : r.free_boundary.wt, r.equil.psio, + sol.basis === :gal_native && r.free_boundary !== nothing) + keep = _unmasked(sol.q_store, r.mlow, size(xi, 1), r.nlow) + return (; mlow=r.mlow, psi=sol.psi_store, xi, keep, dW=r.free_boundary === nothing ? nothing : _first_energy(r.free_boundary.et), matched=_matched(r)) end function _mode_displacement_data(h5path::AbstractString) h5open(h5path, "r") do fid - # Forward integration stores its profiles in ForwardIntegration, a matched Galerkin solve in GalerkinIntegration. + # Forward integration stores its profiles in ForwardIntegration, a Galerkin solve in GalerkinIntegration. group = isempty(fid["$_FWD/xi_psi"]) ? _GAL : _FWD - (; mlow=read(fid["Info/mlow"]), psi=read(fid["$group/psi"]), xi=read(fid["$group/xi_psi"])[:, 1, :], - dW=_first_energy(read(fid["$_FBS/eigenmode_energies"]))) + psi = read(fid["$group/psi"]) + xi = _least_stable(read(fid["$group/xi_psi"]), read(fid["$_FBS/W_freeboundary_eigenmodes"]), read(fid["Equilibrium/psi_total"]), group == _GAL) + mlow = read(fid["Info/mlow"]) + keep = _unmasked(read(fid["$group/q"]), mlow, size(xi, 1), read(fid["Info/nlow"])) + (; mlow, psi, xi, keep, dW=_first_energy(read(fid["$_FBS/eigenmode_energies"])), matched=_matched(fid)) end end _criterion_data(r::ForceFreeStatesResult) = (; psi=r.diagnostics.psi_store, crit=r.diagnostics.crit_store) _criterion_data(h5path::AbstractString) = h5open(fid -> (; psi=read(fid["$_FWD/psi"]), crit=read(fid["$_FWD/crit"])), h5path, "r") -_energy_eigenvector_data(r::ForceFreeStatesResult) = (; wt=r.free_boundary.wt, mlow=r.mlow) -_energy_eigenvector_data(h5path::AbstractString) = h5open(fid -> (; wt=read(fid["$_FBS/W_freeboundary_eigenmodes"]), mlow=read(fid["Info/mlow"])), h5path, "r") +_energy_eigenvector_data(r::ForceFreeStatesResult) = (; wt=r.free_boundary.wt, mlow=r.mlow, matched=_matched(r)) +_energy_eigenvector_data(h5path::AbstractString) = + h5open(fid -> (; wt=read(fid["$_FBS/W_freeboundary_eigenmodes"]), mlow=read(fid["Info/mlow"]), matched=_matched(fid)), h5path, "r") -_energy_data(r::ForceFreeStatesResult) = (; et=r.free_boundary.et, ep=r.free_boundary.ep, ev=r.free_boundary.ev) +_energy_data(r::ForceFreeStatesResult) = (; et=r.free_boundary.et, ep=r.free_boundary.ep, ev=r.free_boundary.ev, matched=_matched(r)) function _energy_data(h5path::AbstractString) h5open(h5path, "r") do fid - (; et=read(fid["$_FBS/eigenmode_energies"]), ep=read(fid["$_FBS/eigenmode_plasma_energies"]), ev=read(fid["$_FBS/eigenmode_vacuum_energies"])) + (; et=read(fid["$_FBS/eigenmode_energies"]), ep=read(fid["$_FBS/eigenmode_plasma_energies"]), ev=read(fid["$_FBS/eigenmode_vacuum_energies"]), + matched=_matched(fid)) end end diff --git a/src/Display.jl b/src/Display.jl index d8aa68fbbb..47c27f26cb 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -195,12 +195,13 @@ end function _free_boundary_note(r::ForceFreeStates.ForceFreeStatesResult) fb = r.free_boundary if fb === nothing - r.closure === :matched && return "not computed (a matched closure carries no ideal δW)" return r.control.vac_flag ? "not computed by the $(r.integrator) integrator" : "not computed (vac_flag = false)" end - verdict = real(first(fb.et)) < 0 ? "unstable" : "stable" e(z) = _energy(r, first(z)) - return "$verdict: et₁ = $(e(fb.et)), ep₁ = $(e(fb.ep)), ev₁ = $(e(fb.ev)), vacuum λ = $(_fmt(fb.vacuum_eigenvalue))" + energies = "et₁ = $(e(fb.et)), ep₁ = $(e(fb.ep)), ev₁ = $(e(fb.ev)), vacuum λ = $(_fmt(fb.vacuum_eigenvalue))" + # A matched closure's non-Hermitian W carries no stability verdict. + r.closure === :matched && return energies + return (real(first(fb.et)) < 0 ? "unstable" : "stable") * ": " * energies end # m/n of each row of the Δ′ matrix: Galerkin solves across its in-band subset of the surfaces. From f17055d372a3339ece9243d786f51dddeeabf36d Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Fri, 13 Nov 2026 22:11:36 +0100 Subject: [PATCH 04/27] ForceFreeStates.Riccati - REFACTOR! - Build every Riccati output from one parallel pass and cross singular surfaces in the asymptotic basis --- .../benchmark_diiid_ideal_ntv_torque.jl | 1 - benchmarks/benchmark_riccati_der.jl | 117 ---- docs/development/references.md | 2 +- docs/development/regression-harness.md | 2 +- docs/src/stability.md | 14 +- examples/DIIID-like_SLAYER_example/gpec.toml | 3 +- .../gpec.toml | 3 +- examples/LAR_beta_scan/gpec.toml | 3 +- examples/LAR_epsilon_scan/gpec.toml | 3 +- examples/Solovev_ideal_example_3D/gpec.toml | 3 +- .../Solovev_ideal_example_multi_n/gpec.toml | 1 - .../single_n_1/gpec.toml | 1 - .../single_n_2/gpec.toml | 1 - .../cases/diiid_n1_riccati.toml | 3 +- .../cases/diiid_n1_riccati_q1.toml | 12 + regression-harness/cases/solovev_multi_n.toml | 1 - src/Deck.jl | 4 +- src/ForceFreeStates/CoreTypes.jl | 36 +- src/ForceFreeStates/EulerLagrange.jl | 125 ++-- src/ForceFreeStates/Integrators.jl | 14 +- src/ForceFreeStates/Result.jl | 17 +- src/ForceFreeStates/Riccati/Crossings.jl | 170 ++---- src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 534 +++--------------- src/ForceFreeStates/Riccati/Driver.jl | 249 ++++---- src/ForceFreeStates/Riccati/Propagators.jl | 425 ++------------ src/ForceFreeStates/Riccati/Types.jl | 23 +- src/ForceFreeStates/Run.jl | 18 +- src/ForceFreeStates/Surfaces/Types.jl | 9 +- src/ForceFreeStates/Utils.jl | 4 +- src/Precompile.jl | 2 +- src/Tearing/Dispersion/CoupledFullMatch.jl | 7 +- test/runtests_analysis_plots.jl | 2 +- test/runtests_eulerlagrange.jl | 22 +- test/runtests_parallel_integration.jl | 164 ++---- test/runtests_resist_eval.jl | 30 +- test/runtests_result_struct.jl | 1 + test/runtests_riccati.jl | 198 +++---- test/runtests_sing.jl | 2 +- test/runtests_slayer_inputs.jl | 6 +- test/runtests_solve_api.jl | 19 +- 40 files changed, 576 insertions(+), 1675 deletions(-) delete mode 100644 benchmarks/benchmark_riccati_der.jl create mode 100644 regression-harness/cases/diiid_n1_riccati_q1.toml diff --git a/benchmarks/benchmark_diiid_ideal_ntv_torque.jl b/benchmarks/benchmark_diiid_ideal_ntv_torque.jl index 3b2ae96fe4..c3724c3035 100644 --- a/benchmarks/benchmark_diiid_ideal_ntv_torque.jl +++ b/benchmarks/benchmark_diiid_ideal_ntv_torque.jl @@ -145,7 +145,6 @@ singfac_min = 1e-4 [Riccati] eulerlagrange_tolerance = 1e-7 save_interval = 3 -renorm_threshold = 1e4 """ ) end diff --git a/benchmarks/benchmark_riccati_der.jl b/benchmarks/benchmark_riccati_der.jl deleted file mode 100644 index 9a1d6411b5..0000000000 --- a/benchmarks/benchmark_riccati_der.jl +++ /dev/null @@ -1,117 +0,0 @@ -# Sanity check: riccati_der! correctly evaluates the explicit Riccati ODE. -# -# riccati_der! implements [Glasser 2018 Phys. Plasmas 25, 032507, Eq. 19]: -# dS/dψ = w†·F̄⁻¹·w - S·Ḡ·S, w = Q - K̄·S -# -# where Q = diag(1/(m - n·q)), F̄ = L·L† (Cholesky), K̄ and Ḡ are the MHD -# metric matrices evaluated at ψ. -# -# NOTE: The identity between this Riccati ODE and the EL chain rule -# dS/dψ = dU₁·U₂⁻¹ - S·dU₂·U₂⁻¹ -# holds ONLY for Hermitian S (physical states evolved from the axis, where -# S†=S is preserved by the EL symmetry). For arbitrary non-Hermitian (U₁, U₂), -# the two expressions differ — so this script compares riccati_der! against the -# explicit formula rather than against sing_der!. -# -# Usage (from the repository root): -# julia --project=. benchmarks/benchmark_riccati_der.jl - -using LinearAlgebra, Random, Printf, TOML -using GeneralizedPerturbedEquilibrium - -const FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates - -function setup_solovev() - GPEC = GeneralizedPerturbedEquilibrium - ex = joinpath(@__DIR__, "..", "test", "test_data", "regression_solovev_ideal_example") - inputs = TOML.parsefile(joinpath(ex, "gpec.toml")) - equil = GPEC.Equilibrium.PlasmaEquilibrium(GPEC.equilibrium_config(inputs, ex), GPEC.analytic_config(inputs)) - prob = GPEC.ForceBalanceProblem(equil; GPEC.force_balance_keywords(inputs, ex)...) - ctrl, intr, equil, _, mats = GPEC._prepare_solve(prob, GPEC.force_balance_algorithm(inputs)) - return ctrl, equil, mats, intr -end - -# Evaluate the Riccati RHS explicitly from splines: dS = w†·F̄⁻¹·w - S·Ḡ·S -function riccati_rhs_manual(S, psi, equil, mats, intr) - N = intr.numpert_total - L = zeros(ComplexF64, N, N) - Kmat = zeros(ComplexF64, N, N) - Gmat = zeros(ComplexF64, N, N) - mats.ideal.F_spline_lower(vec(L), psi; hint=mats._hint) - mats.ideal.K_spline(vec(Kmat), psi; hint=mats._hint) - mats.ideal.G_spline(vec(Gmat), psi; hint=mats._hint) - - q = equil.profiles.q_spline(psi) - singfac = vec(1.0 ./ ((intr.mlow:intr.mhigh) .- q .* (intr.nlow:intr.nhigh)')) - - # w = Q - K̄·S (Q is diagonal; add only the diagonal entries) - w = -Kmat * S - for i in 1:N - w[i, i] += singfac[i] - end - - # v = F̄⁻¹·w via stored Cholesky factor L (L·L† = F̄) - v = copy(w) - ldiv!(LowerTriangular(L), v) - ldiv!(UpperTriangular(L'), v) - - return adjoint(w) * v - S * Gmat * S -end - -println("\n=== riccati_der! formula verification ===") -println("Verifies riccati_der! output matches manual evaluation of Glasser 2018 Eq. 19.") -println("Test state: Hermitian S (physical constraint). Expected error: ~machine epsilon.\n") - -ctrl, equil, mats, intr = setup_solovev() -N = intr.numpert_total - -odet = FFS.OdeState(N, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr.msing) -FFS.initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) -chunks = FFS.chunk_el_integration_bounds(odet, ctrl, intr) - -# 30% into each chunk: well inside the interval, away from singularities at psi_end -test_psis = [c.psi_start + 0.3 * (c.psi_end - c.psi_start) for c in chunks] - -println(" N=$N modes, $(length(test_psis)) test ψ points (30% into each chunk)\n") -@printf(" %8s %14s %14s %12s\n", "ψ", "‖dS_manual‖", "‖dS_ric‖", "rel error") -println(" " * "-"^54) - -rng = Random.MersenneTwister(42) -threshold = 1e-10 - -max_err = let max_err = 0.0 - for psi in test_psis - # Hermitian S: physical Riccati matrix is Hermitian (preserved by EL symmetry) - A = randn(rng, ComplexF64, N, N) - S = (A + A') / 2 # Hermitian by construction - - # Manual RHS - dS_manual = riccati_rhs_manual(S, psi, equil, mats, intr) - - # riccati_der! RHS - u_ric = zeros(ComplexF64, N, N, 2) - du_ric = zeros(ComplexF64, N, N, 2) - u_ric[:, :, 1] .= S - u_ric[:, :, 2] .= Matrix{ComplexF64}(I, N, N) - dummy_chunk = FFS.IntegrationChunk(psi, psi, false, 0, 1) - params = (ctrl, equil, mats, intr, odet, dummy_chunk) - FFS.riccati_der!(du_ric, u_ric, params, psi) - dS_ric = du_ric[:, :, 1] - - ref = max(norm(dS_manual), 1e-10) - err = norm(dS_ric - dS_manual) / ref - max_err = max(max_err, err) - status = err < threshold ? "" : " ← FAIL" - @printf(" %8.4f %14.4e %14.4e %12.4e%s\n", psi, norm(dS_manual), norm(dS_ric), err, status) - end - max_err -end - -println() -if max_err < threshold - @printf("PASSED — max rel error = %.2e (threshold %.0e)\n", max_err, threshold) -else - @printf("FAILED — max rel error = %.2e exceeds threshold %.0e\n", max_err, threshold) - exit(1) -end -println() diff --git a/docs/development/references.md b/docs/development/references.md index 9dbb3c4112..e1ca1cda8e 100644 --- a/docs/development/references.md +++ b/docs/development/references.md @@ -112,7 +112,7 @@ GPEC will eventually implement resistive MHD stability analysis based on: - **Glasser (2018)**: "A robust solution for the resistive MHD toroidal Δ′ matrix in near real-time" - Location: `docs/resources/2018-Glasser-A robust solution for the resistive MHD toroidal Delta-prime matrix in near real-time.pdf` - - Published: Physics of Plasmas **25**, 032501 (2018) + - Published: Physics of Plasmas **25**, 082502 (2018) - Describes: Fast computation of Δ' matrix for resistive stability - **Wang et al. (2020)**: "Modeling of resistive plasma response in toroidal geometry using an asymptotic matching approach" diff --git a/docs/development/regression-harness.md b/docs/development/regression-harness.md index c6da88b19a..22a715e67f 100644 --- a/docs/development/regression-harness.md +++ b/docs/development/regression-harness.md @@ -115,7 +115,7 @@ regress --cases solovev_n1 --ref-range develop~10..develop - `--jobs N` — run N cases at a time (see *Parallel lanes* above) - `--isolate` — run each case in its own fresh subprocess instead of a warm worker -GPEC workers run with `-t auto` (all cores) so GPEC's threaded kernels are active; set `GPEC_REGRESS_THREADS=1` to force single-threaded runs. Tracked quantities are not bit-identical across thread counts. Most move only in the last few bits, inside their noise floors; the parallel Riccati integrator splits its domain by thread count, so its energies move by ~5e-9 and its step counts by ~2 between 1 and 16 threads, and the Riccati cases' floors are set above that spread. The count each run actually used is recorded in its environment fingerprint (shown in the report's `env:` lines), and the report flags two compared runs with different counts. Thread count is not part of the cache key; a `CHANGED` row in a comparison across thread counts that sits just above its floor is worth re-checking at a matched `GPEC_REGRESS_THREADS`. +GPEC workers run with `-t auto` (all cores) so GPEC's threaded kernels are active; set `GPEC_REGRESS_THREADS=1` to force single-threaded runs. Tracked quantities are not bit-identical across thread counts. Most move only in the last few bits, inside their noise floors; the Riccati integrator's chunking does not depend on the thread count. The count each run actually used is recorded in its environment fingerprint (shown in the report's `env:` lines), and the report flags two compared runs with different counts. Thread count is not part of the cache key; a `CHANGED` row in a comparison across thread counts that sits just above its floor is worth re-checking at a matched `GPEC_REGRESS_THREADS`. On a machine you share with other people or with your own parallel sessions, `-t auto` is antisocial: set `GPEC_REGRESS_THREADS` to a bounded count, and `JULIA_NUM_PRECOMPILE_TASKS` alongside it, since `Pkg.instantiate()` otherwise fans out to `Sys.CPU_THREADS + 1` precompile workers at the start of every ref. If the machine has a batch scheduler, submit the run through it and pin both variables to the allocation, with `--jobs` × `GPEC_REGRESS_THREADS` equal to the CPUs requested. diff --git a/docs/src/stability.md b/docs/src/stability.md index aa86df2ecb..0fe50c3f68 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -34,14 +34,14 @@ where ``\mathbf{L}`` is built from the Fourier-space metric matrices ``\bar{F}`` The resonance factor vanishes at each rational surface, so the solutions there behave as ``|\psi - \psi_s|^{-1/2 \pm \sqrt{-D_I}}``, a large and a small solution governed by the Mercier index ``D_I``; GPEC assembles the right-hand side from reduced matrices that carry explicit ``(m - nq)`` factors rather than their inverses, the convention used on every page. The Newcomb criterion states that the plasma is fixed-boundary stable if and only if the solution that is regular at the axis remains nonsingular across every rational surface and up to the edge. -The Riccati integrator works with the matrix ``S = U_1 U_2^{-1}`` ([Glasser, Kolemen and Glasser (2018)](citations.md#ForceFreeStates), Eq. 19), which obeys a quadratic matrix ODE and stays bounded where ``U_1`` and ``U_2`` grow exponentially, so that the rational surfaces can be crossed without the Gaussian reduction of the forward integration. +The Riccati integrator works with the matrix ``S = U_1 U_2^{-1}`` ([Glasser, Kolemen and Glasser (2018)](citations.md#ForceFreeStates), Eq. 36), which obeys a quadratic matrix ODE and stays bounded where ``U_1`` and ``U_2`` grow exponentially, so that the rational surfaces can be crossed without the Gaussian reduction of the forward integration. Its global boundary-value problem over all surfaces gives the Δ′ matrix of [Glasser and Kolemen (2018)](citations.md#Tearing), stored in the PEST-3 convention: the diagonal entry of each surface is its outer-region Δ′, positive when the outer region drives the tearing mode, and the off-diagonal entries couple the surfaces. ## Integrators `[ForceFreeStates] integrator` selects the radial method; its numerical settings sit in a section of the same name. -- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in the Riccati basis and assembles the Δ′ matrix. It stores the chunk endpoints only, so it yields no dense ``\xi`` profiles. +- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the Riccati matrix ``S`` at every solver step, not the displacement, so it yields no ``\xi`` profiles. - `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction at each rational surface. It returns dense displacement profiles, and is the only integrator whose result `plasma_response` accepts (the response operators are built from the dense ``\xi`` solution; a wall is refused too) and the only one that supports the kinetic solve. - `"Galerkin"` (`[Galerkin]`) solves the outer region variationally on a finite-element basis, giving the resistive Δ′ matrix and the PEST-3 blocks but no free-boundary energies; see [Galerkin Solver](galerkin.md). @@ -69,7 +69,7 @@ save_interval = 1 # save every Nth ODE step; steps near rational surfaces renorm_threshold = 1e3 # renormalize the solution basis above this column norm ``` -`examples/DIIID-like_riccati_deltaprime_example` sets the same three keys under `[Riccati]`. +`examples/DIIID-like_riccati_deltaprime_example` sets `eulerlagrange_tolerance` and `save_interval` under `[Riccati]`; `renorm_threshold` belongs to `[Forward]` only. The same solve from a script takes the deck keys as keywords of the problem and the integrator: @@ -136,10 +136,10 @@ The perpendicular diffusivities that set the layer widths are described with the ## Numerical notes -- The Riccati integrator splits the domain into chunks whose count is derived from the number of singular surfaces (`[Riccati] nchunks` overrides the target, `0` is automatic); every chunk integrates from identity initial conditions, so the result is independent of the thread count. -- The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from the split forward and backward propagators for the same reason. -- Both integrators use the adaptive ninth-order `Vern9` solver at `eulerlagrange_tolerance`; the Riccati basis is recovered by renormalizing whenever the solution exceeds `renorm_threshold`. -- The two crossing conventions differ slightly, so Riccati and Forward free-boundary energies agree to within a few percent, not to machine precision. +- The Riccati integrator splits the domain into chunks whose count is derived from the number of singular surfaces (`[Riccati] nchunks` overrides the target, `0` is automatic); every chunk integrates from its own start (the identity, or the asymptotic solutions of [Glasser and Kolemen (2018)](citations.md#Tearing) for the two chunks next to a rational surface), so the result is independent of the thread count. +- The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from products of the same propagators, matched midway between the surfaces. +- Both integrators use the adaptive ninth-order `Vern9` solver at `eulerlagrange_tolerance`; the Riccati integrator reduces its state to ``(S, I)`` after every chunk, and Forward applies Gaussian reduction whenever a solution norm grows past `renorm_threshold`. +- The two integrators cross a rational surface differently. Riccati carries the nonresonant asymptotic coefficients across it (Glasser and Kolemen (2018), Eq. 36), so its energies do not depend on `singfac_min`. Forward takes a trapezoidal step between the two sides, with an error of first order in `singfac_min`, so its energies converge to Riccati's as `singfac_min` shrinks. Local stability (Mercier, resistive interchange and ballooning) is a separate stage on the same equilibrium; see [Local Stability](ballooning.md). diff --git a/examples/DIIID-like_SLAYER_example/gpec.toml b/examples/DIIID-like_SLAYER_example/gpec.toml index fa41a0dd50..0f5f28d085 100644 --- a/examples/DIIID-like_SLAYER_example/gpec.toml +++ b/examples/DIIID-like_SLAYER_example/gpec.toml @@ -56,8 +56,7 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-10# Relative tolerance for ODE integration of Euler-Lagrange equations -save_interval = 1 # Save every Nth ODE step (1=all). Always saves near rational surfaces. -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization +save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored # SLAYER tearing-mode growth-rate analysis on the DIII-D-like H-mode equilibrium. # Runs off the ForceFreeStates result (no PE). The plasma (profiles incl. the χ⊥/χ_φ diff --git a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml index 31457af0d4..ddc2ee098a 100644 --- a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml +++ b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml @@ -55,5 +55,4 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-10 # Relative tolerance for ODE integration of Euler-Lagrange equations -save_interval = 1 # Save every Nth ODE step (1=all). Always saves near rational surfaces. -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization +save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored diff --git a/examples/LAR_beta_scan/gpec.toml b/examples/LAR_beta_scan/gpec.toml index d40e82a476..5906bf4c4c 100644 --- a/examples/LAR_beta_scan/gpec.toml +++ b/examples/LAR_beta_scan/gpec.toml @@ -69,5 +69,4 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-12 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization -save_interval = 1 # Save every Nth ODE step (1=all). Always saves near rational surfaces. +save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored diff --git a/examples/LAR_epsilon_scan/gpec.toml b/examples/LAR_epsilon_scan/gpec.toml index 119bb894a7..a5a19e9ac9 100644 --- a/examples/LAR_epsilon_scan/gpec.toml +++ b/examples/LAR_epsilon_scan/gpec.toml @@ -70,5 +70,4 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-12 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization -save_interval = 1 # Save every Nth ODE step (1=all). Always saves near rational surfaces. +save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored diff --git a/examples/Solovev_ideal_example_3D/gpec.toml b/examples/Solovev_ideal_example_3D/gpec.toml index a7b68e8d62..e5a6681c68 100644 --- a/examples/Solovev_ideal_example_3D/gpec.toml +++ b/examples/Solovev_ideal_example_3D/gpec.toml @@ -51,8 +51,7 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-7 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization -save_interval = 1 # Save every Nth ODE step (1=all). Always saves near rational surfaces. +save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored [Wall] # See examples/Solovev_ideal_example/gpec.toml for the rationale behind the close conformal wall. diff --git a/examples/Solovev_ideal_example_multi_n/gpec.toml b/examples/Solovev_ideal_example_multi_n/gpec.toml index c8e51b8c78..569280fc47 100644 --- a/examples/Solovev_ideal_example_multi_n/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/gpec.toml @@ -58,7 +58,6 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-7 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization # Solovev analytic equilibrium parameters; this section selects the equilibrium. See SolovevConfig in src/Equilibrium. [Solovev] diff --git a/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml b/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml index 0c272a9a0a..8e611f4956 100644 --- a/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml @@ -52,7 +52,6 @@ singfac_min = 1e-4 # Fractional distance from rational q at which ide # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-7 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization # Solovev analytic equilibrium parameters; this section selects the equilibrium. See SolovevConfig in src/Equilibrium. [Solovev] diff --git a/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml b/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml index f200df8c2a..0aa031281d 100644 --- a/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml @@ -52,7 +52,6 @@ singfac_min = 1e-4 # Fractional distance from rational q at which ide # Numerical settings of the Riccati integrator [Riccati] eulerlagrange_tolerance = 1e-7 # Relative tolerance for ODE integration of Euler-Lagrange equations -renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization # Solovev analytic equilibrium parameters; this section selects the equilibrium. See SolovevConfig in src/Equilibrium. [Solovev] diff --git a/regression-harness/cases/diiid_n1_riccati.toml b/regression-harness/cases/diiid_n1_riccati.toml index 4c2642145e..3dbbb2d9b4 100644 --- a/regression-harness/cases/diiid_n1_riccati.toml +++ b/regression-harness/cases/diiid_n1_riccati.toml @@ -36,7 +36,6 @@ label = "edge coil response delta_coil" noise_threshold = 1e-8 order = 12 -# The parallel Riccati chunking depends on the thread count, which moves energies by ~5e-9 (spectrum ~1e-6 absolute) and step counts by ~2 between 1 and 16 threads; the floors below sit well above that. # Energies — leading generalized (W,N) pencil eigenvalues at the final truncation (psilim): power-normalized (⟨|ξ|²⟩ = 1 metric) and invariant to the working-coordinate Jacobian. [quantities.et_real] h5path = "ForceFreeStates/FreeBoundaryStability/eigenmode_energies" @@ -95,7 +94,7 @@ label = "singular q values" noise_threshold = 1e-8 order = 32 -# Integration — chunk-endpoint step counts move when the chunk sizing changes. +# Integration — stored and total solver-step counts move when the chunk layout or the tolerance changes. [quantities.nstep] h5path = "ForceFreeStates/Solutions/ForwardIntegration/nstep" type = "int_scalar" diff --git a/regression-harness/cases/diiid_n1_riccati_q1.toml b/regression-harness/cases/diiid_n1_riccati_q1.toml new file mode 100644 index 0000000000..bf43935d32 --- /dev/null +++ b/regression-harness/cases/diiid_n1_riccati_q1.toml @@ -0,0 +1,12 @@ +# Regression case: the diiid_n1_riccati deck with the q = 1 surface inside the integration domain. +# The on-axis q is lowered to 0.9 and the integration starts inside q = 1, so the m = 1 surface is +# crossed like the others. It tracks the energies and Δ' where the singular-surface crossing +# matters most: the base deck starts outside q = 1.02 and never crosses that surface. +[case] +name = "diiid_n1_riccati_q1" +base = "diiid_n1_riccati" # Inherit example_dir, [quantities.*] and [overrides] from this case +description = "DIII-D-like equilibrium, n=1, Riccati integrator with the q = 1 surface inside the domain" + +[overrides] +"Equilibrium.newq0" = 0.9 # On-axis q below 1, so a q = 1 surface exists +"ForceFreeStates.qlow" = 0.1 # Start the integration inside q = 1 diff --git a/regression-harness/cases/solovev_multi_n.toml b/regression-harness/cases/solovev_multi_n.toml index 7f366331d1..caadd39091 100644 --- a/regression-harness/cases/solovev_multi_n.toml +++ b/regression-harness/cases/solovev_multi_n.toml @@ -8,7 +8,6 @@ description = "Solovev analytical equilibrium, multi-n, ideal stability" example_dir = "examples/Solovev_ideal_example_multi_n" # Energies — leading generalized (W,N) pencil eigenvalues at the final truncation (psilim): power-normalized (⟨|ξ|²⟩ = 1 metric) and invariant to the working-coordinate Jacobian. -# The parallel Riccati chunking depends on the thread count, which moves energies by ~2e-9 (spectra ~1e-6 absolute) and step counts by ~2 between 1 and 16 threads; the floors below sit well above that. [quantities.et_real] h5path = "ForceFreeStates/FreeBoundaryStability/eigenmode_energies" type = "complex_vector" diff --git a/src/Deck.jl b/src/Deck.jl index ea0f4b17ce..c4403b60b1 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -20,7 +20,8 @@ const _RUN_SECTION_KEYS = ("verbose", "HDF5_filename", "output_filename", "write const _RUN_KEY_SECTIONS = ("Equilibrium", "LocalStability", "ForceFreeStates", "PerturbedEquilibrium", "KineticForces", "ErrorFields") # Keys that moved to another section, each with where it lives now. -const _ODE_DECK_KEYS = ("eulerlagrange_tolerance", "renorm_threshold", "numsteps_init", "numunorms_init", "save_interval") +const _ODE_DECK_KEYS = ("eulerlagrange_tolerance", "save_interval") +const _FORWARD_DECK_KEYS = ("renorm_threshold", "numsteps_init", "numunorms_init") const _SEARCH_DECK_KEYS = ("scan_mode", "Q_re_range", "Q_im_range", "nre", "nim", "amr_passes", "amr_max_cells", "boxes", "multi_box_prescreen_n", "pole_threshold", "pole_threshold_adaptive", "filter_above_poles", "filter_outside_re", "gamma_gap_threshold", "polish_roots", "validity_rtol", "root_classification", "store_scan") @@ -35,6 +36,7 @@ const _MOVED_KEYS = Dict{String,Dict{String,String}}( "gal_ideal_flag" => "moved to [Match] as ideal", "gal_inner_solver" => "moved to [GGJ] as solver", (k => "moved to the integrator's section, [Forward] or [Riccati]" for k in _ODE_DECK_KEYS)..., + (k => "moved to [Forward]" for k in _FORWARD_DECK_KEYS)..., ("gal_$k" => "moved to [Match] as $k" for k in ("eta", "rho", "rotation", "gamma"))..., ("gal_inner_$k" => "moved to [GGJ] as $k" for k in ("xfac", "nx", "nq", "cutoff", "kmax"))..., ("gal_$k" => "moved to [Galerkin] as $k" for k in ("nx", "nq", "pfac", "dx0", "dx1", "dx2", "cutoff", "tol", "gnstep", diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 1cb794f65c..c1d0e8f17e 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -11,6 +11,22 @@ Supertype for objects that carry the resolved (m, n) mode space — `mlow`, `mhi """ abstract type ModeSpace end +""" + ModeIndices(modes::ModeSpace) + +Immutable copy of a mode space's indexing, for code that must not see the rest of its source. +""" +struct ModeIndices <: ModeSpace + mlow::Int + mhigh::Int + mpert::Int + nlow::Int + nhigh::Int + npert::Int + numpert_total::Int +end +ModeIndices(m::ModeSpace) = ModeIndices(m.mlow, m.mhigh, m.mpert, m.nlow, m.nhigh, m.npert, m.numpert_total) + """ ForceFreeStatesInternal @@ -59,26 +75,6 @@ Solve-time scratch state for a force-balance solve: the resolved mode space, sin q1lim::Float64 = 0.0 wall_settings::Union{Nothing,Vacuum.WallSettings} = nothing verbose::Bool = false - """ - Inter-surface Δ' matrix, `msing × msing`, PEST3 convention: the odd-parity projection of - `delta_prime_raw`, set by `compute_delta_prime_matrix!` (Riccati path only). - """ - delta_prime_matrix::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) - - """ - Edge coil-response matrix, `2msing × numpert_total`: column k is the resonant small-solution - response at each surface side to a unit source on edge mode k (Eq. 37 rpec edge condition, - `_solve_bvp_edge_coil`). Empty unless the S-axis vacuum-edge BVP was assembled. - """ - delta_coil::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) - - """ - Raw `2msing × 2msing` outer-region matching matrix D' (Pletzer–Dewar 1991, before parity - rotation), side-major ordering `[L_s1, R_s1, …, L_sm, R_sm]`. `pest3_decompose` recovers the - A', B', Γ', Δ' blocks. No ½ prefactor (matches Fortran rdcon; the paper applies ½). - Empty unless the Riccati integrator was used. - """ - delta_prime_raw::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) end """ diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index d407000592..5e32e8e533 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -53,7 +53,7 @@ records needed to undo it, and singular-surface asymptotic coefficients. - `du_store::Array{ComplexF64,3}` - du₁/dψ at each stored step, shape `(numpert_total, numpert_total, step)`; empty until `materialize_derivative_stores!` fills it (the galerkin-matched path supplies it at construction). - `xi_s_store::Array{ComplexF64,3}` - Clebsch displacement Ξ_s (Glasser 2016 Eq. 18) at each stored step; empty until materialized, like `du_store`. - - `u_store_el_basis::Bool` - True when `u_store` holds the Euler-Lagrange state; false on the sparse parallel path (Riccati-basis chunk endpoints), where derivative + - `u_store_el_basis::Bool` - True when `u_store` holds the Euler-Lagrange state; false on the Riccati path (stored states are the Riccati matrix), where derivative stores cannot be materialized. - `du_store_populated::Bool` - True once `du_store`/`xi_s_store` hold valid data in the final basis. - `crit_store::Vector{Float64}` - Critical eigenvalue (smallest eigenvalue of W⁻¹) at each stored step. @@ -133,9 +133,9 @@ OdeState(numpert_total::Int, numsteps_init::Int, numunorms_init::Int, msing::Int """ compute_delta_prime_from_ca!(odet, intr, equil) -**Stub, not physically valid.** Per-surface Δ' estimate `(ca_r[i,i,2,s] - ca_l[i,i,2,s]) / (4π²·psio)` -from the asymptotic coefficients. It ignores inter-surface coupling and the vacuum, so it does not -agree with the physical `ForceFreeStatesInternal.delta_prime_matrix`. Used only by tests. +**Stub, not physically valid.** Fill each surface's `delta_prime` with the per-surface estimate +`(ca_r[i,i,2,s] - ca_l[i,i,2,s]) / (4π²·psio)` from the asymptotic coefficients. It ignores inter-surface +coupling and the vacuum, so it does not agree with the physical `ForceFreeStatesResult.delta_prime`. """ function compute_delta_prime_from_ca!(odet::OdeState, intr::ForceFreeStatesInternal, equil::Equilibrium.PlasmaEquilibrium) denom = (2π)^2 * equil.psio # = twopi * chi1 in SingularCoupling.jl @@ -182,80 +182,60 @@ end """ balance_integration_chunks(chunks, ctrl, intr) -> Vector{IntegrationChunk} -Split the highest-`ode_itime_cost` chunk at its equal-cost midpoint until the count reaches -`ctrl.algorithm.nchunks` (`0` = auto). The target never depends on the thread count, so Riccati -output is thread-count independent. Only the last sub-chunk of a split keeps its crossing. +Split every crossing chunk once, then the costliest chunk (`ode_itime_cost`) until there are +`ctrl.algorithm.nchunks` (`0` = auto). Splits are at the equal-cost point; the upper part keeps the crossing. """ function balance_integration_chunks(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal) - min_chunks = 2 * intr.msing + 3 - # Enough sub-chunks per segment that no single long-span propagator is too ill-conditioned for the BVP - min_bvp_intervals = 8 * (intr.msing + 1) + intr.msing - if ctrl.algorithm.nchunks > 0 - if ctrl.algorithm.nchunks < min_chunks - @warn "nchunks = $(ctrl.algorithm.nchunks) is below the $min_chunks chunks required by $(intr.msing) singular surfaces; clamping up." - end - target_n = max(ctrl.algorithm.nchunks, min_chunks) - else - target_n = max(min_chunks, min_bvp_intervals) - end - - result = collect(chunks) - - while length(result) < target_n - # Find the highest-cost splittable chunk - best_idx = 0 - best_cost = -Inf - for (i, chunk) in enumerate(result) - width = chunk.psi_end - chunk.psi_start - if width > 1e-8 - c = ode_itime_cost(chunk.psi_start, chunk.psi_end, intr) - if c > best_cost - best_cost = c - best_idx = i - end - end - end - - best_idx == 0 && break # No more splittable chunks - - chunk = result[best_idx] - total_cost = best_cost - target_cost = total_cost / 2.0 - - # Bisect for ψ_mid with cost(psi_start, ψ_mid) ≈ target_cost + function split(chunk::IntegrationChunk) + half_cost = ode_itime_cost(chunk.psi_start, chunk.psi_end, intr) / 2 lo, hi = chunk.psi_start, chunk.psi_end for _ in 1:50 - mid = (lo + hi) / 2.0 - if ode_itime_cost(chunk.psi_start, mid, intr) < target_cost + mid = (lo + hi) / 2 + if ode_itime_cost(chunk.psi_start, mid, intr) < half_cost lo = mid else hi = mid end end - psi_mid = (lo + hi) / 2.0 - - left = IntegrationChunk(; psi_start=chunk.psi_start, psi_end=psi_mid, - needs_crossing=false, ising=0, direction=1) - right = IntegrationChunk(; psi_start=psi_mid, psi_end=chunk.psi_end, - needs_crossing=chunk.needs_crossing, ising=chunk.ising, - direction=chunk.direction) - splice!(result, best_idx, [left, right]) + psi_mid = (lo + hi) / 2 + return [IntegrationChunk(; psi_start=chunk.psi_start, psi_end=psi_mid, needs_crossing=false), + IntegrationChunk(; psi_start=psi_mid, psi_end=chunk.psi_end, chunk.needs_crossing, chunk.ising, chunk.direction)] + end + + result = IntegrationChunk[] + for chunk in chunks + append!(result, chunk.needs_crossing ? split(chunk) : [chunk]) + end + + target_n = length(result) + if ctrl.algorithm.nchunks > 0 + if ctrl.algorithm.nchunks < target_n + @warn "nchunks = $(ctrl.algorithm.nchunks) is below the $target_n chunks required by the singular surfaces crossed; clamping up." + end + target_n = max(ctrl.algorithm.nchunks, target_n) + else + # Enough sub-chunks per segment that no single long-span propagator is too ill-conditioned for the BVP + target_n = max(target_n, 8 * (intr.msing + 1) + intr.msing) + end + + while length(result) < target_n + costs = [c.psi_end - c.psi_start > 1e-8 ? ode_itime_cost(c.psi_start, c.psi_end, intr) : -Inf for c in result] + cost, costliest = findmax(costs) + isfinite(cost) || break # nothing left wide enough to split + splice!(result, costliest, split(result[costliest])) end return result end """ - eulerlagrange_integration(ctrl, equil, mats, intr) -> (odet, propagators, chunks, S_left) + eulerlagrange_integration(ctrl, equil, mats, intr) -> (odet, riccati) Integrate the Euler-Lagrange equations from the axis to `intr.psilim`, crossing each singular surface on the way. Dispatches on `ctrl.algorithm` to [`riccati_eulerlagrange_integration`](@ref) (the chunked propagator BVP) or -[`forward_eulerlagrange_integration`](@ref). - -Only the Riccati branch populates `propagators` / `chunks` / `S_left`, which -`compute_delta_prime_matrix!` consumes for the Δ' BVP; the forward branch returns `nothing` -for all three. +[`forward_eulerlagrange_integration`](@ref). `riccati` holds the inputs of +`compute_delta_prime_matrix`; it is `nothing` on the forward branch. """ function eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) @@ -272,13 +252,12 @@ function eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil::Equilibr end """ - forward_eulerlagrange_integration(ctrl, equil, mats, intr; verbose=intr.verbose) -> (odet, nothing, nothing, nothing) + forward_eulerlagrange_integration(ctrl, equil, mats, intr; verbose=intr.verbose) -> (odet, nothing) Forward branch of [`eulerlagrange_integration`](@ref): integrates chunk by chunk from the axis, applying Gaussian reduction whenever a solution norm ratio exceeds `ctrl.algorithm.renorm_threshold` and undoing it -via `transform_u!` at the end, so `odet.u_store` comes back dense in the axis basis. Call -directly to force this branch regardless of `ctrl.algorithm`; `verbose` overrides -`intr.verbose` for progress logging. +via `transform_u!` at the end, so `odet.u_store` comes back dense in the axis basis. `ctrl.algorithm` +must be a `Forward`, whose settings it reads; `verbose` overrides `intr.verbose` for progress logging. """ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal; verbose::Bool=intr.verbose) @@ -322,7 +301,7 @@ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil:: # Undo Gaussian reduction to get true solution vectors transform_u!(odet, intr) - return (odet, nothing, nothing, nothing) + return odet, nothing end """ @@ -630,7 +609,7 @@ function cross_ideal_singular_surf!( odet.ca_r[:, :, :, ising] .= sing_get_ca(odet.u, ua, intr) odet.ca_populated = true - # No Δ' here: it needs the Riccati gauge (U₂ = I); see compute_delta_prime_matrix! + # No Δ' here: it needs the Riccati propagators; see compute_delta_prime_matrix odet.q = equil.profiles.q_spline(odet.psifac; hint=odet.spline_hint) store_ode_data!(odet, odet.psifac, odet.u) end @@ -697,14 +676,16 @@ end const COLUMN_ABSTOL_CALLBACK = DiscreteCallback((u, t, integrator) -> true, refresh_column_abstol!; save_positions=(false, false)) """ - solve_el(prob, rtol; callback=COLUMN_ABSTOL_CALLBACK) + solve_el(prob, rtol; callback=COLUMN_ABSTOL_CALLBACK, save_everystep=false) -Vern9 solve of an Euler-Lagrange problem returning the end state, with the per-column abstol of `column_abstol!`. +Vern9 solve of an Euler-Lagrange problem with the per-column abstol of `column_abstol!`, returning the end state +or, with `save_everystep`, the state at every solver step. A custom `callback` must refresh that abstol itself, after any reduction or renormalization of the state. Errors when the solver stops short of the interval's end (e.g. the step size underflows), naming the ψ reached. """ -function solve_el(prob, rtol; callback=COLUMN_ABSTOL_CALLBACK) - sol = solve(prob, Vern9(); reltol=rtol, abstol=column_abstol(prob.u0, rtol), callback, save_everystep=false, save_end=true) +function solve_el(prob, rtol; callback=COLUMN_ABSTOL_CALLBACK, save_everystep::Bool=false) + # dense=false: saved steps keep the state only, not the interpolation stages. + sol = solve(prob, Vern9(); reltol=rtol, abstol=column_abstol(prob.u0, rtol), callback, save_everystep, dense=false, save_end=true) SciMLBase.successful_retcode(sol) || error( "Euler-Lagrange integration aborted at ψ = $(@sprintf("%.6f", sol.t[end])) before ψ = $(@sprintf("%.6f", prob.tspan[2])) " * @@ -1011,7 +992,7 @@ end In-place Euler-Lagrange derivative du/dψ at `psieval` [Glasser Phys. Plasmas 2016 112506 Eq. 24], ideal or kinetic, in the `(du, u, p, t)` form the ODE solver calls; `du` and `u` have shape -`(numpert_total, numpert_total, 2)`. Ξ_s is not computed here; see [`compute_node_xi_s!`](@ref). +`(numpert_total, ncolumns, 2)`. Ξ_s is not computed here; see [`compute_node_xi_s!`](@ref). """ function sing_der!(du::Array{ComplexF64,3}, u::Array{ComplexF64,3}, params::Tuple{ForceFreeStatesControl,Equilibrium.PlasmaEquilibrium, @@ -1039,7 +1020,7 @@ end el_derivatives!(du, u, kinetic, equil, mats, intr, psieval, spline_hint, mats_hint) -> q Euler-Lagrange (or, when `kinetic` is true, FKG) derivative kernel: writes du₁/dψ and du₂/dψ at -`psieval` into `du` and returns q there. Holds no state of its own — the two hints are the +`psieval` into `du` and returns q there, for any number of solution columns. Holds no state of its own — the two hints are the caller's interval-search accelerators, so concurrent callers just pass their own. """ @with_pool pool function el_derivatives!(du::Array{ComplexF64,3}, u::Array{ComplexF64,3}, @@ -1054,7 +1035,7 @@ caller's interval-search accelerators, so concurrent callers just pass their own fmat_lower = acquire!(pool, ComplexF64, Npert, Npert) kmat = similar!(pool, fmat_lower) gmat = similar!(pool, fmat_lower) - tmp_mat = similar!(pool, fmat_lower) + tmp_mat = acquire!(pool, ComplexF64, Npert, size(u, 2)) fill!(tmp_mat, zero(ComplexF64)) u1 = @view(u[:, :, 1]) diff --git a/src/ForceFreeStates/Integrators.jl b/src/ForceFreeStates/Integrators.jl index 8210f4f8cc..3705a5e76c 100644 --- a/src/ForceFreeStates/Integrators.jl +++ b/src/ForceFreeStates/Integrators.jl @@ -14,7 +14,7 @@ Serial forward integration with Gaussian reduction and dense solution profiles. ## Fields - `eulerlagrange_tolerance::Float64` - Relative tolerance for ODE integration. - - `renorm_threshold::Float64` - Column-norm growth threshold for Gaussian reduction or Riccati renormalization. + - `renorm_threshold::Float64` - Column-norm growth threshold for Gaussian reduction. - `numsteps_init::Int` - Initial capacity for stored ODE solution steps. - `numunorms_init::Int` - Initial capacity for solution-normalization records. - `save_interval::Int` - Save every Nth ODE step; always retain steps near rational surfaces. @@ -35,21 +35,15 @@ Chunked Riccati integration and the singular-surface boundary-value solve. ## Fields - `eulerlagrange_tolerance::Float64` - Relative tolerance for ODE integration. - - `renorm_threshold::Float64` - Column-norm growth threshold for Gaussian reduction or Riccati renormalization. - - `numsteps_init::Int` - Initial capacity for stored ODE solution steps. - - `numunorms_init::Int` - Initial capacity for solution-normalization records. - - `save_interval::Int` - Save every Nth ODE step; always retain steps near rational surfaces. + - `save_interval::Int` - Store every Nth solver step of each chunk; chunk ends and the edge-dW scan band are always stored. - `nchunks::Int` - Target chunk count; zero derives the count from the singular surfaces. - - `extended_precision_bvp::Bool` - Use Complex{Double64} for the Delta-prime BVP and PEST3 combination to reduce cancellation error. + - `extended_precision_bvp::Bool` - Solve the Delta-prime BVP in Complex{Double64} instead of ComplexF64; far slower, and needed only beyond about 150 poloidal harmonics. """ @kwdef struct Riccati <: AbstractIntegrator eulerlagrange_tolerance::Float64 = 1e-8 - renorm_threshold::Float64 = 1e3 - numsteps_init::Int = 4000 - numunorms_init::Int = 100 save_interval::Int = 1 nchunks::Int = 0 - extended_precision_bvp::Bool = true + extended_precision_bvp::Bool = false end """ diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index 2d2affa457..adca699c44 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -175,15 +175,15 @@ function _matched_gal_profiles(gal_result::GalerkinResult, m::MatchResult, mats: end """ - build_result(integrator, ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, gal_dp) + build_result(integrator, ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime) -> ForceFreeStatesResult Assemble the published result once the solve is finished, with the ideal or regular closure (a `MatchProblem` solve transforms it afterwards). Materializes the forward path's derivative stores and forms `W_p` when the free-boundary stage did not run; everything else is copied or aliased. -`odet` is the ODE state (`nothing` for Galerkin); `gal_data`/`gal_dp` are the Galerkin internals and -its Δ′ payload (`nothing` otherwise). +`odet` is the ODE state (`nothing` for Galerkin), `gal_data` the Galerkin internals (`nothing` otherwise), +and `delta_prime` the Δ′ payload of a Riccati or Galerkin solve (`nothing` otherwise). """ function build_result( integrator::Symbol, @@ -195,7 +195,7 @@ function build_result( odet::Union{Nothing,OdeState}, free_energies::Union{Nothing,FreeBoundaryResult}, gal_data::Union{Nothing,GalerkinResult}, - gal_dp::Union{Nothing,DeltaPrimeData} + delta_prime::Union{Nothing,DeltaPrimeData} ) # The forward sweep is the only formalism whose stores need materializing; doing it here # keeps `SolutionProfiles.du_store`/`xi_s_store` populated by construction. @@ -207,15 +207,6 @@ function build_result( nothing end - # One Δ′ payload whichever formalism produced it; Riccati leaves the PEST-3 blocks unfilled - # because it persists only the raw D′ and recovers them on demand via `pest3_decompose`. - delta_prime = if gal_dp !== nothing - gal_dp - elseif !isempty(intr.delta_prime_matrix) - DeltaPrimeData(intr.delta_prime_matrix, intr.delta_prime_raw, intr.delta_coil, nothing, nothing, nothing) - else - nothing - end kinetic = (kmsing=intr.kmsing, kinsing=intr.kinsing, scan_psi=intr.kinsing_scan_psi, scan_cond=intr.kinsing_scan_cond, scan_threshold=intr.kinsing_scan_threshold) diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index d0b157d4aa..5691e5c4c2 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -1,131 +1,79 @@ -# Singular-surface crossing algorithms for the Riccati/fundamental-matrix integration. +# Singular-surface crossing of the Riccati integrator, in the asymptotic basis. """ - riccati_cross_ideal_singular_surf!(odet, ctrl, equil, mats, intr, ising) + asymptotic_bases(chunks, ctrl, equil, mats, intr) -> Dict{Int,NamedTuple} -Cross a singular surface on the Riccati path: the Riccati counterpart of `cross_ideal_singular_surf!`, -without Gaussian reduction (S is bounded) and zeroing the resonant columns `ipert_res` directly. +Asymptotic basis `(; left, right)`, each N × 2N × 2, on both sides of every crossed surface, where its crossing +chunk ends. Keyed by the surface's index in `intr.sing`. +""" +function asymptotic_bases(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) + bases = Dict{Int,@NamedTuple{left::Array{ComplexF64,3}, right::Array{ComplexF64,3}}}() + for chunk in chunks + chunk.needs_crossing || continue + singp = intr.sing[chunk.ising] + dpsi = singp.psifac - chunk.psi_end + bases[chunk.ising] = (; left=sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0), dpsi), + right=sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0), dpsi)) + end + return bases +end -Expects `odet.u` in the bounded (U₁, U₂) form from `riccati_integrate_chunk!` with `needs_crossing=true`. -`ca_l`/`ca_r` are captured before `renormalize_riccati!` restores the (S, I) form, so the introduced -small solution has `ca_r[ipert_res, ipert_res, 2] = 1`. """ -function riccati_cross_ideal_singular_surf!( - odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, intr::ForceFreeStatesInternal, ising::Int -) - # Skip Gaussian reduction — S is bounded so no large-norm columns exist. + cross_singular_surface!(odet, intr, ising) + +Cross singular surface `ising` [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]. `odet.u` holds +asymptotic coefficients, in the left basis on entry and the right basis on return, with no big solution on +either side; both sets are recorded in `odet.ca_l` and `odet.ca_r`. +""" +function cross_singular_surface!(odet::OdeState, intr::ForceFreeStatesInternal, ising::Int) singp = intr.sing[ising] - dpsi = singp.psifac - odet.psifac # ψ_res - ψ_current (positive) ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - - sing_asymp_left, sing_asymp_right = _two_sided_singular_asymptotics(singp, ctrl, equil, mats, intr) - _log_riccati_crossing_diagnostics(odet, intr, ising, singp, dpsi, sing_asymp_left, sing_asymp_right) - - _capture_left_crossing_data!(odet, singp, sing_asymp_left, dpsi, intr, ising) - _predict_across_singular_surface!(odet, ctrl, equil, mats, intr, ising, ipert_res, dpsi, sing_asymp_right) - _capture_right_crossing_data!(odet, singp, sing_asymp_right, dpsi, intr, ising, ipert_res, ctrl) - - _stash_per_surface_delta_prime_stub!(odet, intr, ising, ipert_res, sing_asymp_right, equil, ctrl) - _store_crossing_step!(odet) - - # Restore canonical (S_new, I) form before continuing integration. - renormalize_riccati!(odet, intr) + eliminate_big_solutions!(odet.u, ipert_res) + odet.ca_l[:, :, :, ising] .= odet.u + start_small_solutions!(odet.u, ipert_res) + odet.ca_r[:, :, :, ising] .= odet.u + odet.ca_populated = true end """ - _two_sided_singular_asymptotics(singp, ctrl, equil, mats, intr) -> (left, right) + eliminate_big_solutions!(ca, ipert_res) -Left (`sig=-1`) and right (`sig=+1`) singular asymptotics, each from its own resonant block. +Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the +basis) so that only column `ipert_res[i]` carries the big solution of resonance `i`. """ -function _two_sided_singular_asymptotics(singp::SingType, ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, - intr::ForceFreeStatesInternal) - sing_asymp_right = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0) - sing_asymp_left = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0) - return sing_asymp_left, sing_asymp_right -end - -# @debug-only per-crossing diagnostics. Enable via JULIA_DEBUG=GeneralizedPerturbedEquilibrium. -function _log_riccati_crossing_diagnostics(odet, intr, ising, singp, dpsi, sing_asymp_left, sing_asymp_right) - @debug begin - ipert_res_diag = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - msg = " ising=$ising: psi_sing=$(@sprintf("%.10f", singp.psifac)), psi_eval=$(@sprintf("%.10f", odet.psifac)), dpsi=$(@sprintf("%.10e", dpsi))\n" - msg *= " alpha_L = $(sing_asymp_left.alpha), alpha_R = $(sing_asymp_right.alpha)\n" - for ip in ipert_res_diag - msg *= " vmatL[0] big: vmat[$ip,$ip,1,1]=$(@sprintf("%.8e", real(sing_asymp_left.vmat[ip,ip,1,1]))), vmat[$ip,$ip,2,1]=$(@sprintf("%.8e", real(sing_asymp_left.vmat[ip,ip,2,1])))\n" - msg *= " vmatR[0] big: vmat[$ip,$ip,1,1]=$(@sprintf("%.8e", real(sing_asymp_right.vmat[ip,ip,1,1]))), vmat[$ip,$ip,2,1]=$(@sprintf("%.8e", real(sing_asymp_right.vmat[ip,ip,2,1])))\n" +function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) + for (i, ipert) in enumerate(ipert_res) + candidates = setdiff(axes(ca, 2), @view ipert_res[1:(i-1)]) + pivot = candidates[argmax(abs.(@view ca[ipert, candidates, 1]))] + for col in axes(ca, 2) + col == pivot && continue + factor = ca[ipert, col, 1] / ca[ipert, pivot, 1] + @views ca[:, col, :] .-= factor .* ca[:, pivot, :] + ca[ipert, col, 1] = 0 end - msg - end -end - -# Capture left-side asymptotic data into odet.ca_l and singp.ua_left/psi_ua_left. -function _capture_left_crossing_data!(odet::OdeState, singp::SingType, sing_asymp_left, - dpsi::Float64, intr::ForceFreeStatesInternal, ising::Int) - ua = sing_get_ua(sing_asymp_left, dpsi) - singp.ua_left = copy(ua) - singp.psi_ua_left = odet.psifac - odet.ca_l[:, :, :, ising] .= sing_get_ca(odet.u, ua, intr) -end - -# Trapezoidal predictor across the singular surface with the resonant columns zeroed (they stay zero). -function _predict_across_singular_surface!(odet::OdeState, ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, - intr::ForceFreeStatesInternal, ising::Int, - ipert_res, dpsi::Float64, sing_asymp_right) - if ctrl.kinetic === nothing - for i in eachindex(sing_asymp_right.r1) - odet.u[:, ipert_res[i], :] .= 0 + if pivot != ipert + swapped = ca[:, pivot, :] + @views ca[:, pivot, :] .= ca[:, ipert, :] + ca[:, ipert, :] .= swapped end end - params = (ctrl, equil, mats, intr, odet, IntegrationChunk(0.0, 0.0, false, ising, 1)) - du1 = zeros(ComplexF64, intr.numpert_total, intr.numpert_total, 2) - du2 = zeros(ComplexF64, intr.numpert_total, intr.numpert_total, 2) - sing_der!(du1, odet.u, params, odet.psifac) - odet.psifac += 2 * dpsi # jump to other side of singular surface - sing_der!(du2, odet.u, params, odet.psifac) - odet.u .+= (du1 .+ du2) .* dpsi + return ca end -# Inject the right-side small asymptotic into the resonant columns, then capture odet.ca_r and singp.ua_right. -function _capture_right_crossing_data!(odet::OdeState, singp::SingType, sing_asymp_right, - dpsi::Float64, intr::ForceFreeStatesInternal, ising::Int, - ipert_res, ctrl::ForceFreeStatesControl) - ua = sing_get_ua(sing_asymp_right, dpsi) - singp.ua_right = copy(ua) - singp.psi_ua_right = odet.psifac - if ctrl.kinetic === nothing - for i in eachindex(sing_asymp_right.r1) - odet.u[ipert_res[i], :, :] .= 0 - odet.u[:, ipert_res[i], :] .= ua[:, ipert_res[i]+intr.numpert_total, :] - end - end - odet.ca_r[:, :, :, ising] .= sing_get_ca(odet.u, ua, intr) - odet.ca_populated = true -end +""" + start_small_solutions!(ca, ipert_res) -# STUB: per-surface ca-based Δ' (not physically valid; see SingType.delta_prime docstring). -# The canonical Δ' is intr.delta_prime_matrix from compute_delta_prime_matrix!. -function _stash_per_surface_delta_prime_stub!(odet::OdeState, intr::ForceFreeStatesInternal, - ising::Int, ipert_res, sing_asymp_right, - equil::Equilibrium.PlasmaEquilibrium, - ctrl::ForceFreeStatesControl) - ctrl.kinetic === nothing || return - denom = (2π)^2 * equil.psio - n_res = length(sing_asymp_right.r1) - N = intr.numpert_total - resize!(intr.sing[ising].delta_prime, n_res) - intr.sing[ising].delta_prime_col = zeros(ComplexF64, N, n_res) - for i in eachindex(sing_asymp_right.r1) - Δca_col = (odet.ca_r[:, ipert_res[i], 2, ising] - odet.ca_l[:, ipert_res[i], 2, ising]) / denom - intr.sing[ising].delta_prime_col[:, i] .= Δca_col - intr.sing[ising].delta_prime[i] = Δca_col[ipert_res[i]] +Turn reduced left-side coefficients `ca` into right-side ones: the resonant coefficients vanish and column +`ipert_res[i]` becomes the small solution of resonance `i`. +""" +function start_small_solutions!(ca::Array{ComplexF64,3}, ipert_res) + for ipert in ipert_res + ca[ipert, :, :] .= 0 + ca[:, ipert, :] .= 0 end -end - -# Store (U₁_new, U₂_new) into u_store before renormalization so that -# evaluate_stability_criterion! can recover S_new = U₁_new / U₂_new via compute_smallest_eigenvalue. -function _store_crossing_step!(odet::OdeState) - store_ode_data!(odet, odet.psifac, odet.u) + for ipert in ipert_res + ca[ipert, ipert, 2] = 1 + end + return ca end diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index fcac7b1151..7866534f54 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -1,123 +1,70 @@ # STRIDE global boundary-value problem: Delta-prime matrix assembly, solve, PEST-3 decomposition. -""" - compute_delta_prime_matrix!(intr, propagators, chunks; wv, psio, debug, S_at_surface_left, ctrl, equil, mats) - -Compute the inter-surface tearing stability matrix (msing × msing) using the -STRIDE global BVP formulation [Glasser 2018 Phys. Plasmas 25, 032501, Sec. III.B]. - -The BVP encodes the full plasma response with unknowns at each surface boundary: - -``` - x_axis (N): free IC parameters at the axis (U₁ = 0 regular solutions) - x_left[j] (2N): state at left inner-layer boundary of surface j - x_right[j] (2N): state at right inner-layer boundary of surface j - x_edge (N): free IC parameters at the edge - Total unknowns: nMat = (2 + 4·msing)·N -``` - -## Boundary conditions - -With `wv` (the singfac-scaled vacuum response) the edge BC is `U₁ = c, U₂ = -wv·ψ₀²·c`, i.e. -`wp + wv = 0`; with `wv = nothing` it is a conducting wall (`U₁ = 0`). When `S_at_surface_left` -is given (one per crossed surface), the axis is matched through a QR-conditioned axis propagator and -ua-initialized shooting propagators; otherwise through a Gaussian-reduced axis FM (STRIDE `ode_fixup`), -which requires forward crossing chunks. +# Relative difference between the two plasma response matrices above which `compute_delta_prime_matrix` warns. +const DELTA_PRIME_RESPONSE_MISMATCH = 1e-6 -## Output: PEST3-convention Δ' (deltap) - -The raw BVP solution is a 2·msing × 2·msing matrix `dp` with left/right -sub-indices at each surface, stored in `intr.delta_prime_raw`. The PEST3-convention Δ' is -[Chance, PPPL-2527]: +""" + compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> Union{Nothing,DeltaPrimeData} -``` - deltap(i,j) = dp(2i,2j) - dp(2i,2j-1) - dp(2i-1,2j) + dp(2i-1,2j-1) -``` +Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix +[Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]. -stored in `intr.delta_prime_matrix` (msing × msing). +### Arguments -## Limitations + - `intr`: Read for its mode space and singular surfaces. + - `propagators`, `chunks`, `bases`, `axis_state`: From `riccati_eulerlagrange_integration`. + - `wv`: Singfac-scaled vacuum response for the edge condition `wp + wv = 0`; `nothing` puts a conducting wall there. + - `wp`: Plasma response from `free_run`. A warning is issued when the BVP's own differs from it by more than + `DELTA_PRIME_RESPONSE_MISMATCH`. + - `psio`: Poloidal flux normalization. + - `extended_precision`: Solve in `Complex{Double64}`. -Assumes one resonant mode per surface: if any surface carries several (a multi-`n` run where one -q satisfies two `(m, n)`, e.g. q = 2 with (2, 1) and (4, 2)), it warns and skips the BVP. +### Returns -`intr.delta_prime_matrix` is the only physically valid Δ'; the per-surface ca-based -`intr.sing[*].delta_prime` is a diagnostic placeholder and need not agree with it. +A [`DeltaPrimeData`](@ref) whose `coil` is Δ_EF (empty without `wv`), or `nothing` when no surface is crossed +or, with a warning, when a surface carries more than one resonant mode. """ -function compute_delta_prime_matrix!( +function compute_delta_prime_matrix( intr::ForceFreeStatesInternal, propagators::Vector{ChunkPropagator}, - chunks::Vector{IntegrationChunk}; + chunks::Vector{IntegrationChunk}, + bases::AbstractDict, + axis_state::Matrix{ComplexF64}; wv::Union{Nothing,Matrix{ComplexF64}}=nothing, + wp::Union{Nothing,Matrix{ComplexF64}}=nothing, psio::Float64=0.0, - debug::Bool=false, - S_at_surface_left::Union{Nothing,Vector{Matrix{ComplexF64}}}=nothing, - ctrl::Union{Nothing,ForceFreeStatesControl}=nothing, - equil::Union{Nothing,Equilibrium.PlasmaEquilibrium}=nothing, - mats::Union{Nothing,MatrixSplines}=nothing + extended_precision::Bool=false ) - intr.msing == 0 && return - _has_unsupported_multi_resonance(intr) && return + intr.msing == 0 && return nothing + _has_unsupported_multi_resonance(intr) && return nothing sing, i_crossings, msing = _select_active_surfaces(intr, chunks) - msing == 0 && return + msing == 0 && return nothing N = intr.numpert_total - - use_S_axis = S_at_surface_left !== nothing && length(S_at_surface_left) == msing - - # The FM-axis fallback uses crossing-chunk propagators as forward maps; backward chunks would give a wrong Δ'. - if !use_S_axis - for ic in i_crossings - chunks[ic].direction == 1 || - error( - "compute_delta_prime_matrix!: FM-axis fallback (use_S_axis=false) requires forward crossing chunks; " * - "chunk $ic has direction=$(chunks[ic].direction). Either provide S_at_surface_left or use bidirectional=false." - ) - end - end - - Phi_L_mats, Phi_R_mats, Phi_R_halves = _assemble_segment_propagators( - propagators, chunks, i_crossings, msing, N, use_S_axis) - ipert_all = [1 + sing[j].m[1] - intr.mlow + (sing[j].n[1] - intr.nlow) * intr.mpert for j in 1:msing] - has_ua = all(j -> !isempty(sing[j].ua_left), 1:msing) - T_left_mats, T_right_mats, T_left_inv, T_right_inv = - _build_asymptotic_basis_matrices(sing, has_ua, N, msing) - - debug && _log_bvp_setup(chunks, sing, S_at_surface_left, use_S_axis, has_ua, - Phi_L_mats, Phi_R_mats, Phi_R_halves, ipert_all, wv, psio, N, msing) - - if use_S_axis - uShootR, uShootL, uAxis = _build_S_axis_shooting_propagators( - propagators, chunks, i_crossings, sing, msing, N, - T_left_mats, T_right_mats, has_ua, ctrl, equil, mats, intr, debug) - debug && _log_S_axis_shooting_propagators(uShootR, uShootL, uAxis, - S_at_surface_left, T_left_mats, - ipert_all, has_ua, msing, N) - M, nMat, col_edge = _assemble_bvp_S_axis( - uShootR, uShootL, uAxis, ipert_all, msing, N, wv, psio) - else - M, nMat, col_edge = _assemble_bvp_FM_axis( - Phi_L_mats, Phi_R_mats, ipert_all, msing, N, - T_left_inv, T_right_inv, has_ua, wv, psio) - end - - if debug - @info "Δ' BVP: nMat=$nMat, rank(M)=$(rank(M)), cond(M)=$(@sprintf("%.2e", cond(M)))" - end - # rpec coil-response block: needs the S-axis row layout that `_solve_bvp_edge_coil` assumes - # for its edge rows, and a vacuum edge in the assembled matrix (col_edge in junc_rows). - if use_S_axis && wv !== nothing - intr.delta_coil = _solve_bvp_edge_coil(M, col_edge, msing, N, ipert_all) + uShootR, uShootL = _shooting_matrices(propagators, chunks, bases, i_crossings) + uAxis = Matrix(qr(axis_state).Q)[:, 1:N] + M, col_edge = _assemble_bvp(uShootR, uShootL, uAxis, ipert_all, msing, N, wv, psio) + + # Δ_EF: needs a vacuum edge in the assembled matrix. + delta_ef = Matrix{ComplexF64}(undef, 0, 0) + if wv !== nothing + delta_ef, edge_coefficients = _solve_bvp_delta_ef(M, col_edge, msing, N, ipert_all) + if wp !== nothing + # Unit edge displacement, so the edge U₂ is the plasma response times ψ₀². + wp_bvp = uShootR[msing][(N+1):(2N), :] * edge_coefficients ./ psio^2 + mismatch = norm(wp_bvp - wp) / norm(wp) + if mismatch > DELTA_PRIME_RESPONSE_MISMATCH + @warn "Riccati: the plasma response from the Δ' system differs from the axis-to-edge one by $(@sprintf("%.1e", mismatch)) " * + "(relative), so the chunk propagators have lost accuracy. Raise [Riccati] nchunks (now $(length(chunks)) chunks); " * + "beyond about 150 poloidal harmonics also set extended_precision_bvp." + end + end end - - deltap, dp_raw_persisted = _solve_bvp_and_combine_pest3( - M, msing, N, nMat, use_S_axis, ipert_all, col_edge, ctrl, debug) - - # The raw side-major D' (Fortran gal_write_delta layout) feeds `pest3_decompose`. - intr.delta_prime_matrix = deltap - intr.delta_prime_raw = dp_raw_persisted + # The raw side-major D' (Fortran gal_write_delta layout) feeds `pest3_decompose`; Riccati leaves the blocks unfilled. + delta_prime, delta_prime_raw = _solve_bvp_and_combine_pest3(M, msing, N, ipert_all, extended_precision) + return DeltaPrimeData(delta_prime, delta_prime_raw, delta_ef, nothing, nothing, nothing) end # Column index helpers for the BVP matrix. j is the 1-based singular-surface index, @@ -131,7 +78,7 @@ function _has_unsupported_multi_resonance(intr::ForceFreeStatesInternal) n_res_per_surface = [length(intr.sing[j].m) for j in 1:msing] any(>(1), n_res_per_surface) || return false offenders = [(j, intr.sing[j].m, intr.sing[j].n) for j in 1:msing if n_res_per_surface[j] > 1] - @warn "compute_delta_prime_matrix!: skipping inter-surface Δ' BVP because some surfaces carry more than one resonant mode " * + @warn "compute_delta_prime_matrix: skipping inter-surface Δ' BVP because some surfaces carry more than one resonant mode " * "(multi-n collision; generalization tracked as follow-up). " * "Per-surface Δ' is unaffected. Multi-resonance surfaces: $offenders" return true @@ -148,120 +95,36 @@ function _select_active_surfaces(intr::ForceFreeStatesInternal, chunks::Vector{I if msing_active < msing excluded = setdiff(1:msing, sing_indices) excluded_ms = [intr.sing[j].m for j in excluded] - @debug "compute_delta_prime_matrix!: $msing singular surfaces, $msing_active crossed (excluded: m=$excluded_ms)" + @debug "compute_delta_prime_matrix: $msing singular surfaces, $msing_active crossed (excluded: m=$excluded_ms)" end sing = [intr.sing[si] for si in sing_indices] return sing, i_crossings, msing_active end -# Assemble per-surface crossing FMs (Phi_L), inter-surface and edge FMs (Phi_R; Phi_R[1] only for the -# FM-axis fallback), and midpoint-split halves (Phi_R_halves) used only by the debug diagnostics. -function _assemble_segment_propagators(propagators::Vector{ChunkPropagator}, - chunks::Vector{IntegrationChunk}, - i_crossings::Vector{Int}, msing::Int, N::Int, - use_S_axis::Bool) - Phi_L_mats = [assemble_fm_matrix(propagators, i_crossings[j]:i_crossings[j]) for j in 1:msing] - Phi_R_mats = Vector{Matrix{ComplexF64}}(undef, msing + 1) - if !use_S_axis - Phi_R_mats[1] = assemble_fm_matrix(propagators, 1:(i_crossings[1]-1); condition=true) - end - for j in 2:msing - Phi_R_mats[j] = assemble_fm_matrix(propagators, (i_crossings[j-1]+1):(i_crossings[j]-1)) - end - Phi_R_mats[msing+1] = assemble_fm_matrix(propagators, (i_crossings[msing]+1):length(chunks)) - - Phi_R_halves = Vector{Tuple{Matrix{ComplexF64},Matrix{ComplexF64}}}(undef, msing - 1) - for j in 1:(msing-1) - chunk_start = i_crossings[j] + 1 - chunk_end = i_crossings[j+1] - 1 - n_chunks = chunk_end - chunk_start + 1 - if n_chunks >= 2 - i_mid = chunk_start + div(n_chunks, 2) - 1 - Phi_left_half = assemble_fm_matrix(propagators, chunk_start:i_mid) - Phi_right_half = assemble_fm_matrix(propagators, (i_mid+1):chunk_end) - Phi_R_halves[j] = (Phi_left_half, Phi_right_half) - else - Phi_R_halves[j] = (Matrix{ComplexF64}(I, 2N, 2N), Phi_R_mats[j+1]) - end - end - return Phi_L_mats, Phi_R_mats, Phi_R_halves -end - -# Asymptotic-basis transformation T = [ua[:,:,1]; ua[:,:,2]] maps (big, small) coefficients to the raw -# state; ua columns 1:N are big (z^{-α}) and N+1:2N small (z^{+α}) solutions. -function _build_asymptotic_basis_matrices(sing::Vector{SingType}, has_ua::Bool, N::Int, msing::Int) - T_left_mats = Vector{Matrix{ComplexF64}}(undef, msing) - T_right_mats = Vector{Matrix{ComplexF64}}(undef, msing) - T_left_inv = Vector{Matrix{ComplexF64}}(undef, msing) - T_right_inv = Vector{Matrix{ComplexF64}}(undef, msing) - if has_ua - for j in 1:msing - sp = sing[j] - T_left_mats[j] = [sp.ua_left[:, :, 1]; sp.ua_left[:, :, 2]] - T_right_mats[j] = [sp.ua_right[:, :, 1]; sp.ua_right[:, :, 2]] - T_left_inv[j] = inv(T_left_mats[j]) - T_right_inv[j] = inv(T_right_mats[j]) - end - end - return T_left_mats, T_right_mats, T_left_inv, T_right_inv -end - -# Build the S-axis shooting propagators uShootR (surface j right → midpoint), uShootL (surface j -# left → midpoint, backward), and the QR-conditioned axis propagator uAxis that uShootL[1] meets. -function _build_S_axis_shooting_propagators( - propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, - i_crossings::Vector{Int}, sing::Vector{SingType}, msing::Int, N::Int, - T_left_mats::Vector{Matrix{ComplexF64}}, T_right_mats::Vector{Matrix{ComplexF64}}, - has_ua::Bool, ctrl, equil, mats, intr::ForceFreeStatesInternal, debug::Bool) - - can_reintegrate = has_ua && ctrl !== nothing && equil !== nothing && mats !== nothing +# Shooting matrices of the BVP [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eqs. 33-35]: `uShootR[j]` and +# `uShootL[j]` map the asymptotic coefficients right and left of surface j to the state at the matching point +# toward the next and the previous surface. +function _shooting_matrices(propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, + bases::AbstractDict, i_crossings::Vector{Int}) + msing = length(i_crossings) + matrix(i) = [propagators[i].u[:, :, 1]; propagators[i].u[:, :, 2]] uShootR = Vector{Matrix{ComplexF64}}(undef, msing) - uShootL = Vector{Matrix{ComplexF64}}(undef, msing) # uShootL[1] handled separately below - + uShootL = Vector{Matrix{ComplexF64}}(undef, msing) for j in 1:msing - shoot_range_R = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:right) - if debug && !isempty(shoot_range_R) - psi_surf_R = chunks[first(shoot_range_R)].psi_start - psi_mid_R = chunks[last(shoot_range_R)].psi_end - psi_ua_R = sing[j].psi_ua_right - @info " uShootR[$j]: shoot_range=$(shoot_range_R), psi_chunk=$(@sprintf("%.6f", psi_surf_R)), psi_ua=$(@sprintf("%.6f", psi_ua_R)), psi_mid=$(@sprintf("%.6f", psi_mid_R)), Δψ_fix=$(@sprintf("%.6e", psi_ua_R - psi_surf_R))" - end - if can_reintegrate && !isempty(shoot_range_R) - uShootR[j] = integrate_fm_with_ua_ic(chunks, shoot_range_R, sing[j].ua_right, - ctrl, equil, mats, intr; backward=false, psi_ua=sing[j].psi_ua_right) - else - T_init = has_ua ? T_right_mats[j] : nothing - uShootR[j] = assemble_fm_matrix(propagators, shoot_range_R; T_init=T_init) - end - - # uShootL[j>=2]: backward from surface j left to midpoint. uShootL[1] handled below. - j == 1 && continue - shoot_range_L = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:left) - if debug - psi_mid = chunks[first(shoot_range_L)].psi_start - psi_surf = chunks[last(shoot_range_L)].psi_end - psi_ua_L = sing[j].psi_ua_left - @info " uShootL[$j]: shoot_range=$(shoot_range_L), psi_mid=$(@sprintf("%.6f", psi_mid)), psi_chunk=$(@sprintf("%.6f", psi_surf)), psi_ua=$(@sprintf("%.6f", psi_ua_L)), Δψ_fix=$(@sprintf("%.6e", psi_ua_L - psi_surf))" - end - if can_reintegrate && !isempty(shoot_range_L) - uShootL[j] = integrate_fm_with_ua_ic(chunks, shoot_range_L, sing[j].ua_left, - ctrl, equil, mats, intr; backward=true, psi_ua=sing[j].psi_ua_left) + if i_crossings[j] == length(chunks) + # The edge is the surface's right inner-layer boundary. + right = bases[chunks[i_crossings[j]].ising].right + uShootR[j] = [right[:, :, 1]; right[:, :, 2]] else - T_init = has_ua ? T_left_mats[j] : nothing - uShootL[j] = assemble_fm_matrix(propagators, shoot_range_L; T_init=T_init) + # The chunk after the surface starts from the right basis; the rest multiply on. + range_R = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:right) + uShootR[j] = foldl((X, i) -> matrix(i) * X, range_R[2:end]; init=matrix(first(range_R))) end + # The crossing chunk carries the left basis back to its start; forward chunks before it are inverted. + range_L = j == 1 ? (1:0) : _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:left) + uShootL[j] = foldl((X, i) -> matrix(i) \ X, reverse(range_L); init=matrix(i_crossings[j])) end - - uAxis, i_axis_mid = _build_conditioned_axis_propagator(propagators, i_crossings, N) - uShootL[1] = _build_uShootL_first(propagators, chunks, i_crossings, sing, - T_left_mats, has_ua, can_reintegrate, i_axis_mid, - ctrl, equil, mats, intr, N) - if debug - shoot_range_L1 = (i_axis_mid+1):(i_crossings[1]-1) - @info " Axis propagator: $(i_axis_mid) chunks, cond=$(@sprintf("%.2e", cond(uAxis)))" - @info " uShootL[1]: range=$(shoot_range_L1), cond=$(@sprintf("%.2e", cond(uShootL[1])))" - end - return uShootR, uShootL, uAxis + return uShootR, uShootL end # Chunk range from surface j to the ψ midpoint toward the next surface (`:right`; the edge for @@ -289,59 +152,14 @@ function _midpoint_shoot_range(chunks::Vector{IntegrationChunk}, i_crossings::Ve return side === :right ? (chunk_start:i_mid_inter) : ((i_mid_inter+1):chunk_end) end -# Propagate [0; I] from the axis with a QR fixup after each chunk (Fortran ode_fixup), stopping one -# chunk before the first surface so uShootL[1] spans a single well-conditioned chunk. -function _build_conditioned_axis_propagator(propagators::Vector{ChunkPropagator}, - i_crossings::Vector{Int}, N::Int) - n_pre_cross = i_crossings[1] - 1 - i_axis_mid = max(1, n_pre_cross - 1) - uAxis = zeros(ComplexF64, 2N, N) - for i in 1:N - uAxis[N+i, i] = 1 - end - for ic in 1:i_axis_mid - prop = propagators[ic] - upper_old = uAxis[1:N, :] - lower_old = uAxis[(N+1):2N, :] - uAxis[1:N, :] .= prop.block_upper_ic[:, :, 1] * upper_old .+ prop.block_lower_ic[:, :, 1] * lower_old - uAxis[(N+1):2N, :] .= prop.block_upper_ic[:, :, 2] * upper_old .+ prop.block_lower_ic[:, :, 2] * lower_old - Q, _ = qr(uAxis) - uAxis .= Matrix(Q)[:, 1:N] - end - for j in 1:N - uAxis[:, j] ./= norm(@view uAxis[:, j]) - end - return uAxis, i_axis_mid -end - -# uShootL[1]: backward propagator from surface 1's left boundary to the axis midpoint; T_left_mats[1] -# (or the identity without ua) when that range is empty. -function _build_uShootL_first(propagators::Vector{ChunkPropagator}, - chunks::Vector{IntegrationChunk}, i_crossings::Vector{Int}, - sing::Vector{SingType}, T_left_mats::Vector{Matrix{ComplexF64}}, - has_ua::Bool, can_reintegrate::Bool, i_axis_mid::Int, - ctrl, equil, mats, intr::ForceFreeStatesInternal, N::Int) - shoot_range_L1 = (i_axis_mid+1):(i_crossings[1]-1) - if can_reintegrate && !isempty(shoot_range_L1) - return integrate_fm_with_ua_ic(chunks, shoot_range_L1, sing[1].ua_left, - ctrl, equil, mats, intr; - backward=true, psi_ua=sing[1].psi_ua_left) - elseif !isempty(shoot_range_L1) - return assemble_fm_matrix(propagators, shoot_range_L1; - T_init=has_ua ? T_left_mats[1] : nothing) - else - return has_ua ? T_left_mats[1] : Matrix{ComplexF64}(I, 2N, 2N) - end -end - -# Assemble the BVP matrix M with the axis matched to the conditioned axis propagator, avoiding the -# ill-conditioned full axis FM. Fortran-matched layout, nMat = (2 + 4·msing)·N. Returns (M, nMat, col_edge). -function _assemble_bvp_S_axis(uShootR::Vector{Matrix{ComplexF64}}, +# Assemble the BVP matrix M with the axis matched to the axis-regular solutions `uAxis` at the start of the first +# crossing chunk. Fortran-matched layout, nMat = (2 + 4·msing)·N. Returns (M, col_edge). +function _assemble_bvp(uShootR::Vector{Matrix{ComplexF64}}, uShootL::Vector{Matrix{ComplexF64}}, uAxis::Matrix{ComplexF64}, ipert_all::Vector{Int}, msing::Int, N::Int, wv::Union{Nothing,Matrix{ComplexF64}}, psio::Float64) - # STRIDE global BVP block structure [Glasser-Kolemen 2018 PoP 25, 032501 Eq. 37]. + # STRIDE global BVP block structure [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]. nMat = (2 + 4 * msing) * N col_axis = 1:N col_edge = (nMat-N+1):nMat @@ -390,90 +208,35 @@ function _assemble_bvp_S_axis(uShootR::Vector{Matrix{ComplexF64}}, M[row_offset, _col_right(j, N)[ipert_j]] = 1 end @assert row_offset == nMat "Row count mismatch: expected $nMat, got $row_offset" - return M, nMat, col_edge + return M, col_edge end -# Coil-response block for the Eq. (37) edge [Glasser-Kolemen 2018 PoP 25, 032501]: impose the rpec edge BC -# (RDCON `gal_set_boundary`, unit source per poloidal mode) and read the small-solution coefficient at each -# surface side, solving all N modes with one factorization. Returns delta_coil (2·msing × N). -function _solve_bvp_edge_coil(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int, ipert_all::Vector{Int}) +# Δ_EF (2·msing × N): the small-solution coefficient at each surface side per unit displacement of each edge mode, +# from the BVP with its edge fixed. Also returns the coefficients right of the last surface (2N × N). +function _solve_bvp_delta_ef(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int, ipert_all::Vector{Int}) nMat = size(M, 1) bot = (nMat-2msing-N+1):(nMat-2msing) # Eq. (38) bottom rows, carrying the W_V block Mc = copy(M) Mc[bot, :] .= 0 Mc[bot, col_edge] .= I(N) # Dirichlet edge: the edge coefficients equal the source B = zeros(ComplexF64, nMat, N) - B[bot, :] .= I(N) # unit drive, one column per edge poloidal mode + B[bot, :] .= I(N) # unit displacement, one column per edge poloidal mode X = lu(Mc) \ B - delta_coil = zeros(ComplexF64, 2msing, N) + delta_ef = zeros(ComplexF64, 2msing, N) for j in 1:msing row_left = _col_left(j, N)[ipert_all[j]+N] row_right = _col_right(j, N)[ipert_all[j]+N] - @views delta_coil[2j-1, :] .= X[row_left, :] - @views delta_coil[2j, :] .= X[row_right, :] + @views delta_ef[2j-1, :] .= X[row_left, :] + @views delta_ef[2j, :] .= X[row_right, :] end - return delta_coil + return delta_ef, X[_col_right(msing, N), :] end -# Fallback BVP assembly with FM-based axis BC (used when no Riccati S matrices are available). -# Uses the conditioned axis propagator Phi_R[1][:,N+1:2N] in place of S-axis matching. -function _assemble_bvp_FM_axis(Phi_L_mats::Vector{Matrix{ComplexF64}}, - Phi_R_mats::Vector{Matrix{ComplexF64}}, ipert_all::Vector{Int}, - msing::Int, N::Int, - T_left_inv::Vector{Matrix{ComplexF64}}, - T_right_inv::Vector{Matrix{ComplexF64}}, has_ua::Bool, - wv::Union{Nothing,Matrix{ComplexF64}}, psio::Float64) - nMat = (2 + 4 * msing) * N - col_axis = 1:N - col_edge = (N+4N*msing+1):nMat - M = zeros(ComplexF64, nMat, nMat) - - M[1:2N, (N+1):(N+2N)] .= Phi_L_mats[1] - M[1:2N, col_axis] .= -view(Phi_R_mats[1], :, (N+1):2N) - - row_drive_base = 2N + (4N - 2) * msing - for j in 1:msing - ipert_j = ipert_all[j] - cl = _col_left(j, N) - cr = _col_right(j, N) - row_cont = 2N + (4N - 2) * (j - 1) - for i in 1:2N - if i != ipert_j && i != ipert_j + N - row_cont += 1 - M[row_cont, cl[i]] = 1 - M[row_cont, cr[i]] = -1 - end - end - junc_rows = (row_cont+1):(2N+(4N-2)*j) - if j < msing - M[junc_rows, cr] .= Phi_R_mats[j+1] - M[junc_rows, _col_left(j + 1, N)] .= -Phi_L_mats[j+1] - else - M[junc_rows, cr] .= Phi_R_mats[msing+1] - if wv !== nothing - M[junc_rows[1:N], col_edge] .= -I(N) - M[junc_rows[(N+1):end], col_edge] .= wv .* psio^2 - else - M[junc_rows[(N+1):end], col_edge] .= -I(N) - end - end - if has_ua - M[row_drive_base+2j-1, cl] .= T_left_inv[j][ipert_j, :] - M[row_drive_base+2j, cr] .= T_right_inv[j][ipert_j, :] - else - M[row_drive_base+2j-1, cl[ipert_j]] = 1 - M[row_drive_base+2j, cr[ipert_j]] = 1 - end - end - return M, nMat, col_edge -end - -# Solve the BVP and apply the PEST3 four-term combination. -function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, nMat::Int, - use_S_axis::Bool, ipert_all::Vector{Int}, col_edge, - ctrl, debug::Bool) +# Solve the BVP and apply the PEST3 four-term combination, in Complex{Double64} when `extended_precision`. +function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}, extended_precision::Bool) + nMat = size(M, 1) s2 = 2 * msing - Tc = (ctrl === nothing || ctrl.algorithm.extended_precision_bvp) ? Complex{Double64} : ComplexF64 + Tc = extended_precision ? Complex{Double64} : ComplexF64 M_solve = Tc.(M) M_lu = lu(M_solve; check=false) use_lu = issuccess(M_lu) @@ -482,18 +245,13 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, @warn "Δ' BVP: LU factorization singular (rank $(rank(M))/$nMat), using pseudo-inverse fallback" end + # One solve per surface side, driving that side's big-solution coefficient. dp_raw = zeros(Tc, s2, s2) b = zeros(Tc, nMat) - for jsing in 1:msing, side in 1:2 - dRow = 2jsing - (2 - side) + for dRow in 1:s2 fill!(b, 0) - drive_row = use_S_axis ? (nMat - s2 + dRow) : (2N + (4N - 2) * msing + dRow) - b[drive_row] = 1 + b[nMat-s2+dRow] = 1 x = use_lu ? (M_lu \ b) : (M_pinv * b) - - debug && _log_bvp_solve(x, b, M_solve, jsing, side, dRow, msing, N, - ipert_all, col_edge, use_S_axis) - for ksing in 1:msing ipert_k = ipert_all[ksing] dp_raw[dRow, 2ksing-1] = x[_col_left(ksing, N)[ipert_k+N]] @@ -501,123 +259,14 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, end end - # PEST3 four-term combination [Chance PPPL-2527; Glasser-Kolemen 2018 PoP 25, 032501 Eq. 31]. - # Δ'[i,j] = (NW − NE − SW + SE) on each 2×2 block of dp_raw. + # PEST3 four-term combination [Chance PPPL-2527]: Δ'[i,j] = (NW − NE − SW + SE) on each 2×2 block of dp_raw. deltap = zeros(Tc, msing, msing) for i in 1:msing, j in 1:msing deltap[i, j] = dp_raw[2i, 2j] - dp_raw[2i, 2j-1] - dp_raw[2i-1, 2j] + dp_raw[2i-1, 2j-1] end - - debug && _log_bvp_pest3(dp_raw, deltap, s2, msing) return ComplexF64.(deltap), ComplexF64.(dp_raw) end -# Logging helpers for `compute_delta_prime_matrix!`. Called only when debug=true. -function _log_bvp_setup(chunks, sing, S_at_surface_left, use_S_axis, has_ua, - Phi_L_mats, Phi_R_mats, Phi_R_halves, ipert_all, wv, psio, N, msing) - @info "Δ' BVP: $(length(chunks)) chunks, $msing surfaces, N=$N" - @info "Δ' BVP: Axis BC: $(use_S_axis ? "S-based (Riccati)" : "FM-based (conditioned)")" - @info "Δ' BVP: Asymptotic basis: $(has_ua ? "available" : "NOT available (raw basis driving)")" - if use_S_axis - for j in 1:msing - @info " S_left[$j]: max=$(@sprintf("%.2e", maximum(abs, S_at_surface_left[j]))), cond=$(@sprintf("%.2e", cond(S_at_surface_left[j])))" - end - end - if has_ua - for j in 1:msing - sp = sing[j] - T_l = [sp.ua_left[:, :, 1]; sp.ua_left[:, :, 2]] - T_r = [sp.ua_right[:, :, 1]; sp.ua_right[:, :, 2]] - @info " Surface $j: cond(T_left)=$(@sprintf("%.2e", cond(T_l))), cond(T_right)=$(@sprintf("%.2e", cond(T_r)))" - ipert_j = ipert_all[j] - @info " Surface $j ua_left (ipert=$ipert_j, psi_ua_left=$(@sprintf("%.8f", sp.psi_ua_left))):" - for i in 1:min(5, N) - @info " ua($i,$ipert_j,1)=$(@sprintf("%16.8e %16.8e", real(sp.ua_left[i,ipert_j,1]), imag(sp.ua_left[i,ipert_j,1]))) ua($i,$ipert_j,2)=$(@sprintf("%16.8e %16.8e", real(sp.ua_left[i,ipert_j,2]), imag(sp.ua_left[i,ipert_j,2])))" - end - @info " small: ua(1,$(ipert_j+N),1)=$(@sprintf("%16.8e %16.8e", real(sp.ua_left[1,ipert_j+N,1]), imag(sp.ua_left[1,ipert_j+N,1])))" - end - end - for j in 1:(msing-1) - Phi_L_h, Phi_R_h = Phi_R_halves[j] - @info " Inter-surface $j→$(j+1): half_L cond=$(@sprintf("%.2e",cond(Phi_L_h))), half_R cond=$(@sprintf("%.2e",cond(Phi_R_h))), full cond=$(@sprintf("%.2e",cond(Phi_R_mats[j+1])))" - end - @info " Phi_R[$(msing+1)] (edge): cond=$(@sprintf("%.2e",cond(Phi_R_mats[msing+1])))" - for j in 1:msing - @info " Surface $j (m=$(sing[j].m[1])): ipert=$(ipert_all[j]), cond(Phi_L)=$(@sprintf("%.2e", cond(Phi_L_mats[j])))" - end - @info "Δ' BVP: Vacuum BC $(wv === nothing ? "off (conducting wall)" : "on (psio=$psio)")" - for j in 1:msing - if !isempty(sing[j].delta_prime) - @info " Surface $j ca-based Δ' = $(@sprintf("%.6f%+.6fi", real(sing[j].delta_prime[1]), imag(sing[j].delta_prime[1])))" - end - end -end - -function _log_S_axis_shooting_propagators(uShootR, uShootL, uAxis, S_at_surface_left, - T_left_mats, ipert_all, has_ua, msing, N) - @info " Shooting propagators (S-based axis BC, no axis unknowns):" - for j in 1:msing - shoot_R_str = @sprintf("%.2e", cond(uShootR[j])) - shoot_L_str = j >= 2 ? @sprintf("%.2e", cond(uShootL[j])) : "N/A (S axis BC)" - @info " uShootL[$j]: cond=$shoot_L_str, uShootR[$j]: cond=$shoot_R_str" - end - S1 = S_at_surface_left[1] - if has_ua - T1 = T_left_mats[1] - axis_BC = T1[1:N, :] - S1 * T1[(N+1):2N, :] - @info " S-axis BC matrix: cond=$(@sprintf("%.2e", cond(axis_BC)))" - end - for j in 1:msing - ipert_j = ipert_all[j] - col_norms_R = [norm(view(uShootR[j], :, k)) for k in 1:2N] - @info " uShootR[$j] column norms: min=$(@sprintf("%.2e", minimum(col_norms_R))), max=$(@sprintf("%.2e", maximum(col_norms_R)))" - @info " uShootR[$j] col ipert=$ipert_j norm=$(@sprintf("%.2e", col_norms_R[ipert_j])), col ipert+N=$(ipert_j+N) norm=$(@sprintf("%.2e", col_norms_R[ipert_j+N]))" - if j >= 2 - col_norms_L = [norm(view(uShootL[j], :, k)) for k in 1:2N] - @info " uShootL[$j] column norms: min=$(@sprintf("%.2e", minimum(col_norms_L))), max=$(@sprintf("%.2e", maximum(col_norms_L)))" - @info " uShootL[$j] col ipert=$ipert_j norm=$(@sprintf("%.2e", col_norms_L[ipert_j])), col ipert+N=$(ipert_j+N) norm=$(@sprintf("%.2e", col_norms_L[ipert_j+N]))" - end - end - for j in 1:(msing-1) - mid_block = hcat(uShootR[j], -uShootL[j+1]) - @info " Midpoint $j→$(j+1): cond([uShootR[$j] | -uShootL[$(j+1)]]) = $(@sprintf("%.2e", cond(mid_block)))" - col_norms_Ljp1 = [norm(view(uShootL[j+1], :, k)) for k in 1:2N] - @info " uShootL[$(j+1)] all col norms: $([(@sprintf("%.2e", c)) for c in col_norms_Ljp1])" - end -end - -function _log_bvp_solve(x, b, M_solve, jsing, side, dRow, msing, N, - ipert_all, col_edge, use_S_axis) - residual = norm(ComplexF64.(M_solve * x - b)) - side_str = side == 1 ? "left" : "right" - @info " BVP solve: jsing=$jsing side=$side_str (dRow=$dRow): ||Mx-b||=$(@sprintf("%.2e", residual)), ||x||=$(@sprintf("%.2e", Float64(norm(x))))" - for ks in 1:msing - ipert_ks = ipert_all[ks] - cl = _col_left(ks, N) - cr = _col_right(ks, N) - xl_big = ComplexF64(x[cl[ipert_ks]]) - xl_small = ComplexF64(x[cl[ipert_ks+N]]) - xr_big = ComplexF64(x[cr[ipert_ks]]) - xr_small = ComplexF64(x[cr[ipert_ks+N]]) - @info " surf $ks: x_left[big]=$(@sprintf("%+.4e%+.4ei", real(xl_big), imag(xl_big))), x_left[small]=$(@sprintf("%+.4e%+.4ei", real(xl_small), imag(xl_small)))" - @info " surf $ks: x_right[big]=$(@sprintf("%+.4e%+.4ei", real(xr_big), imag(xr_big))), x_right[small]=$(@sprintf("%+.4e%+.4ei", real(xr_small), imag(xr_small)))" - @info " surf $ks: ||x_left||=$(@sprintf("%.2e", Float64(norm(x[cl])))), ||x_right||=$(@sprintf("%.2e", Float64(norm(x[cr]))))" - end - if use_S_axis - @info " ||x_edge||=$(@sprintf("%.2e", Float64(norm(x[col_edge]))))" - end -end - -function _log_bvp_pest3(dp_raw, deltap, s2, msing) - @info "Δ' BVP: Full dp_raw matrix ($(s2)×$(s2)):" - for i in 1:s2 - row_str = join([@sprintf("%+.6e", Float64(real(dp_raw[i, j]))) for j in 1:s2], " ") - @info " dp_raw[$i,:] = $row_str" - end - @info "Δ' BVP: Raw dp diagonal = $([@sprintf("%.4f%+.4fi", Float64(real(dp_raw[i,i])), Float64(imag(dp_raw[i,i]))) for i in 1:s2])" - @info "Δ' BVP: deltap diagonal = $([@sprintf("%.4f%+.4fi", real(deltap[i,i]), imag(deltap[i,i])) for i in 1:msing])" -end - """ pest3_decompose(dp_raw::AbstractMatrix) -> NamedTuple{(:A, :B, :Γ, :Δ)} @@ -638,12 +287,11 @@ where `RR = dp_raw[2i, 2j]`, `RL = dp_raw[2i, 2j−1]`, No Pletzer–Dewar ½ prefactor, matching Fortran RDCON; it cancels in `det(D' − D(γ)) = 0`. -The Δ' block returned here equals `intr.delta_prime_matrix` (the m×m PEST3 -tearing projection computed inside `compute_delta_prime_matrix!`). +The Δ' block returned here equals `DeltaPrimeData.matrix`. # Arguments - - `dp_raw` — 2m×2m complex matrix (typically `intr.delta_prime_raw`). + - `dp_raw` — 2m×2m complex matrix (typically `DeltaPrimeData.raw`). # Returns diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index ef85b7bfa4..32524a8476 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -1,228 +1,171 @@ """ - Riccati/ - Dual Riccati reformulation of the Euler-Lagrange ODE + riccati_eulerlagrange_integration(ctrl, equil, mats, intr) -> (odet, riccati) -Tracks the dual Riccati matrix S = U₁·U₂⁻¹ = P⁻¹ (P = U₂·U₁⁻¹ the plasma response matrix), which stays -bounded near singular surfaces where U₁ and U₂ grow exponentially. Reference: Glasser (2018) Phys. Plasmas -25, 032507 — Eq. 19 (dual form), dS/dψ = w†·F̄⁻¹·w − S·Ḡ·S with w = Q − K̄·S. +Integrate the Euler-Lagrange equations from the axis to `intr.psilim` with parallel chunk propagators +[Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507; Glasser & Kolemen 2018, Phys. Plasmas 25, 082502]. -The explicit Riccati ODE is not integrated directly: its quadratic term defeats relative error control when -|S| is large. Instead the linear EL ODE (`sing_der!`) is integrated in (U₁, U₂), and the exact change of -variables `renormalize_riccati_inplace!` resets the state to (S, I) whenever max(|U₁|) or max(|U₂|) exceeds -`renorm_threshold`, the Riccati analogue of Gaussian reduction. - -## Storage convention - - - During a chunk: u[:,:,1] = U₁ (starts as S), u[:,:,2] = U₂ (starts as I). - - After renormalization: u[:,:,1] = S, u[:,:,2] = I, so downstream U₁/U₂ ratios (wp in Free.jl, the - fixed-boundary criterion) read S directly. - - Axis: S(ψ₀) = 0 (U₁ = 0, U₂ = I), unless a positive `ctrl.frobenius_psi_max` at or above the start - opts into the diagonal Frobenius init (U₂ = I, per-mode U₁). - -Unlike the forward path, `riccati_integrator_callback!` renormalizes instead of Gaussian reduction, -`riccati_cross_ideal_singular_surf!` crosses without Gaussian reduction, and `transform_u!` is a no-op. -""" - -""" - riccati_eulerlagrange_integration(ctrl, equil, mats, intr) -> (odet, propagators, chunks, S_left) - -The Riccati/STRIDE integrator: solves the same system as [`forward_eulerlagrange_integration`](@ref) -by integrating chunk fundamental matrices (propagators) concurrently with `Threads.@threads`, -assembling them serially with Riccati crossings (no Gaussian reduction), and re-integrating the -outer plasma with `riccati_integrate_chunk!` for dense, bounded checkpoints. Crossing chunks are -integrated backward and inverted by LU, which keeps them well-conditioned at large N (STRIDE, -Glasser 2018 Phys. Plasmas 25, 032501). The trailing three return values feed the Δ' BVP in -`compute_delta_prime_matrix!`; this is the only branch that produces them. - -Select with `Riccati()`, or `integrator = "Riccati"` in a deck's `[ForceFreeStates]`. Requires -`singfac_min != 0`. Results do not depend on the thread count; `ctrl.algorithm.nchunks` is the only -tunable. `odet.u_store` holds chunk-endpoint Riccati states, not the EL basis -(`odet.u_store_el_basis == false`), so PerturbedEquilibrium and the HDF5 ξ datasets require `Forward()`. +Returns `odet`, whose stores hold the state as (S, I), S = U₁U₂⁻¹, at every stored solver step, and `riccati`, +the inputs of `compute_delta_prime_matrix`: `(; propagators, chunks, bases, axis_state)`, with `axis_state` +(2N × N) the state entering the first crossing chunk. """ function riccati_eulerlagrange_integration( ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal ) odet = _initialize_parallel_odet(ctrl, equil, mats, intr) - chunks, propagators, odet_proxies = _setup_parallel_chunks_and_proxies(odet, ctrl, intr) - intr.verbose && _log_parallel_start(odet, equil, chunks) - - _run_parallel_bvp_phase!(propagators, chunks, ctrl, equil, mats, intr, odet_proxies) - - # Harvest thread-local solver-step counts; the outer re-integration counts via its own callback. - odet.total_steps += sum(p.total_steps for p in odet_proxies) - - S_at_surface_left, last_crossing_step = - _assemble_propagators_serially!(odet, propagators, chunks, ctrl, equil, mats, intr) - - _reintegrate_outer_plasma!(odet, last_crossing_step, ctrl, equil, mats, intr) + chunks = balance_integration_chunks(chunk_el_integration_bounds(odet, ctrl, intr; bidirectional=true), ctrl, intr) + bases = asymptotic_bases(chunks, ctrl, equil, mats, intr) + if intr.verbose + @info " ψ = $((@sprintf "%.3f" odet.psifac)), q = $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac)))" + @info " Riccati FM: $(length(chunks)) chunks over $(Threads.nthreads()) thread$(Threads.nthreads() == 1 ? "" : "s")" + end - chunks, propagators = _handle_edge_dW_scan!(odet, chunks, propagators, ctrl, equil, mats, intr) - resize!(S_at_surface_left, intr.msing) # one per surviving surface, as the Δ' BVP requires + propagators = chunk_propagators(chunks, bases, ctrl.algorithm.eulerlagrange_tolerance, equil, mats, ModeIndices(intr)) + odet.total_steps += sum(p -> length(p.psi) - 1, propagators) + axis_state = _assemble_propagators_serially!(odet, propagators, chunks, ctrl, equil, intr) + _handle_edge_dW_scan!(odet, chunks, propagators, bases, ctrl, equil, mats, intr) + compute_delta_prime_from_ca!(odet, intr, equil) - # compute_delta_prime_matrix! runs later, after free_run supplies the vacuum edge response wv. if intr.verbose @info "Evaluating fixed-boundary stability criterion" end odet.nzero = evaluate_stability_criterion!(odet, equil.profiles) transform_u!(odet, intr) # no-op when ifix=0 (no Gaussian reduction) - return odet, propagators, chunks, S_at_surface_left + return odet, (; propagators, chunks, bases, axis_state) end -# Build odet and initialize at the magnetic axis. Same path as serial eulerlagrange_integration. +# OdeState at the axis start, with empty stores. function _initialize_parallel_odet(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) - odet = OdeState(intr.numpert_total, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr.msing) + odet = OdeState(intr.numpert_total, 1, 1, intr.msing) initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) - # No Gaussian reduction on the Riccati path. odet.new = false + odet.u_store_el_basis = false fill!(odet.unorm0, 1.0) return odet end -# Build the bidirectional chunk list, per-chunk propagators, and per-thread proxy OdeStates -# (sized by maxthreadid(), since threadid() can exceed nthreads() with an interactive pool). -function _setup_parallel_chunks_and_proxies(odet::OdeState, ctrl::ForceFreeStatesControl, - intr::ForceFreeStatesInternal) - # Crossing chunks get direction=-1: growing EL solutions decay backward, so Φ_bwd is well-conditioned. - base_chunks = chunk_el_integration_bounds(odet, ctrl, intr; bidirectional=true) - chunks = balance_integration_chunks(base_chunks, ctrl, intr) - N = intr.numpert_total - propagators = [ChunkPropagator(N) for _ in chunks] - odet_proxies = [OdeState(N, 1, 1, 0) for _ in 1:Threads.maxthreadid()] - return chunks, propagators, odet_proxies -end - -function _log_parallel_start(odet::OdeState, equil::Equilibrium.PlasmaEquilibrium, chunks::Vector{IntegrationChunk}) - @info " ψ = $((@sprintf "%.3f" odet.psifac)), q = $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac)))" - @info " Riccati FM: $(length(chunks)) chunks over $(Threads.nthreads()) thread$(Threads.nthreads() == 1 ? "" : "s")" -end - -# Integrate each chunk's propagator from identity IC in parallel; chunks are independent, so the -# result does not depend on the thread layout. :static makes threadid() a stable proxy index. -function _run_parallel_bvp_phase!(propagators::Vector{ChunkPropagator}, - chunks::Vector{IntegrationChunk}, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, - intr::ForceFreeStatesInternal, - odet_proxies::Vector{OdeState}) +# Every chunk's propagator, integrated across threads from inputs none of them can modify. +function chunk_propagators(chunks::Vector{IntegrationChunk}, bases::AbstractDict, rtol::Float64, + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices) + propagators = Vector{ChunkPropagator}(undef, length(chunks)) nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try - Threads.@threads :static for i in eachindex(chunks) - integrate_propagator_chunk!(propagators[i], chunks[i], ctrl, equil, mats, intr, - odet_proxies[Threads.threadid()]) + Threads.@threads for i in eachindex(chunks) + propagators[i] = chunk_propagator(chunks[i], propagator_start(chunks, i, bases, modes.numpert_total), rtol, equil, mats, modes) end finally BLAS.set_num_threads(nblas) end + return propagators end -# Apply chunk propagators serially, renormalizing to (S, I) after each (STRIDE's ode_fixup role: -# keeps conditioning at O(cond_per_chunk) instead of its K-th power). Backward chunks are applied -# via apply_propagator_inverse!. S_at_surface_left is the Riccati S at each surface's left boundary, -# the Δ' BVP axis BC. Returns (S_at_surface_left, last_crossing_step). +# Solver steps of a chunk whose states are stored, in increasing ψ: every `save_interval`-th, all from +# `dW_edge_scan_start` on, and the upper end. `after_crossing` adds the first, the state right of the surface. +function stored_step_indices(prop::ChunkPropagator, chunk::IntegrationChunk, after_crossing::Bool, ctrl::ForceFreeStatesControl) + nstep = length(prop.psi) + order = chunk.direction == 1 ? ((after_crossing ? 1 : 2):nstep) : ((nstep-1):-1:1) + return [k for (i, k) in enumerate(order) if + i == length(order) || i % ctrl.algorithm.save_interval == 0 || prop.psi[k] >= ctrl.dW_edge_scan_start] +end + +# Multiply the chunk propagators from the axis outward, crossing each singular surface, and fill `odet`'s stores +# with the (S, I) state at every stored step. Returns the state entering the first crossing chunk (2N × N). function _assemble_propagators_serially!(odet::OdeState, propagators::Vector{ChunkPropagator}, - chunks::Vector{IntegrationChunk}, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, intr::ForceFreeStatesInternal) + chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, + equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) N = intr.numpert_total - S_at_surface_left = Matrix{ComplexF64}[] - last_crossing_step = 1 + stored = [stored_step_indices(propagators[i], chunks[i], i > 1 && chunks[i-1].needs_crossing, ctrl) for i in eachindex(chunks)] + slots = cumsum([0; length.(stored)]) # store slot before each chunk's first + odet.psi_store = Vector{Float64}(undef, slots[end]) + odet.q_store = Vector{Float64}(undef, slots[end]) + odet.u_store = Array{ComplexF64}(undef, N, N, 2, slots[end]) + + chunk_starts = Vector{Matrix{ComplexF64}}(undef, length(chunks)) + axis_state = Matrix{ComplexF64}(undef, 0, 0) for (i, chunk) in enumerate(chunks) - if chunk.direction == -1 + if chunk.needs_crossing + isempty(axis_state) && (axis_state = [odet.u[:, :, 1]; odet.u[:, :, 2]]) apply_propagator_inverse!(odet, propagators[i]) + chunk_starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] + cross_singular_surface!(odet, intr, chunk.ising) + odet.psifac = chunks[i+1].psi_start else + chunk_starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] apply_propagator!(odet, propagators[i]) + renormalize_riccati_inplace!(odet.u, N) + odet.psifac = chunk.psi_end end - renormalize_riccati_inplace!(odet.u, N) - odet.psifac = chunk.psi_end - odet.q = equil.profiles.q_spline(odet.psifac) - if intr.verbose - @info " ψ = $((@sprintf "%.3f" odet.psifac)), q= $((@sprintf "%.3f" odet.q)), max(S) = $((@sprintf "%.2e" maximum(abs, odet.u[:,:,1]))), steps = $(odet.step-1)" + @info " ψ = $((@sprintf "%.3f" odet.psifac)), q= $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac))), steps = $(slots[i+1])" end + end + odet.q = equil.profiles.q_spline(odet.psifac) - if chunk.needs_crossing - ctrl.kinetic !== nothing && error("Riccati() does not support kinetic runs; use Forward().") - # State is (S, I) from the renorm above — well-conditioned at the surface's left boundary. - push!(S_at_surface_left, copy(odet.u[:, :, 1])) - riccati_cross_ideal_singular_surf!(odet, ctrl, equil, mats, intr, chunk.ising) - last_crossing_step = odet.step - 1 - else - # Store the chunk-endpoint state; these are Riccati states, not the EL basis. - odet.u_store_el_basis = false - if odet.step >= size(odet.u_store, 4) - resize_storage!(odet) + nblas = BLAS.get_num_threads() + BLAS.set_num_threads(1) + try + Threads.@threads for i in eachindex(chunks) + prop = propagators[i] + u = zeros(ComplexF64, N, N, 2) + for (j, k) in enumerate(stored[i]) + @views for half in 1:2 + mul!(u[:, :, half], prop.steps[k][:, :, half], chunk_starts[i]) + end + renormalize_riccati_inplace!(u, N) + slot = slots[i] + j + odet.psi_store[slot] = prop.psi[k] + odet.q_store[slot] = equil.profiles.q_spline(prop.psi[k]) + @views odet.u_store[:, :, :, slot] .= u end - odet.psi_store[odet.step] = odet.psifac - odet.q_store[odet.step] = odet.q - @views odet.u_store[:, :, :, odet.step] .= odet.u - odet.step += 1 + empty!(prop.psi) + empty!(prop.steps) end + finally + BLAS.set_num_threads(nblas) end - return S_at_surface_left, last_crossing_step + odet.step = slots[end] + return axis_state end -# Re-integrate last rational surface → psilim with Riccati: FM propagation loses precision there at -# high N, and findmax_dW_edge! needs dense checkpoints. Starts from the pre-renorm crossing state. -function _reintegrate_outer_plasma!(odet::OdeState, last_crossing_step::Int, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, - intr::ForceFreeStatesInternal) - N = intr.numpert_total - odet.u .= odet.u_store[:, :, :, last_crossing_step] - odet.psifac = odet.psi_store[last_crossing_step] - odet.q = odet.q_store[last_crossing_step] - odet.step = last_crossing_step + 1 - renormalize_riccati_inplace!(odet.u, N) - outer_chunk = IntegrationChunk(; psi_start=odet.psifac, psi_end=intr.psilim * (1 - eps), - needs_crossing=false, ising=0) - riccati_integrate_chunk!(odet, ctrl, equil, mats, intr, outer_chunk) - # Post: odet.u is in (S, I) form; odet.step points to next empty slot. -end - -# Edge-dW scan; on truncation, also cut the Δ' chunks and propagators back to the new edge. +# Edge-dW scan; on truncation, also cut `chunks` and `propagators` back to the new edge. function _handle_edge_dW_scan!(odet::OdeState, chunks::Vector{IntegrationChunk}, - propagators::Vector{ChunkPropagator}, + propagators::Vector{ChunkPropagator}, bases::AbstractDict, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) - N = intr.numpert_total - odet.step -= 1 - trim_storage!(odet) - scan_edge_dW!(odet, ctrl, equil, mats, intr) || return chunks, propagators + scan_edge_dW!(odet, ctrl, equil, mats, intr) || return - renormalize_riccati_inplace!(odet.u, N) # stored snapshot may be pre-renorm rebuild = truncate_chunks!(chunks, intr.psilim, intr.msing) resize!(propagators, length(chunks)) if rebuild !== nothing - integrate_propagator_chunk!(propagators[rebuild], chunks[rebuild], ctrl, equil, mats, intr, OdeState(N, 1, 1, 0)) + prop = chunk_propagator(chunks[rebuild], propagator_start(chunks, rebuild, bases, intr.numpert_total), + ctrl.algorithm.eulerlagrange_tolerance, equil, mats, ModeIndices(intr)) + propagators[rebuild] = ChunkPropagator(prop.u, Float64[], Array{ComplexF64,3}[]) end - return chunks, propagators + return end """ truncate_chunks!(chunks, psi_edge, msing) -> Union{Int,Nothing} -Cut `chunks` back to an edge at `psi_edge`: drop those past it, end the straddling one at it, and -clear any crossing onto a surface no longer in the plasma. Returns the index of a chunk that was -shortened and so must be re-integrated. +Cut `chunks` back to an edge at `psi_edge`: drop those past it, end the straddling one at it, and turn a +crossing chunk whose surface is no longer in the plasma into a forward chunk. Returns the index of a chunk +that changed and so must be re-integrated. """ function truncate_chunks!(chunks::Vector{IntegrationChunk}, psi_edge::Real, msing::Int) last = findlast(c -> c.psi_start < psi_edge, chunks) last === nothing && error("truncate_chunks!: edge ψ=$psi_edge lies before all chunk starts") resize!(chunks, last) c = chunks[last] - shortened = c.psi_end > psi_edge - # ising <= msing means the surface survived: edge truncation drops surfaces from the outside only. + # Truncation drops surfaces from the outside, so ising <= msing means the surface survived. crosses = c.needs_crossing && c.ising <= msing - if shortened || crosses != c.needs_crossing - chunks[last] = IntegrationChunk(; psi_start=c.psi_start, psi_end=min(c.psi_end, psi_edge), - needs_crossing=crosses, ising=crosses ? c.ising : 0, direction=c.direction) - end - return shortened ? last : nothing + (c.psi_end > psi_edge || crosses != c.needs_crossing) || return nothing + chunks[last] = IntegrationChunk(; psi_start=c.psi_start, psi_end=min(c.psi_end, psi_edge), + needs_crossing=crosses, ising=crosses ? c.ising : 0, direction=crosses ? c.direction : 1) + return last end diff --git a/src/ForceFreeStates/Riccati/Propagators.jl b/src/ForceFreeStates/Riccati/Propagators.jl index 81bd3d831c..0d2f61ccd1 100644 --- a/src/ForceFreeStates/Riccati/Propagators.jl +++ b/src/ForceFreeStates/Riccati/Propagators.jl @@ -1,249 +1,9 @@ -# Chunk-propagator integration: EL-ODE fundamental matrices, Riccati renormalization, assembly. - -# `riccati_integrator_callback!` saves every step within this fraction of the span (or absolute ψ -# floor, for short chunks) of a segment's right end; elsewhere every `save_interval`-th step. -const SAVE_NEAR_END_FRAC = 0.05 -const SAVE_NEAR_END_PSI = 1e-4 - -""" - assemble_fm_matrix(propagators, idx_range; condition=false, T_init=nothing) -> Matrix{ComplexF64} - -Assemble the 2N×2N fundamental matrix Φ_end * ... * Φ_start * T_init over chunks `idx_range`, -mapping the IC at the start of `idx_range[1]` to the state at the end of `idx_range[end]` -(`T_init` defaults to the identity). - -Each `ChunkPropagator` stores the 2N columns of Φ split into two N×N×2 blocks: - -``` - block_upper_ic[:,:,1:2] ↔ Φ[:,1:N] (result from IC=(I,0)) - block_lower_ic[:,:,1:2] ↔ Φ[:,N+1:2N] (result from IC=(0,I)) -``` - -`condition=true` applies `condition_propagator!` after each product (STRIDE's `ode_fixup`), so only -the N U₂ columns survive. Use it only for the axis→first-surface segment, where the axis BC (U₁ = 0) -needs only U₂ ICs; never for inter-surface segments, where both halves carry information. -""" -function assemble_fm_matrix(propagators::Vector{ChunkPropagator}, idx_range; - condition::Bool=false, - T_init::Union{Nothing,Matrix{ComplexF64}}=nothing) - # Take N from T_init when given, so an empty idx_range (or propagator list) still works. - N = if T_init !== nothing - size(T_init, 1) ÷ 2 - elseif !isempty(idx_range) - size(propagators[first(idx_range)].block_upper_ic, 1) - else - @assert !isempty(propagators) "assemble_fm_matrix: cannot infer N from empty propagators with no T_init" - size(propagators[1].block_upper_ic, 1) - end - Phi = T_init !== nothing ? copy(T_init) : Matrix{ComplexF64}(I, 2N, 2N) - isempty(idx_range) && return Phi - for i in idx_range - p = propagators[i] - #! format: off - Phi_i = [p.block_upper_ic[:,:,1] p.block_lower_ic[:,:,1]; - p.block_upper_ic[:,:,2] p.block_lower_ic[:,:,2]] - #! format: on - Phi = Phi_i * Phi - if condition - condition_propagator!(Phi, N) - end - end - return Phi -end - -""" - condition_propagator!(Phi, N) - -Apply Gaussian reduction to the U₂-columns (columns N+1:2N) of a 2N×2N propagator -matrix in-place, following STRIDE's `ode_fixup` convention. Triangularizes the U₁ -(upper N rows) subblock by pivoted elimination, improving the condition number so -the propagator can be used in a BVP without losing numerical rank. - -After conditioning, only the U₂ columns carry meaningful information; the U₁ columns -(1:N) are zeroed. The BVP axis block uses `Phi[:, N+1:2N]` (the conditioned half). -""" -function condition_propagator!(Phi::Matrix{ComplexF64}, N::Int) - # Work on the right half: columns N+1:2N (U₂ initial conditions) - cols = view(Phi, :, N+1:2N) - - # Sort columns by norm of the U₁ (upper N) block — largest first - norms = [norm(view(cols, 1:N, k)) for k in 1:N] - order = sortperm(norms; rev=true) - - mask_col = trues(N) # which columns remain to process - mask_row = trues(N) # which pivot rows remain available - - for isol in 1:N - kcol = order[isol] - mask_col[kcol] = false - - # Find best pivot row (largest |element| among unmasked rows) - best_row = 0 - best_val = 0.0 - for r in 1:N - if mask_row[r] && abs(cols[r, kcol]) > best_val - best_val = abs(cols[r, kcol]) - best_row = r - end - end - if best_row == 0 || best_val == 0 - continue - end - mask_row[best_row] = false - - # Eliminate this pivot from all other unmasked columns - pivot = cols[best_row, kcol] - for jcol in 1:N - if mask_col[jcol] - factor = -cols[best_row, jcol] / pivot - @views cols[:, jcol] .+= factor .* cols[:, kcol] - cols[best_row, jcol] = 0 # exact zero - end - end - end - - # Zero the U₁ columns (left half) — they are no longer meaningful - Phi[:, 1:N] .= 0 - return Phi -end - -""" - riccati_der!(du, u, params, psieval) - -Evaluate the explicit dual Riccati ODE right-hand side: -dS/dψ = w†·F̄⁻¹·w - S·Ḡ·S, w = Q - K̄·S - -where Q = diag(1/(m - n·q)) is the diagonal singular factor matrix. -The identity slice u[:,:,2] = I does not evolve (du[:,:,2] = 0). - -Reference implementation, not called in production: the quadratic S·Ḡ·S term makes the explicit -Riccati ODE unstable for explicit solvers, so the driver integrates `sing_der!` with -`renormalize_riccati_inplace!` instead. Exercised only by unit tests. - -See: Glasser (2018) Phys. Plasmas 25, 032507 — Eq. 19 (dual Riccati form) -""" -@with_pool pool function riccati_der!( - du::Array{ComplexF64,3}, - u::Array{ComplexF64,3}, - params::Tuple{ForceFreeStatesControl,Equilibrium.PlasmaEquilibrium, - MatrixSplines,ForceFreeStatesInternal,OdeState,IntegrationChunk}, - psieval::Float64 -) - - _, equil, mats, intr, odet, _ = params - - Npert = intr.numpert_total - S = @view u[:, :, 1] - dS = @view du[:, :, 1] - @view(du[:, :, 2]) .= 0 # identity does not evolve - - # Compute singfac = 1/(m - n·q) as column vector Q = diag(singfac_vec) - # [Glasser 2016 eq. 24] - singfac_vec = acquire!(pool, Float64, Npert) - singfac_mat = reshape(singfac_vec, intr.mpert, intr.npert) - odet.q = equil.profiles.q_spline(psieval; hint=odet.spline_hint) - singfac_mat .= 1.0 ./ ((intr.mlow:intr.mhigh) .- odet.q .* (intr.nlow:intr.nhigh)') - - fmat_lower = acquire!(pool, ComplexF64, Npert, Npert) - kmat = similar!(pool, fmat_lower) - gmat = similar!(pool, fmat_lower) - w = similar!(pool, fmat_lower) # w = Q - K̄·S - v = similar!(pool, fmat_lower) # v = F̄⁻¹·w (then reused for S·Ḡ·S) - tmp = similar!(pool, fmat_lower) # scratch - - # Evaluate F̄ (Cholesky factor), K̄, Ḡ splines at current ψ - mats.ideal.F_spline_lower(vec(fmat_lower), psieval; hint=mats._hint) - mats.ideal.K_spline(vec(kmat), psieval; hint=mats._hint) - mats.ideal.G_spline(vec(gmat), psieval; hint=mats._hint) - - # w = Q - K̄·S; Q is diagonal, so singfac_vec is added on the diagonal only. - mul!(w, kmat, S) # w = K̄·S - @. w = -w # w = -K̄·S - for i in 1:Npert - @inbounds w[i, i] += singfac_vec[i] # add diagonal Q: w = Q - K̄·S - end - - # v = F̄⁻¹·w (in-place Cholesky solve with stored lower-triangular factor) - v .= w - ldiv!(LowerTriangular(fmat_lower), v) - ldiv!(UpperTriangular(fmat_lower'), v) - - # dS = w†·v - S·Ḡ·S [Glasser 2018 eq. 19, dual Riccati] - mul!(dS, adjoint(w), v) # dS = w†·v - - # Subtract S·Ḡ·S (reuse v and tmp to avoid extra allocation) - mul!(tmp, gmat, S) # tmp = Ḡ·S - mul!(v, S, tmp) # v = S·Ḡ·S - dS .-= v -end - -""" - riccati_integrator_callback!(integrator) - -Per-step callback for `riccati_integrate_chunk!`: counts the step, applies -`renormalize_riccati_inplace!` when max(|U₁|) or max(|U₂|) exceeds `ctrl.algorithm.renorm_threshold` -(the Riccati analogue of Gaussian reduction), refreshes the per-column abstol, and stores selected steps. -""" -function riccati_integrator_callback!(integrator) - - ctrl, _, _, intr, odet, chunk = integrator.p - - odet.total_steps += 1 # count every accepted solver step (saved or not), as segment_callback! does - - # Renormalize to (S, I) when either block exceeds renorm_threshold. - if maximum(abs, @view(integrator.u[:, :, 1])) > ctrl.algorithm.renorm_threshold || - maximum(abs, @view(integrator.u[:, :, 2])) > ctrl.algorithm.renorm_threshold - renormalize_riccati_inplace!(integrator.u, intr.numpert_total) - end - - # Refresh after any renorm so the tolerance matches the current state. - column_abstol!(integrator.opts.abstol, integrator.u, ctrl.algorithm.eulerlagrange_tolerance) - - # Save the first two steps, every step near the right end, and every save_interval-th step otherwise. - psi_range = abs(integrator.sol.prob.tspan[2] - integrator.sol.prob.tspan[1]) - psi_remaining = abs(integrator.sol.prob.tspan[2] - integrator.t) - near_end = psi_remaining < SAVE_NEAR_END_FRAC * psi_range || psi_remaining < SAVE_NEAR_END_PSI - steps_in_segment = length(integrator.sol.t) - near_start = steps_in_segment <= 2 - should_save = near_start || near_end || (odet.step % ctrl.algorithm.save_interval == 0) - - if should_save - store_ode_data!(odet, integrator.t, integrator.u) - end -end - -""" - riccati_integrate_chunk!(odet, ctrl, equil, mats, intr, chunk) - -Integrate the Riccati state from `chunk.psi_start` to `chunk.psi_end` with `sing_der!` and -`riccati_integrator_callback!`, starting from u = (S, I). The end state is renormalized to (S, I) -unless `chunk.needs_crossing`, in which case the bounded (U₁, U₂) is left for the crossing. -""" -function riccati_integrate_chunk!( - odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, intr::ForceFreeStatesInternal, chunk::IntegrationChunk -) - cb = DiscreteCallback((u, t, integrator) -> true, riccati_integrator_callback!) - rtol = ctrl.algorithm.eulerlagrange_tolerance - prob = ODEProblem(sing_der!, odet.u, (chunk.psi_start, chunk.psi_end), - (ctrl, equil, mats, intr, odet, chunk)) - sol = solve_el(prob, rtol; callback=cb) - odet.u .= sol.u[end] - odet.psifac = sol.t[end] - # Before a crossing, skip the renorm so ca_l and ca_r share the pre-renorm normalization (needed for Δ'). - if !chunk.needs_crossing - renormalize_riccati_inplace!(odet.u, intr.numpert_total) - end -end +# Chunk propagators: their integration and application, and the reduction of a state to (S, I). """ renormalize_riccati_inplace!(u, N) -In-place Riccati renormalization on an arbitrary N×N×2 array: -u[:,:,1] = U₁ · U₂⁻¹ (new S) -u[:,:,2] = I - -The Riccati analogue of Gaussian reduction: keeps the inputs to `sing_der!` bounded. +Reduce the N × N × 2 state `u` = (U₁, U₂) in place to (S, I), S = U₁U₂⁻¹. """ function renormalize_riccati_inplace!(u::Array{ComplexF64,3}, N::Int) U2_copy = copy(@view u[:, :, 2]) @@ -255,176 +15,61 @@ function renormalize_riccati_inplace!(u::Array{ComplexF64,3}, N::Int) end """ - renormalize_riccati!(odet, intr) - -[`renormalize_riccati_inplace!`](@ref) on `odet.u`. After a singular surface crossing, which leaves -u[:,:,2] = U₂_new ≠ I, it restores the canonical storage u[:,:,1] = S_new = U₁_new·U₂_new⁻¹, u[:,:,2] = I -before the integration continues. The crossing's u_store entry keeps U₁_new and U₂_new, so -`compute_smallest_eigenvalue` is unaffected. -""" -renormalize_riccati!(odet::OdeState, intr::ForceFreeStatesInternal) = renormalize_riccati_inplace!(odet.u, intr.numpert_total) - -""" - integrate_propagator_chunk!(prop, chunk, ctrl, equil, mats, intr, odet_proxy) + propagator_start(chunks, i, bases, N) -> Array{ComplexF64,3} -Fill `prop` with the chunk's fundamental matrix by integrating the EL ODE from IC (I, 0) into -`prop.block_upper_ic` and from (0, I) into `prop.block_lower_ic`, without renormalization or storage. -`odet_proxy` holds the `sing_der!` side effects; concurrent calls need distinct proxies. +Start basis (N × 2N × 2) of chunk `i`'s propagator: the left basis of its surface for a crossing chunk, the +right basis for the chunk after one [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 33], else the identity. """ -function integrate_propagator_chunk!( - prop::ChunkPropagator, - chunk::IntegrationChunk, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, - intr::ForceFreeStatesInternal, - odet_proxy::OdeState -) - N = intr.numpert_total - # Backward chunks integrate psi_end → psi_start, where forward-growing solutions decay. - tspan = chunk.direction == 1 ? - (chunk.psi_start, chunk.psi_end) : - (chunk.psi_end, chunk.psi_start) - rtol = ctrl.algorithm.eulerlagrange_tolerance - params = (ctrl, equil, mats, intr, odet_proxy, chunk) - - # Upper block IC: U₁ = I, U₂ = 0 - u_upper = zeros(ComplexF64, N, N, 2) - for i in 1:N - u_upper[i, i, 1] = 1 - end - odet_proxy.spline_hint[] = 1 - odet_proxy.mats_hint[] = 1 - prob = ODEProblem(sing_der!, u_upper, tspan, params) - sol = solve_el(prob, rtol) - prop.block_upper_ic .= sol.u[end] - odet_proxy.total_steps += sol.stats.naccept # thread-local; summed into odet after the BVP barrier - - # Lower block IC: U₁ = 0, U₂ = I - u_lower = zeros(ComplexF64, N, N, 2) - for i in 1:N - u_lower[i, i, 2] = 1 +function propagator_start(chunks::Vector{IntegrationChunk}, i::Int, bases::AbstractDict, N::Int) + chunks[i].needs_crossing && return bases[chunks[i].ising].left + i > 1 && chunks[i-1].needs_crossing && return bases[chunks[i-1].ising].right + u0 = zeros(ComplexF64, N, 2N, 2) + for j in 1:N + u0[j, j, 1] = 1 + u0[j, N+j, 2] = 1 end - odet_proxy.spline_hint[] = 1 - odet_proxy.mats_hint[] = 1 - prob = ODEProblem(sing_der!, u_lower, tspan, params) - sol = solve_el(prob, rtol) - prop.block_lower_ic .= sol.u[end] - odet_proxy.total_steps += sol.stats.naccept + return u0 end """ - integrate_fm_with_ua_ic(chunks, chunk_range, ua, ctrl, equil, mats, intr; - backward=false, psi_ua=NaN) -> Matrix{ComplexF64} + chunk_propagator(chunk, u0, rtol, equil, mats, modes) -> ChunkPropagator -Re-integrate a span of chunks from the asymptotic solutions `ua` as initial conditions (Fortran -STRIDE `uFM_sing_init`). Column j of the 2N×2N result is the solution at the far end with IC -column j of T = [ua[:,:,1]; ua[:,:,2]]. With `backward=true` the IC sits at the span's right end -and the integration runs toward its start. `psi_ua`, when given, replaces the chunk boundary as the -IC location. Integrating from `ua` keeps the small solutions that multiplying an identity-IC -propagator by T loses to roundoff. +Integrate the ideal EL ODE over `chunk` from the start basis `u0` at relative tolerance `rtol`, keeping every +solver step. """ -function integrate_fm_with_ua_ic( - chunks::Vector{IntegrationChunk}, - chunk_range::UnitRange{Int}, - ua::Array{ComplexF64,3}, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, - intr::ForceFreeStatesInternal; - backward::Bool=false, - psi_ua::Float64=NaN -) - N = intr.numpert_total - psi_start = chunks[first(chunk_range)].psi_start - psi_end = chunks[last(chunk_range)].psi_end - # ua lives at the inner-layer boundary psi_ua, which may differ slightly from the chunk boundary. - if backward && !isnan(psi_ua) - psi_end = psi_ua - elseif !backward && !isnan(psi_ua) - psi_start = psi_ua +function chunk_propagator(chunk::IntegrationChunk, u0::Array{ComplexF64,3}, rtol::Float64, + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices) + tspan = chunk.direction == 1 ? (chunk.psi_start, chunk.psi_end) : (chunk.psi_end, chunk.psi_start) + spline_hint, mats_hint = Ref(1), Ref(1) + function derivative!(du, u, _, psi) + el_derivatives!(du, u, false, equil, mats, modes, psi, spline_hint, mats_hint) + return nothing end - tspan = backward ? (psi_end, psi_start) : (psi_start, psi_end) - rtol = ctrl.algorithm.eulerlagrange_tolerance - - result = zeros(ComplexF64, 2N, 2N) - odet_proxy = OdeState(N, 1, 1, 0) - dummy_chunk = IntegrationChunk(psi_start, psi_end, false, 0, backward ? -1 : 1) - params = (ctrl, equil, mats, intr, odet_proxy, dummy_chunk) - - # Batch 1: columns 1:N of T (big solutions) - u0 = zeros(ComplexF64, N, N, 2) - u0[:, :, 1] .= ua[:, 1:N, 1] - u0[:, :, 2] .= ua[:, 1:N, 2] - odet_proxy.spline_hint[] = 1 - odet_proxy.mats_hint[] = 1 - prob = ODEProblem(sing_der!, u0, tspan, params) - sol = solve_el(prob, rtol) - result[1:N, 1:N] .= sol.u[end][:, :, 1] - result[N+1:2N, 1:N] .= sol.u[end][:, :, 2] - - # Batch 2: columns N+1:2N of T (small solutions) - u0[:, :, 1] .= ua[:, N+1:2N, 1] - u0[:, :, 2] .= ua[:, N+1:2N, 2] - odet_proxy.spline_hint[] = 1 - odet_proxy.mats_hint[] = 1 - prob = ODEProblem(sing_der!, u0, tspan, params) - sol = solve_el(prob, rtol) - result[1:N, N+1:2N] .= sol.u[end][:, :, 1] - result[N+1:2N, N+1:2N] .= sol.u[end][:, :, 2] - - return result + sol = solve_el(ODEProblem(derivative!, copy(u0), tspan), rtol; save_everystep=true) + return ChunkPropagator(sol.u[end], sol.t, sol.u) end """ apply_propagator!(odet, prop) -Apply the chunk propagator `prop` to any state `odet.u` (including the Riccati (S, I) form) in-place. -Implements the subpropagator composition Φ(ψ₂, ψ₀) = Φ(ψ₂, ψ₁) · Φ(ψ₁, ψ₀) of -Glasser-Kolemen (2018) Phys. Plasmas 25, 032501 Eq. 29. +Multiply `odet.u` by the chunk propagator `prop` [Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507, Eq. 29]. """ function apply_propagator!(odet::OdeState, prop::ChunkPropagator) - U1_upper = @view prop.block_upper_ic[:, :, 1] - U2_upper = @view prop.block_upper_ic[:, :, 2] - U1_lower = @view prop.block_lower_ic[:, :, 1] - U2_lower = @view prop.block_lower_ic[:, :, 2] - - u1_prev = copy(@view odet.u[:, :, 1]) - u2_prev = copy(@view odet.u[:, :, 2]) - tmp = similar(u1_prev) - - # U₁_new = U1_upper · u1_prev + U1_lower · u2_prev - mul!(view(odet.u, :, :, 1), U1_upper, u1_prev) - mul!(tmp, U1_lower, u2_prev) - odet.u[:, :, 1] .+= tmp - - # U₂_new = U2_upper · u1_prev + U2_lower · u2_prev - mul!(view(odet.u, :, :, 2), U2_upper, u1_prev) - mul!(tmp, U2_lower, u2_prev) - odet.u[:, :, 2] .+= tmp + x = [odet.u[:, :, 1]; odet.u[:, :, 2]] + @views for k in 1:2 + mul!(odet.u[:, :, k], prop.u[:, :, k], x) + end end """ apply_propagator_inverse!(odet, prop) -Apply the *inverse* of the chunk propagator `prop` to the current state `odet.u` in-place. - -Used for backward chunks: the well-conditioned Φ_bwd maps `psi_end` → `psi_start`, so solving -Φ_bwd · x = u_old by LU advances the state `psi_start` → `psi_end` far more accurately than Φ_fwd. - -Implements the inverse subpropagator identity Φ(ψ₂, ψ₁) = Φ(ψ₁, ψ₂)⁻¹ of -Glasser-Kolemen (2018) Phys. Plasmas 25, 032501 Eq. 33. +Solve the chunk propagator `prop` against `odet.u`, which carries a state across a backward chunk +[Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507, Eq. 33]. """ function apply_propagator_inverse!(odet::OdeState, prop::ChunkPropagator) N = size(odet.u, 1) - # Assemble 2N×2N backward FM Φ_bwd - #! format: off - Φ = [prop.block_upper_ic[:,:,1] prop.block_lower_ic[:,:,1]; - prop.block_upper_ic[:,:,2] prop.block_lower_ic[:,:,2]] - #! format: on - # x = Φ_bwd⁻¹ · [U₁_old; U₂_old] advances psi_start → psi_end. - u_old = [odet.u[:, :, 1]; odet.u[:, :, 2]] # 2N × N - u_new = Φ \ u_old # LU solve, 2N × N - odet.u[:, :, 1] .= u_new[1:N, :] - odet.u[:, :, 2] .= u_new[N+1:2N, :] + x = [prop.u[:, :, 1]; prop.u[:, :, 2]] \ [odet.u[:, :, 1]; odet.u[:, :, 2]] + odet.u[:, :, 1] .= x[1:N, :] + odet.u[:, :, 2] .= x[(N+1):(2N), :] end diff --git a/src/ForceFreeStates/Riccati/Types.jl b/src/ForceFreeStates/Riccati/Types.jl index 04fd25355a..8ea1b70495 100644 --- a/src/ForceFreeStates/Riccati/Types.jl +++ b/src/ForceFreeStates/Riccati/Types.jl @@ -25,22 +25,17 @@ end """ ChunkPropagator -Fundamental matrix for one integration chunk, stored as two N×N×2 solution blocks. -Represents the propagator Φ(ψ₂,ψ₁) computed by integrating the EL ODE from two -identity-block initial conditions: +Fundamental matrix of one integration chunk: column `j` is the solution started from column `j` of the chunk's +start basis (`propagator_start`). - - `block_upper_ic`: result of integrating with IC = (I_N, 0_N) (U₁ = I, U₂ = 0) - - `block_lower_ic`: result of integrating with IC = (0_N, I_N) (U₁ = 0, U₂ = I) - -Applying the propagator to the current state `u_prev`: - -u₁_new = block_upper_ic[:,:,1] · u₁_prev + block_lower_ic[:,:,1] · u₂_prev -u₂_new = block_upper_ic[:,:,2] · u₁_prev + block_lower_ic[:,:,2] · u₂_prev +## Fields -Each chunk starts from an identity IC rather than the accumulated state, so chunks integrate in parallel. + - `u::Array{ComplexF64,3}` - The matrix at the end of the integration, `(N, 2N, 2)`: U₁ in slice 1, U₂ in slice 2. + - `psi::Vector{Float64}` - ψ of every solver step, in integration order. + - `steps::Vector{Array{ComplexF64,3}}` - The matrix at each `psi`. """ struct ChunkPropagator - block_upper_ic::Array{ComplexF64,3} # shape (N, N, 2) — result from IC = (I, 0) - block_lower_ic::Array{ComplexF64,3} # shape (N, N, 2) — result from IC = (0, I) + u::Array{ComplexF64,3} + psi::Vector{Float64} + steps::Vector{Array{ComplexF64,3}} end -ChunkPropagator(N::Int) = ChunkPropagator(zeros(ComplexF64, N, N, 2), zeros(ComplexF64, N, N, 2)) diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 7e440b1f59..5256fe4102 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -61,20 +61,20 @@ function run_force_free_states( odet = nothing free_energies = nothing gal_data = nothing - gal_dp = nothing + delta_prime = nothing if ctrl.algorithm isa Galerkin ctrl.kinetic === nothing || error("Galerkin() does not support kinetic runs; use Forward().") gal_start = time() wv = ctrl.vac_flag ? first(compute_scaled_wv(ctrl, equil, intr)) : nothing - gal_data, gal_dp = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) + gal_data, delta_prime = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) gal_dt = time() - gal_start @info "Galerkin solve completed in $(@sprintf("%.3f", gal_dt)) s" else if intr.verbose @info "Integrating Euler-Lagrange equation" end - odet, fm_propagators, fm_chunks, fm_S_left = eulerlagrange_integration(ctrl, equil, mats, intr) + odet, riccati = eulerlagrange_integration(ctrl, equil, mats, intr) if odet.nzero > 0 && intr.verbose @warn "Fixed-boundary mode unstable for n = $nstring" end @@ -85,7 +85,7 @@ function run_force_free_states( @info "Computing free boundary energies ($wall_desc)" end free_energies = free_run(odet, ctrl, equil, mats, intr) - normalize_eigenfunctions!(odet, free_energies.wt, equil.psio) + odet.u_store_el_basis && normalize_eigenfunctions!(odet, free_energies.wt, equil.psio) if real(free_energies.et[1]) < 0 if intr.verbose @warn "Free-boundary mode unstable for n = $nstring" @@ -97,20 +97,18 @@ function run_force_free_states( end # Inter-surface Δ' (STRIDE BVP): needs Riccati() propagators and wv from free_run. - if ctrl.kinetic === nothing && intr.msing > 0 && fm_propagators !== nothing + if ctrl.kinetic === nothing && intr.msing > 0 && riccati !== nothing if intr.verbose @info "Computing Δ' matrix (STRIDE BVP with vacuum coupling)" end - compute_delta_prime_matrix!(intr, fm_propagators, fm_chunks; - wv=free_energies.wv, psio=equil.psio, debug=intr.verbose, - S_at_surface_left=fm_S_left, - ctrl=ctrl, equil=equil, mats=mats) + delta_prime = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.bases, riccati.axis_state; + wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) end end end # Publish the solve: from here on the downstream stages read the result, never `intr`. - result = build_result(_integrator_symbol(ctrl.algorithm), ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, gal_dp) + result = build_result(_integrator_symbol(ctrl.algorithm), ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime) return result end diff --git a/src/ForceFreeStates/Surfaces/Types.jl b/src/ForceFreeStates/Surfaces/Types.jl index 0099590ab1..333a93ca6c 100644 --- a/src/ForceFreeStates/Surfaces/Types.jl +++ b/src/ForceFreeStates/Surfaces/Types.jl @@ -14,9 +14,7 @@ A mutable struct holding data related to the singular surfaces in the equilibriu - `q::Float64` - Safety factor (= m/n) - `q1::Float64` - Derivative of safety factor with respect to ψ - `delta_prime::Vector{ComplexF64}` - **Debug stub, not physically valid.** Per-surface ca-based Δ' estimate; - use `ForceFreeStatesInternal.delta_prime_matrix` (STRIDE global BVP, Glasser 2018 PoP 25, 032501) for tearing stability. - - `delta_prime_col::Matrix{ComplexF64}` - **Debug stub, not physically valid.** Per-surface ca-based Δ' columns, `(numpert_total, n_res_modes)`, - `delta_prime_col[j, i] = (ca_r[j,ipert_res_i,2] - ca_l[j,ipert_res_i,2]) / (4π²·psio)`; diagonal matches `delta_prime`. Riccati/parallel paths only. + use `ForceFreeStatesResult.delta_prime` (STRIDE global BVP, Glasser & Kolemen 2018, Phys. Plasmas 25, 082502) for tearing stability. """ @kwdef mutable struct SingType psifac::Float64 = 0.0 @@ -26,11 +24,6 @@ A mutable struct holding data related to the singular surfaces in the equilibriu q::Float64 = 0.0 q1::Float64 = 0.0 delta_prime::Vector{ComplexF64} = ComplexF64[] - delta_prime_col::Matrix{ComplexF64} = Matrix{ComplexF64}(undef, 0, 0) - ua_left::Array{ComplexF64,3} = Array{ComplexF64}(undef, 0, 0, 0) # asymptotic basis at left inner-layer boundary - ua_right::Array{ComplexF64,3} = Array{ComplexF64}(undef, 0, 0, 0) # asymptotic basis at right inner-layer boundary - psi_ua_left::Float64 = 0.0 # ψ where ua_left was evaluated (left inner-layer boundary) - psi_ua_right::Float64 = 0.0 # ψ where ua_right was evaluated (right inner-layer boundary) restype::Any = nothing # ResistGeometry from ResistEval.jl (populated by resist_eval_all!); typed `Any` to avoid a cross-file type reference end diff --git a/src/ForceFreeStates/Utils.jl b/src/ForceFreeStates/Utils.jl index b7948380af..57a54d5e77 100644 --- a/src/ForceFreeStates/Utils.jl +++ b/src/ForceFreeStates/Utils.jl @@ -84,8 +84,8 @@ Euler-Lagrange system is linear in `u`, and both operations right-multiply the s mixing matrix `T`, so `du(ψ, u·T) = du(ψ, u)·T`. Returns `false` without allocating when there is nothing to work from — no `mats`, no stored -steps, or a solution held in a basis the Euler-Lagrange kernel does not apply to (the sparse -parallel path, which stores chunk-endpoint Riccati matrices). +steps, or a solution held in a basis the Euler-Lagrange kernel does not apply to (the +Riccati path, which stores Riccati matrices). """ function materialize_derivative_stores!( odet::OdeState, diff --git a/src/Precompile.jl b/src/Precompile.jl index 79091d88d5..6e00648c2e 100644 --- a/src/Precompile.jl +++ b/src/Precompile.jl @@ -22,7 +22,7 @@ import Logging for formalism in ("Riccati", "Forward") inputs["ForceFreeStates"]["integrator"] = formalism foreach(name -> delete!(inputs, name), ("Riccati", "Forward")) - inputs[formalism] = Dict{String,Any}("renorm_threshold" => 1e3, "eulerlagrange_tolerance" => 1e-7) + inputs[formalism] = Dict{String,Any}("eulerlagrange_tolerance" => 1e-7) mktempdir() do workdir open(io -> TOML.print(io, inputs), joinpath(workdir, "gpec.toml"), "w") Logging.with_logger(Logging.NullLogger()) do diff --git a/src/Tearing/Dispersion/CoupledFullMatch.jl b/src/Tearing/Dispersion/CoupledFullMatch.jl index 19e7e52ba0..578f1bcd93 100644 --- a/src/Tearing/Dispersion/CoupledFullMatch.jl +++ b/src/Tearing/Dispersion/CoupledFullMatch.jl @@ -11,7 +11,7 @@ # Eq. (36)-(40); original matching construction Pletzer & Dewar 1991, # J. Plasma Phys. **45**, 427). # -# The outer D' (`intr.delta_prime_raw`) is in the side-major L/R basis while the inner layer returns +# The outer D' (`DeltaPrimeData.raw`) is in the side-major L/R basis while the inner layer returns # Δ in the parity ± basis, so both amplitude sets are kept as unknowns and joined by the matching # identity rows, giving a 4m × 4m system instead of a basis-mixing 2m × 2m determinant. # @@ -64,9 +64,8 @@ end inner_kwargs=NamedTuple()) -> MultiSurfaceCouplingFull Construct the 4m × 4m dispersion matrix driver. `dp_raw` must be the -2m × 2m matrix in side-major ordering (the `intr.delta_prime_raw` -field populated by `ForceFreeStates.compute_delta_prime_matrix!` on the -Riccati path). Surface k's inner layer is evaluated at `Q·ratio_k` Doppler-shifted by its +2m × 2m matrix in side-major ordering (the `DeltaPrimeData.raw` +field of a Riccati solve). Surface k's inner layer is evaluated at `Q·ratio_k` Doppler-shifted by its E×B offset `q_shift_k`, exactly as in the reduced `multi_surface_coupling`: added to Q for a SLAYER surface, and as `i·q_shift_k` to the growth rate s for a GGJ surface (see `SurfaceCoupling`). diff --git a/test/runtests_analysis_plots.jl b/test/runtests_analysis_plots.jl index 6951228387..3ad1a020f4 100644 --- a/test/runtests_analysis_plots.jl +++ b/test/runtests_analysis_plots.jl @@ -143,7 +143,7 @@ using TOML @testset "Riccati run offers Δ′ but no solution profiles" begin mktempdir() do dir ret, h5 = _run_fixture(dir, "regression_solovev_ideal_example"; - edit=d -> (d["ForceFreeStates"]["integrator"] = "Riccati"; d["Riccati"] = pop!(d, "Forward"))) + edit=d -> (d["ForceFreeStates"]["integrator"] = "Riccati"; d["Riccati"] = delete!(pop!(d, "Forward"), "renorm_threshold"))) _check_sources(ret.ffs, h5) @test :delta_prime in A.capabilities(ret.ffs) && :solution_profiles ∉ A.capabilities(ret.ffs) @test_throws A.REASONS[:solution_profiles] A.ForceFreeStates.plot_mode_displacement(ret.ffs) diff --git a/test/runtests_eulerlagrange.jl b/test/runtests_eulerlagrange.jl index 2fe69f4417..4cbc5cf0cd 100644 --- a/test/runtests_eulerlagrange.jl +++ b/test/runtests_eulerlagrange.jl @@ -135,18 +135,25 @@ end @testset "truncate_chunks! cuts the Riccati chunks back to the edge" begin F = GeneralizedPerturbedEquilibrium.ForceFreeStates - # Crossing chunks end just short of surfaces 1-3; the edge drops surface 3 (msing = 2). + # Backward crossing chunks end just short of surfaces 1-3; the edge drops surface 3 (msing = 2). chunks() = [ - F.IntegrationChunk(; psi_start=a, psi_end=b, needs_crossing=i <= 3, ising=i <= 3 ? i : 0) + F.IntegrationChunk(; psi_start=a, psi_end=b, needs_crossing=i <= 3, ising=i <= 3 ? i : 0, direction=i <= 3 ? -1 : 1) for (i, (a, b)) in enumerate(((0.10, 0.29), (0.31, 0.59), (0.61, 0.89), (0.91, 0.99))) ] cs = chunks() @test F.truncate_chunks!(cs, 0.75, 2) == 3 # straddling chunk shortened, so re-integrate it @test length(cs) == 3 && cs[3].psi_end == 0.75 && count(c -> c.needs_crossing, cs) == 2 + @test cs[3].direction == 1 # no surface left to cross: a forward chunk + # Edge exactly at a crossing chunk's end: its surface is dropped, so it turns forward and is re-integrated. cs = chunks() - @test F.truncate_chunks!(cs, 0.89, 2) === nothing # edge exactly at a chunk end: nothing to re-integrate - @test count(c -> c.needs_crossing, cs) == 2 # but its crossing onto the dropped surface is still cleared + @test F.truncate_chunks!(cs, 0.89, 2) == 3 + @test cs[3].psi_end == 0.89 && !cs[3].needs_crossing && cs[3].direction == 1 + + # Edge at the end of the last chunk with every surface kept: nothing changes. + cs = chunks() + @test F.truncate_chunks!(cs, 0.99, 3) === nothing + @test cs[3].needs_crossing && cs[3].direction == -1 && cs[4].psi_end == 0.99 end @testset "transform_u!" begin @@ -321,9 +328,8 @@ end @test FFS.column_abstol!(tol, u, 1e-6) === tol @test all(FFS.column_abstol(zeros(ComplexF64, 2, 2, 2), 1e-6) .> 0) # Pin the defaults: every shipped deck sets both, so the harness would not catch a revert - c = FFS.ForceFreeStatesControl() - @test c.algorithm.renorm_threshold == 1e3 - @test c.algorithm.save_interval == 1 + @test Forward().renorm_threshold == 1e3 + @test Forward().save_interval == 1 && Riccati().save_interval == 1 end @testset "compute_solution_norms!" begin @@ -666,7 +672,7 @@ end intr.numpert_total = intr.mpert * intr.npert metric = FFS.make_metric(equil, intr.mpert) mats = FFS.build_matrix_splines(equil, intr, metric) - odet, _, _, _ = FFS.eulerlagrange_integration(ctrl, equil, mats, intr) + odet = first(FFS.eulerlagrange_integration(ctrl, equil, mats, intr)) return odet, ctrl, equil, mats, intr end diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 7ddba18d9f..2eb96ecc9e 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -9,6 +9,7 @@ function _prepared_solovev(integrator::String="Forward"; nchunks=nothing) if integrator != "Forward" inputs["ForceFreeStates"]["integrator"] = integrator integrator == "Galerkin" ? delete!(inputs, "Forward") : (inputs[integrator] = pop!(inputs, "Forward")) + integrator == "Riccati" && delete!(inputs["Riccati"], "renorm_threshold") end nchunks === nothing || (inputs[integrator]["nchunks"] = nchunks) equil = GPEC.Equilibrium.PlasmaEquilibrium(GPEC.equilibrium_config(inputs, ex), GPEC.analytic_config(inputs)) @@ -17,7 +18,7 @@ function _prepared_solovev(integrator::String="Forward"; nchunks=nothing) return ctrl, intr, equil, metric, mats end -@testset "BVP without controls preserves extended precision" begin +@testset "BVP solve precision" begin FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates M = ComplexF64[1 / (i + j - 1) + 0.02im / (i + j) for i in 1:6, j in 1:6] reference = setprecision(BigFloat, 256) do @@ -32,123 +33,71 @@ end delta = reshape([raw[2, 2] - raw[2, 1] - raw[1, 2] + raw[1, 1]], 1, 1) return ComplexF64.(delta), ComplexF64.(raw) end - default = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, nothing, false) - extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(), false) - ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, 6, false, [1], nothing, FFS.ForceFreeStatesControl(; algorithm=Riccati(; extended_precision_bvp=false)), false) - @test default == reference + extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], true) + ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], false) @test extended == reference @test ordinary != reference + @test all(isapprox.(ordinary, reference; rtol=1e-8)) + @test !Riccati().extended_precision_bvp end @testset "Riccati FM Integration Tests" begin - @testset "ChunkPropagator identity on trivial interval" begin - # Integrating over a zero-width interval should give the identity propagator. - # We test that apply_propagator! on an identity state preserves the state. + @testset "apply_propagator! and its inverse" begin + FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates N = 3 - prop = GeneralizedPerturbedEquilibrium.ForceFreeStates.ChunkPropagator(N) - - # Set propagator to identity (block_upper_ic = (I, 0), block_lower_ic = (0, I)) - for i in 1:N - prop.block_upper_ic[i, i, 1] = 1 # U1 block from IC=(I,0) - prop.block_lower_ic[i, i, 2] = 1 # U2 block from IC=(0,I) - end - - # Apply identity propagator to an arbitrary state - odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(N, 10, 5, 0) - u1_in = [1.0+0.5im 0.2im 0.0; - 0.1+0.1im 1.2+0.1im 0.0; - 0.0im 0.0 0.9+0.3im] - u2_in = [0.8+0.1im 0.1im 0.0; - 0.0im 1.0+0.2im 0.1; - 0.1im 0.0 1.1+0.0im] - odet.u[:, :, 1] .= u1_in - odet.u[:, :, 2] .= u2_in - - GeneralizedPerturbedEquilibrium.ForceFreeStates.apply_propagator!(odet, prop) - - @test odet.u[:, :, 1] ≈ u1_in rtol = 1e-12 - @test odet.u[:, :, 2] ≈ u2_in rtol = 1e-12 - end - - @testset "apply_propagator! linearity" begin - # Verify that apply_propagator! applies the correct linear map. - N = 3 - prop = GeneralizedPerturbedEquilibrium.ForceFreeStates.ChunkPropagator(N) - - # Fill block_upper_ic and block_lower_ic with random data - rng_upper = [1.1+0.2im 0.1im 0.05; - 0.0im 0.9+0.3im 0.1; - 0.2+0.1im 0.0 1.0+0.1im] - rng_lower = [0.8+0.1im 0.1im 0.0; - 0.0im 1.2+0.2im 0.1; - 0.0im 0.1 0.9+0.1im] - prop.block_upper_ic[:, :, 1] .= rng_upper - prop.block_upper_ic[:, :, 2] .= 0.5 * rng_upper - prop.block_lower_ic[:, :, 1] .= 0.3 * rng_lower - prop.block_lower_ic[:, :, 2] .= rng_lower - - odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(N, 10, 5, 0) - u1_in = 0.5 * I(N) .+ 0.1im * ones(N, N) - u2_in = I(N) .+ 0.2im * ones(N, N) - odet.u[:, :, 1] .= u1_in - odet.u[:, :, 2] .= u2_in - - GeneralizedPerturbedEquilibrium.ForceFreeStates.apply_propagator!(odet, prop) - - # Manual computation of expected result - U1_upper = prop.block_upper_ic[:, :, 1] - U2_upper = prop.block_upper_ic[:, :, 2] - U1_lower = prop.block_lower_ic[:, :, 1] - U2_lower = prop.block_lower_ic[:, :, 2] - u1_expected = U1_upper * u1_in + U1_lower * u2_in - u2_expected = U2_upper * u1_in + U2_lower * u2_in - - @test odet.u[:, :, 1] ≈ u1_expected rtol = 1e-12 - @test odet.u[:, :, 2] ≈ u2_expected rtol = 1e-12 - end - - @testset "apply_propagator_inverse! is inverse of apply_propagator!" begin - # Verify that apply_propagator_inverse! is the algebraic inverse of apply_propagator!: - # applying inverse then forward should recover the original state exactly. - # This checks the LU-solve path: Φ \ (Φ * u) = u for an arbitrary invertible Φ. - N = 3 - prop = GeneralizedPerturbedEquilibrium.ForceFreeStates.ChunkPropagator(N) - - # Near-identity blocks guarantee the 2N×2N matrix [A B; C D] is invertible A = I(N) .+ 0.15 * [1.0+0.2im 0.1im 0.05; 0.0im 0.9+0.3im 0.1; 0.2+0.1im 0.0 1.0+0.1im] B = 0.1 * [0.8+0.1im 0.1im 0.0; 0.0im 1.2+0.2im 0.1; 0.0im 0.1 0.9+0.1im] C = 0.1 * [0.5+0.1im 0.0im 0.1; 0.1im 0.8+0.2im 0.0; 0.0im 0.0 0.7+0.1im] D = I(N) .+ 0.15 * [0.9+0.1im 0.0im 0.05; 0.0im 1.0+0.2im 0.0; 0.1+0.1im 0.0 0.95+0.1im] + # Fundamental matrix [A B; C D] in the propagator layout: U₁ rows in slice 1, U₂ rows in slice 2. + prop = FFS.ChunkPropagator(cat([A B], [C D]; dims=3), Float64[], Array{ComplexF64,3}[]) - prop.block_upper_ic[:, :, 1] .= A - prop.block_lower_ic[:, :, 1] .= B - prop.block_upper_ic[:, :, 2] .= C - prop.block_lower_ic[:, :, 2] .= D - - u1_in = [1.0+0.5im 0.2im 0.0; - 0.1+0.1im 1.2+0.1im 0.0; - 0.0im 0.0 0.9+0.3im] + u1_in = [1.0+0.5im 0.2im 0.0; 0.1+0.1im 1.2+0.1im 0.0; 0.0im 0.0 0.9+0.3im] u2_in = I(N) .+ 0.1im * ones(N, N) - - odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(N, 10, 5, 0) + odet = FFS.OdeState(N, 10, 5, 0) odet.u[:, :, 1] .= u1_in odet.u[:, :, 2] .= u2_in - # Round-trip: inverse then forward = identity - GeneralizedPerturbedEquilibrium.ForceFreeStates.apply_propagator_inverse!(odet, prop) - GeneralizedPerturbedEquilibrium.ForceFreeStates.apply_propagator!(odet, prop) + FFS.apply_propagator!(odet, prop) + @test odet.u[:, :, 1] ≈ A * u1_in + B * u2_in rtol = 1e-12 + @test odet.u[:, :, 2] ≈ C * u1_in + D * u2_in rtol = 1e-12 + FFS.apply_propagator_inverse!(odet, prop) @test odet.u[:, :, 1] ≈ u1_in rtol = 1e-12 @test odet.u[:, :, 2] ≈ u2_in rtol = 1e-12 end + @testset "propagator steps reproduce a direct integration" begin + # The fundamental matrix at a solver step, applied to a start state, is the solution from that state. + FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates + ctrl, intr, equil, metric, mats = _prepared_solovev("Riccati") + N = intr.numpert_total + odet = FFS.OdeState(N, 1, 1, intr.msing) + FFS.initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) + chunks = FFS.balance_integration_chunks(FFS.chunk_el_integration_bounds(odet, ctrl, intr), ctrl, intr) + chunk = chunks[1] + start = FFS.propagator_start(chunks, 1, Dict{Int,Any}(), N) + prop = FFS.chunk_propagator(chunk, start, ctrl.algorithm.eulerlagrange_tolerance, equil, mats, FFS.ModeIndices(intr)) + @test length(prop.psi) == length(prop.steps) + @test prop.psi[1] == chunk.psi_start && prop.psi[end] == chunk.psi_end + @test prop.steps[1][:, :, 1] == [I(N) zeros(N, N)] && prop.steps[1][:, :, 2] == [zeros(N, N) I(N)] + @test prop.steps[end] == prop.u + + k = length(prop.psi) ÷ 2 + direct = FFS.solve_el(FFS.ODEProblem(FFS.sing_der!, copy(odet.u), (chunk.psi_start, prop.psi[k]), + (ctrl, equil, mats, intr, FFS.OdeState(N, 1, 1, 0), chunk)), ctrl.algorithm.eulerlagrange_tolerance).u[end] + x = [odet.u[:, :, 1]; odet.u[:, :, 2]] + @test prop.steps[k][:, :, 1] * x ≈ direct[:, :, 1] rtol = 1e-5 + @test prop.steps[k][:, :, 2] * x ≈ direct[:, :, 2] rtol = 1e-5 + end + @testset "balance_integration_chunks produces target count" begin - # Verify that balance_integration_chunks creates at least - # max(2*msing+3, 8*(msing+1)+msing) chunks from a small set of base chunks. + # Verify that balance_integration_chunks creates 8*(msing+1)+msing chunks from a small set of + # base chunks, and never fewer than the base chunks with every crossing chunk split once. ctrl, intr, equil, metric, mats = _prepared_solovev("Riccati") - odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(intr.numpert_total, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr.msing) + odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(intr.numpert_total, 1, 1, intr.msing) GeneralizedPerturbedEquilibrium.ForceFreeStates.initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) base_chunks = GeneralizedPerturbedEquilibrium.ForceFreeStates.chunk_el_integration_bounds(odet, ctrl, intr) @@ -158,7 +107,8 @@ end # (src/ForceFreeStates/EulerLagrange.jl). Keep this in sync. The formula reads only # intr.msing — no thread count enters it, which is what makes Riccati outputs # independent of how many threads `julia -t` provides. - target_n = max(2 * intr.msing + 3, 8 * (intr.msing + 1) + intr.msing) + min_chunks = length(base_chunks) + count(c -> c.needs_crossing, base_chunks) + target_n = max(min_chunks, 8 * (intr.msing + 1) + intr.msing) # After balancing, chunk count equals target_n: the while-loop adds exactly one # chunk per iteration (a bisection split) and exits when length(result) >= target_n, @@ -201,11 +151,12 @@ end balanced_more = GeneralizedPerturbedEquilibrium.ForceFreeStates.balance_integration_chunks(base_chunks, ctrl_more, intr) @test length(balanced_more) == target_n + 7 - # An nchunks below the singular-surface floor is clamped up, with a warning. - min_chunks = 2 * intr.msing + 3 + # An nchunks below the singular-surface floor is clamped up, with a warning. At the floor a + # forward chunk still separates every crossing chunk from the previous surface or the axis. ctrl_few = first(_prepared_solovev("Riccati"; nchunks=1)) balanced_few = @test_logs (:warn,) match_mode = :any GeneralizedPerturbedEquilibrium.ForceFreeStates.balance_integration_chunks(base_chunks, ctrl_few, intr) - @test length(balanced_few) == max(min_chunks, length(base_chunks)) + @test length(balanced_few) == min_chunks + @test all(i > 1 && !balanced_few[i-1].needs_crossing for i in eachindex(balanced_few) if balanced_few[i].needs_crossing) end @testset "chunk_el_integration_bounds direction field — bidirectional mode" begin @@ -214,7 +165,7 @@ end # the right sub-chunk inherits direction from the parent, the left sub-chunk is always +1. ctrl, intr, equil, metric, mats = _prepared_solovev("Riccati") - odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(intr.numpert_total, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr.msing) + odet = GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState(intr.numpert_total, 1, 1, intr.msing) GeneralizedPerturbedEquilibrium.ForceFreeStates.initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) # Default (bidirectional=false): all chunks should have direction=+1 @@ -253,7 +204,7 @@ end # on this small multi-surface fixture. function run_solovev(integrator) ctrl, intr, equil, metric, mats = _prepared_solovev(integrator) - odet, _, _, _ = GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr) + odet = first(GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr)) vac = GeneralizedPerturbedEquilibrium.ForceFreeStates.free_run(odet, ctrl, equil, mats, intr) return real(vac.et[1]), intr end @@ -298,14 +249,12 @@ end # physically meaningful. BVP Δ' regression is concentrated on the DIIID-like # fixture below (intrinsically stable, well-conditioned BVP Δ'). - @testset "Riccati leaves a sparse u_store in the Riccati basis" begin - # The Riccati path stores only chunk-endpoint snapshots, so u_store / psi_store have - # strictly fewer entries than the forward path's dense saved steps, and the stored - # state is not in the Euler-Lagrange axis basis. Downstream ξ consumers must therefore - # be fed by the forward integrator; this test pins that contract. + @testset "Riccati leaves its u_store in the Riccati basis" begin + # The stored Riccati states are (S, I), not the Euler-Lagrange axis basis. Downstream ξ consumers + # must therefore be fed by the forward integrator; this test pins that contract. function run_and_capture(integrator) ctrl, intr, equil, metric, mats = _prepared_solovev(integrator) - odet, _, _, _ = GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr) + odet = first(GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr)) # Derivatives are recomputed on demand; materialize so the stores can be compared. GeneralizedPerturbedEquilibrium.ForceFreeStates.materialize_derivative_stores!(odet, equil, mats, intr) return odet @@ -314,9 +263,6 @@ end odet_fwd = run_and_capture("Forward") odet_ric = run_and_capture("Riccati") - @test odet_ric.step < odet_fwd.step - @test length(odet_ric.psi_store) < length(odet_fwd.psi_store) - # The forward path returns dense ξ in the axis basis, ready for PerturbedEquilibrium. @test odet_fwd.u_store_el_basis @test odet_fwd.du_store_populated diff --git a/test/runtests_resist_eval.jl b/test/runtests_resist_eval.jl index f82b5f6595..2f703a53f2 100644 --- a/test/runtests_resist_eval.jl +++ b/test/runtests_resist_eval.jl @@ -74,18 +74,10 @@ dq = deriv_view(equil.profiles.q_spline, 1) s1 = SingType(; psifac=0.3, rho=sqrt(0.3), m=[2], n=[1], q=2.0, q1=dq(0.3), - delta_prime=ComplexF64[], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[]) s2 = SingType(; psifac=0.7, rho=sqrt(0.7), m=[3], n=[1], q=3.0, q1=dq(0.7), - delta_prime=ComplexF64[], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[]) @test s1.restype === nothing @test s2.restype === nothing @@ -105,11 +97,7 @@ dq = deriv_view(equil.profiles.q_spline, 1) s1 = SingType(; psifac=0.3, rho=sqrt(0.3), m=[2], n=[1], q=2.0, q1=dq(0.3), - delta_prime=ComplexF64[], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[]) intr = ForceFreeStates.ForceFreeStatesInternal(; sing=[s1], msing=1) ForceFreeStates.resist_eval_all!(intr, equil) @@ -138,11 +126,7 @@ @testset "ggj_parameters: errors when restype not populated" begin s_unpop = SingType(; psifac=0.5, rho=sqrt(0.5), m=[2], n=[1], q=2.0, q1=1.0, - delta_prime=ComplexF64[], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[]) @test s_unpop.restype === nothing @test_throws ArgumentError ggj_parameters(s_unpop, equil; eta=1e-7, rho=1e-7) end @@ -151,11 +135,7 @@ dq = deriv_view(equil.profiles.q_spline, 1) s1 = SingType(; psifac=0.3, rho=sqrt(0.3), m=[2], n=[1], q=2.0, q1=dq(0.3), - delta_prime=ComplexF64[], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[]) intr = ForceFreeStates.ForceFreeStatesInternal(; sing=[s1], msing=1) ForceFreeStates.resist_eval_all!(intr, equil) gs = [ggj_parameters(intr.sing[1], equil; eta=eta, rho=rho, ising=1)] diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index f38ada7aa3..e72c492ad6 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -22,6 +22,7 @@ include("display_check.jl") merge!(inputs["ForceFreeStates"], ffs_overrides) new = get(inputs["ForceFreeStates"], "integrator", "Riccati") old == new || haskey(inputs, old) && (new == "Galerkin" ? delete!(inputs, old) : (inputs[new] = pop!(inputs, old))) + haskey(inputs, "Riccati") && delete!(inputs["Riccati"], "renorm_threshold") for (name, section) in extra_sections haskey(inputs, name) ? merge!(inputs[name], section) : (inputs[name] = section) end diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index b3904b9702..c6e9c7ca41 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -1,22 +1,34 @@ -using LinearAlgebra, Random, TOML +using LinearAlgebra, Logging, TOML const FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates -# The Solovev fixture prepared as solve prepares it, up to the integration. Each integration mutates its +# A fixture (Solovev by default) prepared as solve prepares it, up to the integration. Each integration mutates its # intr (sing[s].delta_prime etc.), so every run takes a freshly prepared one. -function prepared_solovev() +function prepared_solovev(; fixture="regression_solovev_ideal_example", integrator="Riccati", singfac_min=nothing, nchunks=0, over=Dict{String,Any}()) GPEC = GeneralizedPerturbedEquilibrium - ex = joinpath(@__DIR__, "test_data", "regression_solovev_ideal_example") + ex = joinpath(@__DIR__, "test_data", fixture) inputs = TOML.parsefile(joinpath(ex, "gpec.toml")) - # The fixture's [Forward] settings drive both paths; the Riccati control also carries the chunking. - inputs["ForceFreeStates"]["integrator"] = "Riccati" - inputs["Riccati"] = pop!(inputs, "Forward") + # The fixture's [Forward] tolerance drives both integrators; the Riccati control also carries the chunking. + inputs["ForceFreeStates"]["integrator"] = integrator + if integrator == "Riccati" + inputs["Riccati"] = delete!(pop!(inputs, "Forward"), "renorm_threshold") + inputs["Riccati"]["nchunks"] = nchunks + end + singfac_min === nothing || (inputs["ForceFreeStates"]["singfac_min"] = singfac_min) + merge!(inputs["ForceFreeStates"], over) equil = GPEC.Equilibrium.PlasmaEquilibrium(GPEC.equilibrium_config(inputs, ex), GPEC.analytic_config(inputs)) prob = GPEC.ForceBalanceProblem(equil; GPEC.force_balance_keywords(inputs, ex)...) ctrl, intr, equil, metric, mats = GPEC._prepare_solve(prob, GPEC.force_balance_algorithm(inputs)) return ctrl, intr, equil, metric, mats end +# Free-boundary energy eigenvalues of a Solovev fixture, crossing each surface at `singfac_min`. +function solovev_energies(integrator, singfac_min; fixture="regression_solovev_ideal_example") + ctrl, intr, equil, _, mats = prepared_solovev(; fixture, integrator, singfac_min) + odet = first(FFS.eulerlagrange_integration(ctrl, equil, mats, intr)) + return FFS.free_run(odet, ctrl, equil, mats, intr).et +end + @testset "Riccati Integration Tests" begin # ── Pure matrix unit tests — no equilibrium needed ──────────────────────── @@ -59,69 +71,45 @@ end @test u[:, :, 1] ≈ S rtol = 1e-12 end - @testset "renormalize_riccati! (OdeState)" begin - N = 3 - rng = [1.0+0.5im 0.2im 0.1; - 0.0im 1.2+0.1im 0.0; - 0.1+0.1im 0.0 0.9+0.3im] - U1 = rng .+ 0.5 * I(N) - U2 = 0.2 * rng .+ I(N) - - odet = FFS.OdeState(N, 10, 5, 1) - odet.u[:, :, 1] .= U1 - odet.u[:, :, 2] .= U2 - - S_expected = U1 / U2 - intr = FFS.ForceFreeStatesInternal(; mpert=N, numpert_total=N) - - FFS.renormalize_riccati!(odet, intr) - - @test odet.u[:, :, 2] ≈ I(N) - @test odet.u[:, :, 1] ≈ S_expected rtol = 1e-12 - end - # ── Shared Solovev setup ────────────────────────────────────────────────── # # equil (Grad-Shafranov solve) and mats (metric matrices) are expensive and # immutable after construction — built ONCE and shared across all tests below. # intr is cheap to (re)initialize but is mutated by each integration run # (sing[s].delta_prime etc.), so a fresh copy is made for each integration. - # - # Integration runs: - # intr_ric / odet_ric — Riccati path (shared by most tests) - # intr_fwd / odet_fwd — Forward path (energy comparison only) ctrl, intr_ric, equil, metric, mats = prepared_solovev() N = intr_ric.numpert_total - # Riccati integration. The driver returns (odet, propagators, chunks, S_at_surface_left); - # only odet is used here. - odet_ric, _, _, _ = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr_ric) - - # Save inline Δ' values before any test that calls compute_delta_prime_from_ca! - # (which overwrites intr_ric.sing[s].delta_prime) - delta_prime_inline = [copy(intr_ric.sing[s].delta_prime) for s in 1:intr_ric.msing] - - vac_ric = FFS.free_run(odet_ric, ctrl, equil, mats, intr_ric) - et_ric = real(vac_ric.et[1]) - - # Forward integration (needed only for energy comparison). - _, intr_fwd, _, _, _ = prepared_solovev() - odet_fwd, _, _, _ = FFS.forward_eulerlagrange_integration(ctrl, equil, mats, intr_fwd) - vac_fwd = FFS.free_run(odet_fwd, ctrl, equil, mats, intr_fwd) - et_fwd = real(vac_fwd.et[1]) + odet_ric = first(FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr_ric)) # ───────────────────────────────────────────────────────────────────────── - @testset "Riccati integration matches forward ODE — Solovev example" begin - # The two formalisms solve the same system, so the leading energy eigenvalue must - # agree closely; the measured Solovev disagreement is ≈5e-5. A regression of the - # Riccati/renormalization algorithm to ~1 % error would fail here loudly. - @test isapprox(et_ric, et_fwd; rtol=1e-4) + @testset "energy does not depend on the crossing distance" begin + et_far = solovev_energies("Riccati", 1e-3) + et_near = solovev_energies("Riccati", 1e-5) + @test isapprox(et_far[1], et_near[1]; rtol=1e-6) + # Forward's trapezoid crossing reaches the same energy only as the distance shrinks. + et_forward = solovev_energies("Forward", 1e-6) + @test isapprox(real(et_far[1]), real(et_forward[1]); rtol=1e-3) + end - # Riccati stores chunk endpoints, the forward path stores every saved ODE step, - # so the Riccati store is always the sparser of the two. - @test odet_ric.step <= odet_fwd.step + @testset "surface with two resonances" begin + fixture = "regression_solovev_ideal_example_multi_n" + et_far = solovev_energies("Riccati", 1e-3; fixture) + et_near = solovev_energies("Riccati", 1e-5; fixture) + et_forward = solovev_energies("Forward", 1e-6; fixture) + # The least-stable multi-n eigenvalue is near marginal, so its relative tolerances are looser. + @test isapprox(et_far[1], et_near[1]; rtol=1e-4) + @test isapprox(real(et_far[1]), real(et_forward[1]); rtol=5e-3) + end + + @testset "stored states" begin + # Every solver step of every chunk is stored, reduced to (S, I), in increasing ψ. + @test odet_ric.step == length(odet_ric.psi_store) == size(odet_ric.u_store, 4) + @test all(diff(odet_ric.psi_store) .> 0) + @test all(odet_ric.u_store[:, :, 2, k] ≈ I(N) for k in 1:odet_ric.step) + @test odet_ric.u_store[:, :, :, end] ≈ odet_ric.u end # Note: a Solovev per-surface Δ' regression testset previously lived here, @@ -132,79 +120,43 @@ end # STRIDE BVP Δ' matrix (see runtests_parallel_integration.jl). @testset "Riccati end state has U₂ ≈ I" begin - # The outer-region re-integration that closes riccati_eulerlagrange_integration - # leaves odet.u[:,:,2] as the identity (canonical Riccati convention after final renorm) + # The edge state is reduced to the canonical Riccati form (S, I). @test odet_ric.u[:, :, 2] ≈ I(N) rtol = 1e-10 end - @testset "riccati_der! formula — Glasser 2018 Eq. 19" begin - # Verify riccati_der! correctly evaluates dS/dψ = w†·F̄⁻¹·w − S·Ḡ·S, w = Q − K̄·S. - # - # Test states are Hermitian (physical constraint: the EL system preserves S†=S from - # the axis). Non-Hermitian states would give ~5% disagreement — not a bug, but a - # consequence of the derivation assuming the physical symmetry. - # - # See benchmarks/benchmark_riccati_der.jl for the extended version with output. - - # Use an initialized OdeState just for spline_hint and chunk bounds - odet_tmp = FFS.OdeState(N, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr_ric.msing) - FFS.initialize_el_at_axis!(odet_tmp, ctrl, mats, equil.profiles, intr_ric) - chunks = FFS.chunk_el_integration_bounds(odet_tmp, ctrl, intr_ric) - - # 30% into each chunk: away from singularities at psi_end - test_psis = [c.psi_start + 0.3 * (c.psi_end - c.psi_start) for c in chunks] - - rng = Random.MersenneTwister(42) - for psi in test_psis - # Hermitian S: physical Riccati matrix is Hermitian (preserved by EL symmetry) - A = randn(rng, ComplexF64, N, N) - S = (A + A') / 2 - - # Manual RHS: w†·F̄⁻¹·w − S·Ḡ·S - L = zeros(ComplexF64, N, N) - Kmat = zeros(ComplexF64, N, N) - Gmat = zeros(ComplexF64, N, N) - mats.ideal.F_spline_lower(vec(L), psi; hint=mats._hint) - mats.ideal.K_spline(vec(Kmat), psi; hint=mats._hint) - mats.ideal.G_spline(vec(Gmat), psi; hint=mats._hint) - q = equil.profiles.q_spline(psi) - singfac = vec(1.0 ./ ((intr_ric.mlow:intr_ric.mhigh) .- - q .* (intr_ric.nlow:intr_ric.nhigh)')) - w = -Kmat * S - for i in 1:N - w[i, i] += singfac[i] - end - v = copy(w) - ldiv!(LowerTriangular(L), v) - ldiv!(UpperTriangular(L'), v) - dS_manual = adjoint(w) * v - S * Gmat * S - - # riccati_der! RHS - u_ric = zeros(ComplexF64, N, N, 2) - du_ric = zeros(ComplexF64, N, N, 2) - u_ric[:, :, 1] .= S - u_ric[:, :, 2] .= Matrix{ComplexF64}(I, N, N) - dummy = FFS.IntegrationChunk(psi, psi, false, 0, 1) - params = (ctrl, equil, mats, intr_ric, odet_tmp, dummy) - FFS.riccati_der!(du_ric, u_ric, params, psi) - - rel_err = norm(du_ric[:, :, 1] - dS_manual) / max(norm(dS_manual), 1e-10) - @test rel_err < 1e-10 + @testset "Δ′ does not depend on the chunk layout" begin + # The TJ fixture has a well-conditioned Δ′; the smallest layout has two chunks per segment. + function delta_prime(nchunks) + ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example", nchunks) + odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) + wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv + delta_prime = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.bases, riccati.axis_state; wv, psio=equil.psio) + return delta_prime.matrix, riccati.chunks end + dp_auto, chunks_auto = delta_prime(0) + dp_few, chunks_few = delta_prime(1) + @test length(chunks_few) < length(chunks_auto) + @test !isempty(dp_auto) && all(isfinite, dp_auto) + @test isapprox(dp_few, dp_auto; rtol=1e-4) end - @testset "compute_delta_prime_from_ca! matches inline Δ'" begin - # Verify the standalone Δ' formula matches the inline Riccati crossing computation. - # Both apply the identical diagonal formula to the same ca_l/ca_r arrays, so the - # result must be bit-for-bit identical (not just approximately equal). - # - # Note: this call overwrites intr_ric.sing[s].delta_prime; delta_prime_inline was - # saved before free_run above so it holds the original inline values. - # - FFS.compute_delta_prime_from_ca!(odet_ric, intr_ric, equil) - for s in 1:intr_ric.msing - @test intr_ric.sing[s].delta_prime == delta_prime_inline[s] - end + @testset "truncation at the edge energy peak" begin + # The chunks, their propagators and the Δ′ system follow the edge to the peak. + ctrl, intr, equil, _, mats = prepared_solovev(; over=Dict{String,Any}("truncate_at_dW_peak" => true)) + odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) + (; propagators, chunks, bases, axis_state) = riccati + @test intr.psilim == odet.psi_store[end] == chunks[end].psi_end + @test length(propagators) == length(chunks) && count(c -> c.needs_crossing, chunks) == intr.msing + @test odet.u_store[:, :, :, end] ≈ odet.u + free = FFS.free_run(odet, ctrl, equil, mats, intr) + @test isfinite(free.et[1]) + # The Δ′ system reproduces the plasma response of the axis-to-edge products, and says so when it does not. + delta_prime = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; + wv=free.wv, wp=free.wp, psio=equil.psio) + @test size(delta_prime.matrix) == (intr.msing, intr.msing) && all(isfinite, delta_prime.matrix) + @test size(delta_prime.coil) == (2 * intr.msing, intr.numpert_total) + @test_logs (:warn, r"differs from the axis-to-edge one") FFS.compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; + wv=free.wv, wp=1.01 .* free.wp, psio=equil.psio) end end diff --git a/test/runtests_sing.jl b/test/runtests_sing.jl index ed477946f3..e338a8faf5 100644 --- a/test/runtests_sing.jl +++ b/test/runtests_sing.jl @@ -91,7 +91,7 @@ using FastInterpolations: cubic_interp, CubicFit, LinearBinarySearch, Series, Ex equil = load_equilibrium_from_gpec(joinpath(@__DIR__, "test_data", "regression_solovev_ideal_example", "gpec.toml")) # default single toroidal mode used in test data; matches intr.nlow set below - ctrl = GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesControl(; nn_low=1) + ctrl = GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesControl(; nn_low=1, algorithm=GeneralizedPerturbedEquilibrium.Forward()) intr = GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesInternal() intr.numpert_total = 32 # replacing mpert (we set equal to 32). This is the same as msol # set mode ranges so sing_der can form singfac_vec consistently diff --git a/test/runtests_slayer_inputs.jl b/test/runtests_slayer_inputs.jl index 89b27dfbdc..2d44a5877a 100644 --- a/test/runtests_slayer_inputs.jl +++ b/test/runtests_slayer_inputs.jl @@ -26,11 +26,7 @@ # Helper to build a minimal SingType without touching unused fields _mk_sing(; psi, q, q1, m, n, delta_prime=-10.0 + 0im) = SingType(; psifac=psi, rho=sqrt(psi), m=[m], n=[n], q=q, q1=q1, - delta_prime=ComplexF64[delta_prime], - delta_prime_col=zeros(ComplexF64, 0, 0), - ua_left=zeros(ComplexF64, 0, 0, 0), - ua_right=zeros(ComplexF64, 0, 0, 0), - psi_ua_left=0.0, psi_ua_right=0.0) + delta_prime=ComplexF64[delta_prime]) @testset "surface_minor_radius: continuity + outboard > 0" begin # Minor radius grows monotonically with ψ (outboard midplane). diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 41883afea2..8d54f7b761 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -18,15 +18,16 @@ include("display_check.jl") ) wall = GPEC.Vacuum.parse_wall(get(deck, "Wall", nothing)) - # The deck's `[ForceFreeStates]` block as `solve` keywords, less `nn` and the wall; its `[Forward]` numerics - # serve both ODE integrators. + # The deck's `[ForceFreeStates]` block as `solve` keywords, less `nn` and the wall; its `[Forward]` tolerance + # serves both ODE integrators. ffs_kwargs = filter(p -> !(p.first in (:nn, :wall)), GPEC.force_balance_keywords(deck, template)) ode_kwargs = GPEC.section_keywords(deck["Forward"], "Forward", GPEC._struct_fields(Forward)) forward = Forward(; ode_kwargs...) - riccati = Riccati(; ode_kwargs...) + riccati_kwargs = GPEC.section_keywords(delete!(copy(deck["Forward"]), "renorm_threshold"), "Riccati", GPEC._struct_fields(Riccati)) + riccati = Riccati(; riccati_kwargs...) # Copy the fixture deck into `dir` and apply `[Equilibrium]` / `[ForceFreeStates]` overrides and extra sections. - # An `integrator` override moves the `[Forward]` numerics to `[Riccati]`, or drops them for Galerkin. + # An `integrator` override moves the `[Forward]` tolerance to `[Riccati]`, or drops the section for Galerkin. function _stage_deck(dir; eq_overrides=Dict{String,Any}(), ffs_overrides=Dict{String,Any}(), extra_sections=Dict{String,Any}()) for name in readdir(template) cp(joinpath(template, name), joinpath(dir, name)) @@ -36,7 +37,8 @@ include("display_check.jl") merge!(inputs["Equilibrium"], eq_overrides) merge!(inputs["ForceFreeStates"], ffs_overrides) ode = pop!(inputs, "Forward") - inputs["ForceFreeStates"]["integrator"] in ("Forward", "Riccati") && (inputs[inputs["ForceFreeStates"]["integrator"]] = ode) + inputs["ForceFreeStates"]["integrator"] == "Forward" && (inputs["Forward"] = ode) + inputs["ForceFreeStates"]["integrator"] == "Riccati" && (inputs["Riccati"] = delete!(ode, "renorm_threshold")) foreach(section -> delete!(inputs, section), ("LocalStability", "Ballooning")) merge!(inputs, extra_sections) open(io -> TOML.print(io, inputs), toml_path, "w") @@ -69,7 +71,7 @@ include("display_check.jl") mktempdir() do dir reference = GPEC.main([_stage_deck(dir; ffs_overrides=Dict{String,Any}("integrator" => "Riccati"))]).ffs prob = ForceBalanceProblem(equil; nn=1, wall=wall, ffs_kwargs...) - api = solve(prob, Riccati(; ode_kwargs..., nchunks=40)) + api = solve(prob, Riccati(; riccati_kwargs..., nchunks=40)) @test api.integrator === :riccati @test api.control.algorithm.nchunks == 40 @@ -79,9 +81,10 @@ include("display_check.jl") @test size(api.delta_prime.matrix) == (msing, msing) @test api.delta_prime.matrix ≈ FFS.pest3_decompose(api.delta_prime.raw).Δ - # Chunking is a decomposition of the same problem, so Δ′ tracks the TOML run. + # Chunking is a decomposition of the same problem, so Δ′ tracks the TOML run to the accuracy + # the propagator products keep at this fixture's singfac_min = 1e-6. @test size(reference.delta_prime.matrix) == size(api.delta_prime.matrix) - @test api.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-6 + @test api.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-4 # With the deck's own (auto) chunking the two runs are the same computation. same = solve(prob, riccati) From ecac988fc9860a87dcb9d1cb0a8cedb14f68362d Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Fri, 13 Nov 2026 23:57:46 +0100 Subject: [PATCH 05/27] ForceFreeStates.Riccati - FEATURE! - Publish solution profiles from the Riccati integrator --- docs/src/stability.md | 2 +- src/Analysis/Registry.jl | 2 +- src/Display.jl | 4 +- src/ForceFreeStates/EulerLagrange.jl | 3 - src/ForceFreeStates/Matching/MatchProblem.jl | 3 +- src/ForceFreeStates/Result.jl | 10 +- src/ForceFreeStates/Riccati/Crossings.jl | 20 ++- src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 22 +--- src/ForceFreeStates/Riccati/Driver.jl | 121 +++++++++++------- src/ForceFreeStates/Riccati/Propagators.jl | 2 + src/ForceFreeStates/Run.jl | 4 +- src/ForceFreeStates/Utils.jl | 6 +- .../PerturbedEquilibrium.jl | 5 +- test/runtests_analysis_plots.jl | 10 +- test/runtests_eulerlagrange.jl | 10 -- test/runtests_parallel_integration.jl | 28 +--- test/runtests_result_struct.jl | 13 +- test/runtests_riccati.jl | 40 ++++-- test/runtests_solve_api.jl | 2 +- 19 files changed, 164 insertions(+), 143 deletions(-) diff --git a/docs/src/stability.md b/docs/src/stability.md index 0fe50c3f68..be8eaebff7 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -41,7 +41,7 @@ Its global boundary-value problem over all surfaces gives the Δ′ matrix of [G `[ForceFreeStates] integrator` selects the radial method; its numerical settings sit in a section of the same name. -- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the Riccati matrix ``S`` at every solver step, not the displacement, so it yields no ``\xi`` profiles. +- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the solution at every solver step, like Forward, so its result carries ``\xi`` profiles; `plasma_response` does not accept a Riccati result yet. - `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction at each rational surface. It returns dense displacement profiles, and is the only integrator whose result `plasma_response` accepts (the response operators are built from the dense ``\xi`` solution; a wall is refused too) and the only one that supports the kinetic solve. - `"Galerkin"` (`[Galerkin]`) solves the outer region variationally on a finite-element basis, giving the resistive Δ′ matrix and the PEST-3 blocks but no free-boundary energies; see [Galerkin Solver](galerkin.md). diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index 03940daa32..159531f0d1 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -44,7 +44,7 @@ What each capability needs, worded as what to change in the run to get it. const REASONS = Dict{Symbol,String}( :equilibrium => "needs an equilibrium", :singular_surfaces => "needs rational surfaces in the integration domain", - :solution_profiles => "needs stored ξ profiles: use the Forward integrator or a matched Galerkin solve (Riccati and unmatched Galerkin store none)", + :solution_profiles => "needs stored ξ profiles: use the Forward or Riccati integrator, or a matched Galerkin solve (unmatched Galerkin stores none)", :fixed_boundary_criterion => "needs the critical determinant scan: use the Forward or Riccati integrator (Galerkin computes none)", :free_boundary => "needs the free-boundary energies: run with vac_flag = true and the Forward or Riccati integrator", :edge_scan => "needs the edge stability scan: set dW_edge_scan_start below psilim", diff --git a/src/Display.jl b/src/Display.jl index 662cbbd476..f2bb509569 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -180,13 +180,12 @@ end function _solution_note(r::ForceFreeStates.ForceFreeStatesResult) r.solution === nothing || return "ξ profiles stored ($(r.solution.step) ψ nodes, $(r.solution.basis) basis)" - return r.integrator === :riccati ? "not computed (Riccati stores no ξ profiles)" : "not computed ($(r.integrator) without a match)" + return "not computed ($(r.integrator) without a match)" end # The crit sign-change count is not yet a validated stability verdict, so it is reported raw. function _fixed_boundary_note(r::ForceFreeStates.ForceFreeStatesResult) r.diagnostics === nothing && return "not computed by the $(r.integrator) integrator" - r.integrator === :riccati && return "not reported (the Riccati (S, I) history cannot show crossings)" r.control.kinetic === nothing || return "not reported (crit assumes a Hermitian W)" return "$(_plural(r.diagnostics.nzero, "crit sign change")) (unvalidated, not a stability verdict)" end @@ -254,6 +253,7 @@ _resonances(r::PlasmaResponse) = ["$(m)/$(n)" for (m, n) in zip(r.rational_m_res function _missing_operators_note(r::PlasmaResponse) r.ffs.free_boundary === nothing && return "not computed (needs a free-boundary result)" r.ffs.solution === nothing && return "not computed (needs stored ξ profiles)" + r.ffs.integrator === :riccati && return "not computed (a Riccati result is not accepted yet)" return "not computed" end diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index 5e32e8e533..ef90625414 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -53,8 +53,6 @@ records needed to undo it, and singular-surface asymptotic coefficients. - `du_store::Array{ComplexF64,3}` - du₁/dψ at each stored step, shape `(numpert_total, numpert_total, step)`; empty until `materialize_derivative_stores!` fills it (the galerkin-matched path supplies it at construction). - `xi_s_store::Array{ComplexF64,3}` - Clebsch displacement Ξ_s (Glasser 2016 Eq. 18) at each stored step; empty until materialized, like `du_store`. - - `u_store_el_basis::Bool` - True when `u_store` holds the Euler-Lagrange state; false on the Riccati path (stored states are the Riccati matrix), where derivative - stores cannot be materialized. - `du_store_populated::Bool` - True once `du_store`/`xi_s_store` hold valid data in the final basis. - `crit_store::Vector{Float64}` - Critical eigenvalue (smallest eigenvalue of W⁻¹) at each stored step. - `ca_r::Array{ComplexF64,4}` - Asymptotic coefficients right of each singular surface, shape `(numpert_total, numpert_total, 2, msing)`. @@ -94,7 +92,6 @@ records needed to undo it, and singular-surface asymptotic coefficients. u_store::Array{ComplexF64,4} = Array{ComplexF64}(undef, numpert_total, numpert_total, 2, numsteps_init) du_store::Array{ComplexF64,3} = Array{ComplexF64}(undef, numpert_total, numpert_total, 0) xi_s_store::Array{ComplexF64,3} = Array{ComplexF64}(undef, numpert_total, numpert_total, 0) - u_store_el_basis::Bool = true du_store_populated::Bool = false crit_store::Vector{Float64} = Vector{Float64}(undef, numsteps_init) ca_r::Array{ComplexF64,4} = zeros(ComplexF64, numpert_total, numpert_total, 2, msing) diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index f80f52eb46..522409c46d 100644 --- a/src/ForceFreeStates/Matching/MatchProblem.jl +++ b/src/ForceFreeStates/Matching/MatchProblem.jl @@ -276,8 +276,9 @@ end # Copy of ffs with the match applied; the ideal reference keeps closure :ideal, its zero bpen and δW. function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult, ideal::Bool) gal = ffs.galerkin + # Without a matched ξ, the ideal solution stands only for the ideal reference. solution = (gal !== nothing && gal.solution !== nothing && !isempty(match.xi)) ? - _matched_gal_profiles(gal, match, ffs.mats, ffs) : ffs.solution + _matched_gal_profiles(gal, match, ffs.mats, ffs) : (ideal ? ffs.solution : nothing) ideal && return _with(ffs; match=match, solution=solution) # The ideal δW does not describe the matched plasma; PE gates on its absence. return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index adca699c44..2251f1ee7a 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -63,7 +63,7 @@ Every final result records how its basis crosses the rational surfaces, so bpen inner layer, per surface (rows follow `surfaces`) and driving mode; all zeros under `:ideal` and `:regular` closure. - `match::Union{Nothing,MatchResult}` - The [`MatchResult`](@ref) of a `MatchProblem` solve; `nothing` otherwise. - `solution::Union{Nothing,SolutionProfiles}` - THE solve's ξ solution; `nothing` when the - formalism produced none (Riccati, and Galerkin without a match). + formalism produced none (Galerkin without a match). - `diagnostics::Union{Nothing,OdeState}` - The integrator's raw ODE state (ψ trace, `crit`, edge scan, asymptotic coefficients). Written to HDF5; not a consumable solution. - `wp::Union{Nothing,Matrix{ComplexF64}}` - Fixed-boundary plasma energy matrix `W_p = (U₂·U₁⁻¹)/ψ₀²` at @@ -138,7 +138,7 @@ with a message naming what a solution takes to produce. """ function require_solution(result::ForceFreeStatesResult, calc::AbstractString) result.solution === nothing || return true - @warn "Skipping $calc: no ξ solution — dense profiles require a Forward (or matched Galerkin) run; " * + @warn "Skipping $calc: no ξ solution — dense profiles require a Forward, Riccati or matched Galerkin run; " * "this result came from the $(result.integrator) integrator" return false end @@ -197,9 +197,9 @@ function build_result( gal_data::Union{Nothing,GalerkinResult}, delta_prime::Union{Nothing,DeltaPrimeData} ) - # The forward sweep is the only formalism whose stores need materializing; doing it here - # keeps `SolutionProfiles.du_store`/`xi_s_store` populated by construction. - solution = if integrator === :forward && odet !== nothing + # The ODE integrators' stores need materializing; doing it here keeps + # `SolutionProfiles.du_store`/`xi_s_store` populated by construction. + solution = if odet !== nothing materialize_derivative_stores!(odet, equil, mats, intr) SolutionProfiles(:el_axis, odet.step, odet.psi_store, odet.q_store, odet.u_store, odet.du_store, odet.xi_s_store) diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index 5691e5c4c2..50ec5e4d76 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -20,29 +20,35 @@ function asymptotic_bases(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeState end """ - cross_singular_surface!(odet, intr, ising) + cross_singular_surface!(odet, intr, ising) -> Matrix{ComplexF64} Cross singular surface `ising` [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]. `odet.u` holds asymptotic coefficients, in the left basis on entry and the right basis on return, with no big solution on -either side; both sets are recorded in `odet.ca_l` and `odet.ca_r`. +either side; both sets are recorded in `odet.ca_l` and `odet.ca_r`. Returns the N × N matrix that takes the +columns on return to their continuation left of the surface, in the columns on entry. """ function cross_singular_surface!(odet::OdeState, intr::ForceFreeStatesInternal, ising::Int) singp = intr.sing[ising] ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - eliminate_big_solutions!(odet.u, ipert_res) + continuation = eliminate_big_solutions!(odet.u, ipert_res) odet.ca_l[:, :, :, ising] .= odet.u start_small_solutions!(odet.u, ipert_res) odet.ca_r[:, :, :, ising] .= odet.u odet.ca_populated = true + # The small solutions introduced on the right do not exist on the left. + continuation[:, ipert_res] .= 0 + return continuation end """ - eliminate_big_solutions!(ca, ipert_res) + eliminate_big_solutions!(ca, ipert_res) -> Matrix{ComplexF64} Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the -basis) so that only column `ipert_res[i]` carries the big solution of resonance `i`. +basis) so that only column `ipert_res[i]` carries the big solution of resonance `i`. Returns the N × N column +transformation applied. """ function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) + transform = Matrix{ComplexF64}(I, size(ca, 2), size(ca, 2)) for (i, ipert) in enumerate(ipert_res) candidates = setdiff(axes(ca, 2), @view ipert_res[1:(i-1)]) pivot = candidates[argmax(abs.(@view ca[ipert, candidates, 1]))] @@ -50,15 +56,17 @@ function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) col == pivot && continue factor = ca[ipert, col, 1] / ca[ipert, pivot, 1] @views ca[:, col, :] .-= factor .* ca[:, pivot, :] + @views transform[:, col] .-= factor .* transform[:, pivot] ca[ipert, col, 1] = 0 end if pivot != ipert swapped = ca[:, pivot, :] @views ca[:, pivot, :] .= ca[:, ipert, :] ca[:, ipert, :] .= swapped + transform[:, [pivot, ipert]] .= transform[:, [ipert, pivot]] end end - return ca + return transform end """ diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index 7866534f54..d2269e0c07 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -4,7 +4,7 @@ const DELTA_PRIME_RESPONSE_MISMATCH = 1e-6 """ - compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> Union{Nothing,DeltaPrimeData} + compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> Union{Nothing,DeltaPrimeData} Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]. @@ -12,7 +12,7 @@ Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix ### Arguments - `intr`: Read for its mode space and singular surfaces. - - `propagators`, `chunks`, `bases`, `axis_state`: From `riccati_eulerlagrange_integration`. + - `propagators`, `chunks`, `axis_state`: From `riccati_eulerlagrange_integration`. - `wv`: Singfac-scaled vacuum response for the edge condition `wp + wv = 0`; `nothing` puts a conducting wall there. - `wp`: Plasma response from `free_run`. A warning is issued when the BVP's own differs from it by more than `DELTA_PRIME_RESPONSE_MISMATCH`. @@ -28,7 +28,6 @@ function compute_delta_prime_matrix( intr::ForceFreeStatesInternal, propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, - bases::AbstractDict, axis_state::Matrix{ComplexF64}; wv::Union{Nothing,Matrix{ComplexF64}}=nothing, wp::Union{Nothing,Matrix{ComplexF64}}=nothing, @@ -43,7 +42,7 @@ function compute_delta_prime_matrix( N = intr.numpert_total ipert_all = [1 + sing[j].m[1] - intr.mlow + (sing[j].n[1] - intr.nlow) * intr.mpert for j in 1:msing] - uShootR, uShootL = _shooting_matrices(propagators, chunks, bases, i_crossings) + uShootR, uShootL = _shooting_matrices(propagators, chunks, i_crossings) uAxis = Matrix(qr(axis_state).Q)[:, 1:N] M, col_edge = _assemble_bvp(uShootR, uShootL, uAxis, ipert_all, msing, N, wv, psio) @@ -104,22 +103,15 @@ end # Shooting matrices of the BVP [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eqs. 33-35]: `uShootR[j]` and # `uShootL[j]` map the asymptotic coefficients right and left of surface j to the state at the matching point # toward the next and the previous surface. -function _shooting_matrices(propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, - bases::AbstractDict, i_crossings::Vector{Int}) +function _shooting_matrices(propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, i_crossings::Vector{Int}) msing = length(i_crossings) matrix(i) = [propagators[i].u[:, :, 1]; propagators[i].u[:, :, 2]] uShootR = Vector{Matrix{ComplexF64}}(undef, msing) uShootL = Vector{Matrix{ComplexF64}}(undef, msing) for j in 1:msing - if i_crossings[j] == length(chunks) - # The edge is the surface's right inner-layer boundary. - right = bases[chunks[i_crossings[j]].ising].right - uShootR[j] = [right[:, :, 1]; right[:, :, 2]] - else - # The chunk after the surface starts from the right basis; the rest multiply on. - range_R = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:right) - uShootR[j] = foldl((X, i) -> matrix(i) * X, range_R[2:end]; init=matrix(first(range_R))) - end + # The chunk after the surface starts from the right basis; the rest multiply on. + range_R = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:right) + uShootR[j] = foldl((X, i) -> matrix(i) * X, range_R[2:end]; init=matrix(first(range_R))) # The crossing chunk carries the left basis back to its start; forward chunks before it are inverted. range_L = j == 1 ? (1:0) : _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:left) uShootL[j] = foldl((X, i) -> matrix(i) \ X, reverse(range_L); init=matrix(i_crossings[j])) diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index 32524a8476..fb55eef23b 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -4,9 +4,9 @@ Integrate the Euler-Lagrange equations from the axis to `intr.psilim` with parallel chunk propagators [Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507; Glasser & Kolemen 2018, Phys. Plasmas 25, 082502]. -Returns `odet`, whose stores hold the state as (S, I), S = U₁U₂⁻¹, at every stored solver step, and `riccati`, -the inputs of `compute_delta_prime_matrix`: `(; propagators, chunks, bases, axis_state)`, with `axis_state` -(2N × N) the state entering the first crossing chunk. +Returns `odet`, whose stores hold the solution at every stored solver step in columns that are continuous in ψ +and equal (S, I), S = U₁U₂⁻¹, at the edge, and `riccati`, the inputs of `compute_delta_prime_matrix`: +`(; propagators, chunks, columns)`, with `columns` from `_assemble_propagators_serially!`. """ function riccati_eulerlagrange_integration( ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, @@ -20,19 +20,32 @@ function riccati_eulerlagrange_integration( @info " Riccati FM: $(length(chunks)) chunks over $(Threads.nthreads()) thread$(Threads.nthreads() == 1 ? "" : "s")" end - propagators = chunk_propagators(chunks, bases, ctrl.algorithm.eulerlagrange_tolerance, equil, mats, ModeIndices(intr)) + rtol = ctrl.algorithm.eulerlagrange_tolerance + propagators = chunk_propagators(chunks, bases, rtol, equil, mats, ModeIndices(intr)) odet.total_steps += sum(p -> length(p.psi) - 1, propagators) - axis_state = _assemble_propagators_serially!(odet, propagators, chunks, ctrl, equil, intr) - _handle_edge_dW_scan!(odet, chunks, propagators, bases, ctrl, equil, mats, intr) + columns = _assemble_propagators_serially!(odet, propagators, chunks, ctrl, equil, intr) + + if scan_edge_dW!(odet, ctrl, equil, mats, intr) + # The edge moved in: shorten the chunk list and multiply the propagators again over the new domain. + rebuild = truncate_chunks!(chunks, intr.psilim, intr.msing) + resize!(propagators, length(chunks)) + if rebuild !== nothing + start = propagator_start(chunks, rebuild, bases, intr.numpert_total) + propagators[rebuild] = chunk_propagator(chunks[rebuild], start, rtol, equil, mats, ModeIndices(intr)) + end + fill!(odet.u, 0) + initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) + columns = _assemble_propagators_serially!(odet, propagators, chunks, ctrl, equil, intr) + end compute_delta_prime_from_ca!(odet, intr, equil) if intr.verbose @info "Evaluating fixed-boundary stability criterion" end odet.nzero = evaluate_stability_criterion!(odet, equil.profiles) - transform_u!(odet, intr) # no-op when ifix=0 (no Gaussian reduction) + restore_solution_columns!(odet, propagators, chunks, columns) - return odet, (; propagators, chunks, bases, axis_state) + return odet, (; propagators, chunks, columns) end # OdeState at the axis start, with empty stores. @@ -43,7 +56,6 @@ function _initialize_parallel_odet(ctrl::ForceFreeStatesControl, odet = OdeState(intr.numpert_total, 1, 1, intr.msing) initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) odet.new = false - odet.u_store_el_basis = false fill!(odet.unorm0, 1.0) return odet end @@ -74,28 +86,33 @@ function stored_step_indices(prop::ChunkPropagator, chunk::IntegrationChunk, aft end # Multiply the chunk propagators from the axis outward, crossing each singular surface, and fill `odet`'s stores -# with the (S, I) state at every stored step. Returns the state entering the first crossing chunk (2N × N). +# with the (S, I) state at every stored step. Returns what later stages need to rebuild solutions from the +# propagators: `axis_state` (2N × N, the state entering the first crossing chunk), `starts` (per chunk, the +# 2N × N coefficients its propagator multiplies), `stored` and `slots` (per chunk, the stored solver steps and the +# store slot before its first), and `continuations` (per crossing chunk, from `cross_singular_surface!`). function _assemble_propagators_serially!(odet::OdeState, propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) N = intr.numpert_total stored = [stored_step_indices(propagators[i], chunks[i], i > 1 && chunks[i-1].needs_crossing, ctrl) for i in eachindex(chunks)] - slots = cumsum([0; length.(stored)]) # store slot before each chunk's first - odet.psi_store = Vector{Float64}(undef, slots[end]) - odet.q_store = Vector{Float64}(undef, slots[end]) - odet.u_store = Array{ComplexF64}(undef, N, N, 2, slots[end]) + slots = cumsum([0; length.(stored)]) + odet.step = slots[end] + odet.psi_store = Vector{Float64}(undef, odet.step) + odet.q_store = Vector{Float64}(undef, odet.step) + odet.u_store = Array{ComplexF64}(undef, N, N, 2, odet.step) - chunk_starts = Vector{Matrix{ComplexF64}}(undef, length(chunks)) + starts = Vector{Matrix{ComplexF64}}(undef, length(chunks)) + continuations = Dict{Int,Matrix{ComplexF64}}() axis_state = Matrix{ComplexF64}(undef, 0, 0) for (i, chunk) in enumerate(chunks) if chunk.needs_crossing isempty(axis_state) && (axis_state = [odet.u[:, :, 1]; odet.u[:, :, 2]]) apply_propagator_inverse!(odet, propagators[i]) - chunk_starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] - cross_singular_surface!(odet, intr, chunk.ising) + starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] + continuations[i] = cross_singular_surface!(odet, intr, chunk.ising) odet.psifac = chunks[i+1].psi_start else - chunk_starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] + starts[i] = [odet.u[:, :, 1]; odet.u[:, :, 2]] apply_propagator!(odet, propagators[i]) renormalize_riccati_inplace!(odet.u, N) odet.psifac = chunk.psi_end @@ -105,60 +122,68 @@ function _assemble_propagators_serially!(odet::OdeState, propagators::Vector{Chu end end odet.q = equil.profiles.q_spline(odet.psifac) + for (i, prop) in enumerate(propagators), (j, k) in enumerate(stored[i]) + odet.psi_store[slots[i]+j] = prop.psi[k] + odet.q_store[slots[i]+j] = equil.profiles.q_spline(prop.psi[k]) + end + store_propagated!(odet.u_store, propagators, starts, stored, slots; reduce=true) + return (; axis_state, starts, stored, slots, continuations) +end +# Fill `u_store` with each chunk's propagator at its stored steps times that chunk's `coefficients` (2N × N), +# reduced to (S, I) when `reduce`. +function store_propagated!(u_store::Array{ComplexF64,4}, propagators::Vector{ChunkPropagator}, + coefficients::Vector{Matrix{ComplexF64}}, stored::Vector{Vector{Int}}, slots::Vector{Int}; reduce::Bool) + N = size(u_store, 1) nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try - Threads.@threads for i in eachindex(chunks) - prop = propagators[i] + Threads.@threads for i in eachindex(propagators) u = zeros(ComplexF64, N, N, 2) for (j, k) in enumerate(stored[i]) @views for half in 1:2 - mul!(u[:, :, half], prop.steps[k][:, :, half], chunk_starts[i]) + mul!(u[:, :, half], propagators[i].steps[k][:, :, half], coefficients[i]) end - renormalize_riccati_inplace!(u, N) - slot = slots[i] + j - odet.psi_store[slot] = prop.psi[k] - odet.q_store[slot] = equil.profiles.q_spline(prop.psi[k]) - @views odet.u_store[:, :, :, slot] .= u + reduce && renormalize_riccati_inplace!(u, N) + @views u_store[:, :, :, slots[i]+j] .= u end - empty!(prop.psi) - empty!(prop.steps) end finally BLAS.set_num_threads(nblas) end - odet.step = slots[end] - return axis_state end -# Edge-dW scan; on truncation, also cut `chunks` and `propagators` back to the new edge. -function _handle_edge_dW_scan!(odet::OdeState, chunks::Vector{IntegrationChunk}, - propagators::Vector{ChunkPropagator}, bases::AbstractDict, - ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, - intr::ForceFreeStatesInternal) - scan_edge_dW!(odet, ctrl, equil, mats, intr) || return - - rebuild = truncate_chunks!(chunks, intr.psilim, intr.msing) - resize!(propagators, length(chunks)) - if rebuild !== nothing - prop = chunk_propagator(chunks[rebuild], propagator_start(chunks, rebuild, bases, intr.numpert_total), - ctrl.algorithm.eulerlagrange_tolerance, equil, mats, ModeIndices(intr)) - propagators[rebuild] = ChunkPropagator(prop.u, Float64[], Array{ComplexF64,3}[]) +# Rewrite `odet.u_store` from (S, I) into solution columns that are continuous in ψ and equal (S, I) at the edge: +# what `transform_u!` leaves for the forward integrator. +function restore_solution_columns!(odet::OdeState, propagators::Vector{ChunkPropagator}, + chunks::Vector{IntegrationChunk}, columns) + (; starts, stored, slots, continuations) = columns + N = size(odet.u, 1) + edge_columns = Matrix{ComplexF64}(I, N, N) # each chunk's start columns in terms of the edge columns + coefficients = similar(starts) + for i in reverse(eachindex(chunks)) + if chunks[i].needs_crossing + edge_columns = continuations[i] * edge_columns + else + chunk_end = [propagators[i].u[:, :, 1]; propagators[i].u[:, :, 2]] * starts[i] + edge_columns = chunk_end[(N+1):(2N), :] \ edge_columns + end + coefficients[i] = starts[i] * edge_columns end - return + store_propagated!(odet.u_store, propagators, coefficients, stored, slots; reduce=false) end """ truncate_chunks!(chunks, psi_edge, msing) -> Union{Int,Nothing} Cut `chunks` back to an edge at `psi_edge`: drop those past it, end the straddling one at it, and turn a -crossing chunk whose surface is no longer in the plasma into a forward chunk. Returns the index of a chunk -that changed and so must be re-integrated. +crossing chunk whose surface is no longer in the plasma into a forward chunk. An edge at the right boundary of +a surface keeps the chunk after its crossing, at zero width. Returns the index of a chunk that changed and so +must be re-integrated. """ function truncate_chunks!(chunks::Vector{IntegrationChunk}, psi_edge::Real, msing::Int) - last = findlast(c -> c.psi_start < psi_edge, chunks) + last = findlast(i -> chunks[i].psi_start < psi_edge || (i > 1 && chunks[i-1].needs_crossing && chunks[i].psi_start == psi_edge), + eachindex(chunks)) last === nothing && error("truncate_chunks!: edge ψ=$psi_edge lies before all chunk starts") resize!(chunks, last) c = chunks[last] diff --git a/src/ForceFreeStates/Riccati/Propagators.jl b/src/ForceFreeStates/Riccati/Propagators.jl index 0d2f61ccd1..65662fd779 100644 --- a/src/ForceFreeStates/Riccati/Propagators.jl +++ b/src/ForceFreeStates/Riccati/Propagators.jl @@ -39,6 +39,8 @@ solver step. """ function chunk_propagator(chunk::IntegrationChunk, u0::Array{ComplexF64,3}, rtol::Float64, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices) + # A zero-width chunk only carries its start basis. + chunk.psi_start == chunk.psi_end && return ChunkPropagator(copy(u0), [chunk.psi_start], [copy(u0)]) tspan = chunk.direction == 1 ? (chunk.psi_start, chunk.psi_end) : (chunk.psi_end, chunk.psi_start) spline_hint, mats_hint = Ref(1), Ref(1) function derivative!(du, u, _, psi) diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 5256fe4102..7fee4f550b 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -85,7 +85,7 @@ function run_force_free_states( @info "Computing free boundary energies ($wall_desc)" end free_energies = free_run(odet, ctrl, equil, mats, intr) - odet.u_store_el_basis && normalize_eigenfunctions!(odet, free_energies.wt, equil.psio) + normalize_eigenfunctions!(odet, free_energies.wt, equil.psio) if real(free_energies.et[1]) < 0 if intr.verbose @warn "Free-boundary mode unstable for n = $nstring" @@ -101,7 +101,7 @@ function run_force_free_states( if intr.verbose @info "Computing Δ' matrix (STRIDE BVP with vacuum coupling)" end - delta_prime = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.bases, riccati.axis_state; + delta_prime = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) end end diff --git a/src/ForceFreeStates/Utils.jl b/src/ForceFreeStates/Utils.jl index 57a54d5e77..f3fb7af636 100644 --- a/src/ForceFreeStates/Utils.jl +++ b/src/ForceFreeStates/Utils.jl @@ -83,9 +83,7 @@ fixup transforms and the free-boundary normalization is exact rather than merely Euler-Lagrange system is linear in `u`, and both operations right-multiply the solution by a mixing matrix `T`, so `du(ψ, u·T) = du(ψ, u)·T`. -Returns `false` without allocating when there is nothing to work from — no `mats`, no stored -steps, or a solution held in a basis the Euler-Lagrange kernel does not apply to (the -Riccati path, which stores Riccati matrices). +Returns `false` without allocating when there is nothing to work from: no `mats` or no stored steps. """ function materialize_derivative_stores!( odet::OdeState, @@ -94,7 +92,7 @@ function materialize_derivative_stores!( intr::ModeSpace ) odet.du_store_populated && return true - (isnothing(mats) || odet.step == 0 || isempty(odet.u_store) || !odet.u_store_el_basis) && return false + (isnothing(mats) || odet.step == 0 || isempty(odet.u_store)) && return false kinetic = mats.kinetic !== nothing nstep = min(odet.step, size(odet.u_store, 4)) diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 2beaa59163..b8d7fabe64 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -75,7 +75,10 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: resp = PlasmaResponse(; ffs, m_modes, n_modes, compute_singular_coupling, compute_torque_response, odet_from_gal=solution !== nothing && solution.basis === :gal_native) - if ForceFreeStates.require(ffs, :free_boundary, "plasma response calculation") && + # A Riccati result carries ξ profiles, but the response operators are not validated on them yet. + riccati = ffs.integrator === :riccati + riccati && @warn "Skipping plasma response calculation: a Riccati result is not accepted yet; use the Forward integrator" + if !riccati && ForceFreeStates.require(ffs, :free_boundary, "plasma response calculation") && ForceFreeStates.require_solution(ffs, "plasma response calculation") build_response_operators!(resp; verbose) if compute_singular_coupling diff --git a/test/runtests_analysis_plots.jl b/test/runtests_analysis_plots.jl index 3ad1a020f4..8b3bd4bb1c 100644 --- a/test/runtests_analysis_plots.jl +++ b/test/runtests_analysis_plots.jl @@ -140,17 +140,13 @@ using TOML end end - @testset "Riccati run offers Δ′ but no solution profiles" begin + @testset "Riccati run offers Δ′ and solution profiles" begin mktempdir() do dir ret, h5 = _run_fixture(dir, "regression_solovev_ideal_example"; edit=d -> (d["ForceFreeStates"]["integrator"] = "Riccati"; d["Riccati"] = delete!(pop!(d, "Forward"), "renorm_threshold"))) _check_sources(ret.ffs, h5) - @test :delta_prime in A.capabilities(ret.ffs) && :solution_profiles ∉ A.capabilities(ret.ffs) - @test_throws A.REASONS[:solution_profiles] A.ForceFreeStates.plot_mode_displacement(ret.ffs) - @test occursin("✗ plot_mode_displacement", repr(MIME"text/plain"(), available_plots(ret.ffs))) - # The summary leaves out the ξ panel rather than failing, keeping the other four. - caps = A.capabilities(ret.ffs) - @test count(((f, _),) -> A._can(f, caps), A.ForceFreeStates._ffs_panels(ret.ffs)) == 4 + @test :delta_prime in A.capabilities(ret.ffs) && :solution_profiles in A.capabilities(ret.ffs) + @test A.ForceFreeStates.plot_mode_displacement(ret.ffs) isa Figure @test A.ForceFreeStates.plot_ffs_summary(ret.ffs) isa Figure # The Δ′ family draws any part of its complex entries and refuses others. @test A.ForceFreeStates.plot_delta_prime(ret.ffs; part=:abs) isa Figure diff --git a/test/runtests_eulerlagrange.jl b/test/runtests_eulerlagrange.jl index 4cbc5cf0cd..75f0edc93d 100644 --- a/test/runtests_eulerlagrange.jl +++ b/test/runtests_eulerlagrange.jl @@ -455,7 +455,6 @@ end @test size(odet.du_store) == (numpert_total, numpert_total, 0) @test size(odet.xi_s_store) == (numpert_total, numpert_total, 0) @test odet.du_store_populated == false - @test odet.u_store_el_basis == true @test length(odet.psi_store) == numsteps_init @test length(odet.q_store) == numsteps_init @test size(odet.ca_r) == (numpert_total, numpert_total, 2, msing) @@ -728,15 +727,6 @@ end @test isapprox(odet_t.xi_s_store[:, :, istep], odet.xi_s_store[:, :, istep] * T; rtol=1e-10) end end - - @testset "refuses a solution outside the Euler-Lagrange basis" begin - odet.du_store_populated = false - odet.du_store = Array{ComplexF64}(undef, intr.numpert_total, intr.numpert_total, 0) - odet.u_store_el_basis = false - @test !FFS.materialize_derivative_stores!(odet, equil, mats, intr) - @test isempty(odet.du_store) - @test !odet.du_store_populated - end end @testset "resonant block Frobenius exponents" begin diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 2eb96ecc9e..9a11dbcd1b 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -249,30 +249,16 @@ end # physically meaningful. BVP Δ' regression is concentrated on the DIIID-like # fixture below (intrinsically stable, well-conditioned BVP Δ'). - @testset "Riccati leaves its u_store in the Riccati basis" begin - # The stored Riccati states are (S, I), not the Euler-Lagrange axis basis. Downstream ξ consumers - # must therefore be fed by the forward integrator; this test pins that contract. - function run_and_capture(integrator) + @testset "both ODE integrators leave solution profiles" begin + # Either store materializes into dΞ_ψ/dψ and Ξ_s, which is what PerturbedEquilibrium consumes. + for integrator in ("Forward", "Riccati") ctrl, intr, equil, metric, mats = _prepared_solovev(integrator) odet = first(GeneralizedPerturbedEquilibrium.ForceFreeStates.eulerlagrange_integration(ctrl, equil, mats, intr)) - # Derivatives are recomputed on demand; materialize so the stores can be compared. - GeneralizedPerturbedEquilibrium.ForceFreeStates.materialize_derivative_stores!(odet, equil, mats, intr) - return odet + @test GeneralizedPerturbedEquilibrium.ForceFreeStates.materialize_derivative_stores!(odet, equil, mats, intr) + @test odet.du_store_populated + @test size(odet.du_store) == size(odet.xi_s_store) == (intr.numpert_total, intr.numpert_total, odet.step) + @test all(isfinite, odet.du_store) && all(isfinite, odet.xi_s_store) end - - odet_fwd = run_and_capture("Forward") - odet_ric = run_and_capture("Riccati") - - # The forward path returns dense ξ in the axis basis, ready for PerturbedEquilibrium. - @test odet_fwd.u_store_el_basis - @test odet_fwd.du_store_populated - - # The Riccati solution is in the Riccati basis, so the derivative stores cannot be - # materialized from it and stay empty rather than holding unusable values. - @test !odet_ric.u_store_el_basis - @test !odet_ric.du_store_populated - @test isempty(odet_ric.du_store) - @test isempty(odet_ric.xi_s_store) end # Production DIII-D energies and Δ′ are tracked by the diiid_n1_riccati harness cases. diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index e72c492ad6..4cf9ffbfc7 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -95,7 +95,7 @@ include("display_check.jl") end end - @testset "riccati run publishes Δ′ and diagnostics but no ξ solution" begin + @testset "riccati run publishes Δ′, diagnostics and a ξ solution" begin mktempdir() do dir _stage_deck(dir, template; ffs_overrides=Dict{String,Any}("integrator" => "Riccati")) ret = GeneralizedPerturbedEquilibrium.main([dir]) @@ -103,10 +103,9 @@ include("display_check.jl") ffs = ret.ffs riccati_result[] = ffs @test ffs.integrator === :riccati - # Chunk-endpoint Riccati states are not a ξ solution; only the raw state is carried. - @test ffs.solution === nothing + @test ffs.solution !== nothing && ffs.solution.basis === :el_axis + @test ffs.solution.step == length(ffs.solution.psi_store) == size(ffs.solution.du_store, 3) @test ffs.diagnostics !== nothing - @test !ffs.diagnostics.u_store_el_basis @test ffs.closure === :ideal @test iszero(ffs.bpen) @@ -131,7 +130,7 @@ include("display_check.jl") @test !(@test_logs (:warn,) FFS.require(ffs, :galerkin, "a calculation")) # `require_solution` is the ξ-specific presence gate. - @test !(@test_logs (:warn,) FFS.require_solution(ffs, "a calculation")) + @test @test_logs FFS.require_solution(ffs, "a calculation") end end @@ -154,11 +153,11 @@ include("display_check.jl") @test ret.pe !== nothing @test isempty(ret.pe.response.permeability) @test isempty(ret.pe.response.C_delta_prime) - @test ret.ffs.free_boundary !== nothing && ret.ffs.solution === nothing + @test ret.ffs.free_boundary !== nothing && ret.ffs.solution !== nothing @test ret.resp.compute_singular_coupling for result in (ret.resp, ret.pe) plain = _check_display(result) - @test occursin("needs stored ξ profiles", plain) + @test occursin("a Riccati result is not accepted yet", plain) @test !occursin("needs a free-boundary result", plain) @test !occursin("singular coupling off", plain) @test !occursin(" 0 J", plain) diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index c6e9c7ca41..ec60ed0196 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -104,12 +104,35 @@ end @test isapprox(real(et_far[1]), real(et_forward[1]); rtol=5e-3) end - @testset "stored states" begin - # Every solver step of every chunk is stored, reduced to (S, I), in increasing ψ. + @testset "stored solution" begin + # Every solver step of every chunk is stored, in increasing ψ, ending at the edge state. @test odet_ric.step == length(odet_ric.psi_store) == size(odet_ric.u_store, 4) @test all(diff(odet_ric.psi_store) .> 0) - @test all(odet_ric.u_store[:, :, 2, k] ≈ I(N) for k in 1:odet_ric.step) @test odet_ric.u_store[:, :, :, end] ≈ odet_ric.u + + # Each stored column is a solution: integrated directly from one stored node it lands on the next. + psi = odet_ric.psi_store + for k in (1, odet_ric.step ÷ 4, odet_ric.step ÷ 2, odet_ric.step - 1) + any(s -> psi[k] < s.psifac < psi[k+1], intr_ric.sing) && continue + params = (ctrl, equil, mats, intr_ric, FFS.OdeState(N, 1, 1, 0), FFS.IntegrationChunk(psi[k], psi[k+1], false, 0, 1)) + direct = FFS.solve_el(FFS.ODEProblem(FFS.sing_der!, odet_ric.u_store[:, :, :, k], (psi[k], psi[k+1]), params), + ctrl.algorithm.eulerlagrange_tolerance).u[end] + @test isapprox(direct, odet_ric.u_store[:, :, :, k+1]; rtol=1e-5) + end + + # Across the surfaces they are the solutions Forward stores: scaled to a unit edge displacement, the + # conjugate momenta agree on each side of every surface. (ξ itself differs there by Forward's crossing + # condition, which leaves a big-solution term next to each surface.) + function edge_scaled_momentum(integrator) + ctrl, intr, equil, _, mats = prepared_solovev(; integrator, singfac_min=1e-6) + odet = first(FFS.eulerlagrange_integration(ctrl, equil, mats, intr)) + return odet, intr, [odet.u_store[:, :, 2, k] / odet.u_store[:, :, 1, odet.step] for k in 1:odet.step] + end + ric, intr, momentum_ric = edge_scaled_momentum("Riccati") + fwd, _, momentum_fwd = edge_scaled_momentum("Forward") + shared = [(findfirst(==(p), ric.psi_store), k) for (k, p) in enumerate(fwd.psi_store[1:fwd.step]) if p in ric.psi_store] + @test length(shared) >= 2 * intr.msing + @test maximum(norm(momentum_ric[i] - momentum_fwd[k]) / norm(momentum_fwd[k]) for (i, k) in shared) < 1e-2 end # Note: a Solovev per-surface Δ' regression testset previously lived here, @@ -130,8 +153,8 @@ end ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example", nchunks) odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv - delta_prime = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.bases, riccati.axis_state; wv, psio=equil.psio) - return delta_prime.matrix, riccati.chunks + result = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) + return result.matrix, riccati.chunks end dp_auto, chunks_auto = delta_prime(0) dp_few, chunks_few = delta_prime(1) @@ -144,18 +167,19 @@ end # The chunks, their propagators and the Δ′ system follow the edge to the peak. ctrl, intr, equil, _, mats = prepared_solovev(; over=Dict{String,Any}("truncate_at_dW_peak" => true)) odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) - (; propagators, chunks, bases, axis_state) = riccati + (; propagators, chunks) = riccati + axis_state = riccati.columns.axis_state @test intr.psilim == odet.psi_store[end] == chunks[end].psi_end @test length(propagators) == length(chunks) && count(c -> c.needs_crossing, chunks) == intr.msing @test odet.u_store[:, :, :, end] ≈ odet.u free = FFS.free_run(odet, ctrl, equil, mats, intr) @test isfinite(free.et[1]) # The Δ′ system reproduces the plasma response of the axis-to-edge products, and says so when it does not. - delta_prime = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; + delta_prime = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=free.wp, psio=equil.psio) @test size(delta_prime.matrix) == (intr.msing, intr.msing) && all(isfinite, delta_prime.matrix) @test size(delta_prime.coil) == (2 * intr.msing, intr.numpert_total) - @test_logs (:warn, r"differs from the axis-to-edge one") FFS.compute_delta_prime_matrix(intr, propagators, chunks, bases, axis_state; + @test_logs (:warn, r"differs from the axis-to-edge one") FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=1.01 .* free.wp, psio=equil.psio) end diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 8d54f7b761..6fa6f17397 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -75,7 +75,7 @@ include("display_check.jl") @test api.integrator === :riccati @test api.control.algorithm.nchunks == 40 - @test api.solution === nothing + @test api.solution !== nothing && api.solution.basis === :el_axis @test api.delta_prime !== nothing msing = length(api.surfaces) @test size(api.delta_prime.matrix) == (msing, msing) From 341814b43ec50172e7c0dbaf6612d50c5b69e366 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 14:36:51 +0100 Subject: [PATCH 06/27] ForceFreeStates - FEATURE! - Share one outer solution basis between Riccati and Galerkin matches --- docs/development/hdf5-conventions.md | 2 +- docs/src/api.md | 2 +- docs/src/galerkin.md | 3 +- docs/src/stability.md | 3 +- src/Analysis/ForceFreeStates.jl | 5 +- src/Analysis/Registry.jl | 2 +- src/Display.jl | 2 +- src/ForceFreeStates/ForceFreeStates.jl | 1 + .../Galerkin/GalerkinSolution.jl | 4 +- src/ForceFreeStates/Galerkin/GalerkinSolve.jl | 45 +++---- .../Galerkin/GalerkinStructs.jl | 27 ---- src/ForceFreeStates/Matching/DeltaPrime.jl | 28 +++++ src/ForceFreeStates/Matching/MatchProblem.jl | 27 ++-- src/ForceFreeStates/Output.jl | 23 ++-- src/ForceFreeStates/Result.jl | 37 +++--- src/ForceFreeStates/Riccati/Crossings.jl | 10 +- src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 40 +++--- src/ForceFreeStates/Riccati/Driver.jl | 7 +- src/ForceFreeStates/Riccati/OuterBasis.jl | 115 ++++++++++++++++++ src/ForceFreeStates/Run.jl | 11 +- .../PerturbedEquilibrium.jl | 4 +- .../PerturbedEquilibriumStructs.jl | 6 +- src/PerturbedEquilibrium/SingularCoupling.jl | 16 +-- src/Utilities/HDF5Schema.jl | 12 ++ test/runtests_parallel_integration.jl | 4 +- test/runtests_result_struct.jl | 14 ++- test/runtests_riccati.jl | 35 +++++- test/runtests_solve_api.jl | 11 +- 28 files changed, 334 insertions(+), 162 deletions(-) create mode 100644 src/ForceFreeStates/Riccati/OuterBasis.jl diff --git a/docs/development/hdf5-conventions.md b/docs/development/hdf5-conventions.md index 403fb7ffc5..e562d9e72c 100644 --- a/docs/development/hdf5-conventions.md +++ b/docs/development/hdf5-conventions.md @@ -40,7 +40,7 @@ Top level (11 groups): | `Info/` | Run metadata: `git_version`, mode-number ranges (`mpert`, `mlow`, …, `mn_index`), `psilim`, `qlim`, `Runtimes/` (per-stage wall-clock seconds) | | `Input/` | Rerun snapshot: `gpec_toml_raw`, `RawInputs/{Equilibrium, ForcingTerms, Coils/, Kinetic, Wall, ErrorFields}` | | `Equilibrium/` | Scalars (`beta_N`, `q_axis`, `q_95`, `I_p`, …) plus `Profiles/` (1-D on `psi`: 2piF, mu0p, dVdpsi, q) and `Geometry/` (2-D on `psi`×`theta`: rcoords, offset, nu, jac) | -| `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (closed ξ profiles in the shared layout, the gal surface list, `gal_basis_output`-gated `Basis/`), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | +| `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (the gal surface list, `gal_basis_output`-gated `Basis/`), `Solutions/Match/` (closed ξ profiles of a `[Match]` in the shared layout, on the grid of the Galerkin or Riccati outer solutions), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | | `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_matrix`/`Delta_prime_raw`/`Delta_coil`/`pest3_A`/`pest3_B`/`pest3_Gamma` (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | | `PerturbedEquilibrium/` | `ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | diff --git a/docs/src/api.md b/docs/src/api.md index 4cb8938ddc..916f34e1fb 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -143,7 +143,7 @@ bpens = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).bp ``` A scalar applies to every surface and a vector gives one value per entry of `ffs.surfaces`, core to edge. -The problem needs a Δ′ payload with coil-response columns, so it accepts Galerkin (`rpec_flag=true`) and Riccati (`vac_flag=true`) results; a Riccati-fed match fills `bpen` and the resonant data but keeps `solution === nothing`. +The problem needs a Δ′ payload with coil-response columns, so it accepts Galerkin (`rpec_flag=true`) and Riccati (`vac_flag=true`) results. Both publish the outer solutions the match combines in `ffs.basis`; the composite inner-region profiles need Galerkin's `cut_solution=true`, and a Riccati basis always carries its cut solution. `GGJModel()` is the closure-capable model; `SLAYERModel()` is slab-only and drives the tearing solve instead. ## Tearing stability diff --git a/docs/src/galerkin.md b/docs/src/galerkin.md index b3e59a745b..56c274df54 100644 --- a/docs/src/galerkin.md +++ b/docs/src/galerkin.md @@ -38,7 +38,8 @@ A `[Match]` section matches the inner layer to its Δ′ and gives a driven ``\x | `SingularSurfaces/Delta_prime_matrix` | the Δ′ matrix in the PEST-3 convention, on the same path as the Riccati result, so downstream stages never branch on which formalism ran | | `SingularSurfaces/Delta_prime_raw`, `Delta_coil` | the side-major matching matrix and the coil-response columns (`rpec_flag = true`) | | `SingularSurfaces/pest3_A`, `pest3_B`, `pest3_Gamma` | the PEST-3 interchange and mixed blocks ``A'``, ``B'``, ``\Gamma'`` | -| `ForceFreeStates/Solutions/GalerkinIntegration/` | the closed ``\xi`` profiles on the Galerkin grid, the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | +| `ForceFreeStates/Solutions/GalerkinIntegration/` | the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | +| `ForceFreeStates/Solutions/Match/` | with a `[Match]` section, the closed ``\xi`` profiles on the Galerkin grid | Nothing is written under `ForceFreeStates/FreeBoundaryStability/`. diff --git a/docs/src/stability.md b/docs/src/stability.md index be8eaebff7..af7a98d45e 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -138,6 +138,7 @@ The perpendicular diffusivities that set the layer widths are described with the - The Riccati integrator splits the domain into chunks whose count is derived from the number of singular surfaces (`[Riccati] nchunks` overrides the target, `0` is automatic); every chunk integrates from its own start (the identity, or the asymptotic solutions of [Glasser and Kolemen (2018)](citations.md#Tearing) for the two chunks next to a rational surface), so the result is independent of the thread count. - The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from products of the same propagators, matched midway between the surfaces. +- With `vac_flag = true` the solutions of that boundary-value problem are rebuilt on the stored grid from the same propagators and published as `ffs.basis`, the outer solutions a `[Match]` combines. - Both integrators use the adaptive ninth-order `Vern9` solver at `eulerlagrange_tolerance`; the Riccati integrator reduces its state to ``(S, I)`` after every chunk, and Forward applies Gaussian reduction whenever a solution norm grows past `renorm_threshold`. - The two integrators cross a rational surface differently. Riccati carries the nonresonant asymptotic coefficients across it (Glasser and Kolemen (2018), Eq. 36), so its energies do not depend on `singfac_min`. Forward takes a trapezoidal step between the two sides, with an error of first order in `singfac_min`, so its energies converge to Riccati's as `singfac_min` shrinks. @@ -149,5 +150,5 @@ The Galerkin solver's functions are documented on the [Galerkin Solver](galerkin ```@autodocs Modules = [GeneralizedPerturbedEquilibrium.ForceFreeStates] -Pages = ["ForceFreeStates.jl", "CoreTypes.jl", "Surfaces/Types.jl", "Riccati/Types.jl", "Matching/DeltaPrime.jl", "Result.jl", "Surfaces/ResistEval.jl", "Matching/ResonantMatch.jl", "Matching/MatchProblem.jl", "EulerLagrange.jl", "Surfaces/Finding.jl", "Surfaces/Asymptotics.jl", "Fourfit.jl", "Kinetic.jl", "FixedKineticMatrices.jl", "FixedBoundaryStability.jl", "Utils.jl", "Free.jl", "Riccati/Propagators.jl", "Riccati/Crossings.jl", "Riccati/DeltaPrimeBVP.jl", "Riccati/Driver.jl"] +Pages = ["ForceFreeStates.jl", "CoreTypes.jl", "Surfaces/Types.jl", "Riccati/Types.jl", "Matching/DeltaPrime.jl", "Result.jl", "Surfaces/ResistEval.jl", "Matching/ResonantMatch.jl", "Matching/MatchProblem.jl", "EulerLagrange.jl", "Surfaces/Finding.jl", "Surfaces/Asymptotics.jl", "Fourfit.jl", "Kinetic.jl", "FixedKineticMatrices.jl", "FixedBoundaryStability.jl", "Utils.jl", "Free.jl", "Riccati/Propagators.jl", "Riccati/Crossings.jl", "Riccati/DeltaPrimeBVP.jl", "Riccati/OuterBasis.jl", "Riccati/Driver.jl"] ``` diff --git a/src/Analysis/ForceFreeStates.jl b/src/Analysis/ForceFreeStates.jl index 3ced9a384c..afcd7bf243 100644 --- a/src/Analysis/ForceFreeStates.jl +++ b/src/Analysis/ForceFreeStates.jl @@ -17,6 +17,7 @@ const Source = Union{AbstractString,ForceFreeStatesResult} const _FWD = "ForceFreeStates/Solutions/ForwardIntegration" const _GAL = "ForceFreeStates/Solutions/GalerkinIntegration" +const _MATCH = "ForceFreeStates/Solutions/Match" const _FBS = "ForceFreeStates/FreeBoundaryStability" # Least-stable total energy, or `nothing` without free-boundary energies. @@ -39,8 +40,8 @@ end function _mode_displacement_data(h5path::AbstractString) h5open(h5path, "r") do fid - # Forward integration stores its profiles in ForwardIntegration, a matched Galerkin solve in GalerkinIntegration. - group = isempty(fid["$_FWD/xi_psi"]) ? _GAL : _FWD + # An ODE integrator stores its profiles in ForwardIntegration, a matched solution in Match. + group = isempty(fid["$_FWD/xi_psi"]) ? _MATCH : _FWD (; mlow=read(fid["Info/mlow"]), psi=read(fid["$group/psi"]), xi=read(fid["$group/xi_psi"])[:, 1, :], dW=_first_energy(read(fid["$_FBS/eigenmode_energies"]))) end diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index 159531f0d1..747d32e622 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -132,7 +132,7 @@ end const _H5_CAPABILITIES = ( :equilibrium => "Equilibrium/Profiles/psi", :singular_surfaces => "SingularSurfaces/rational_psi", - :solution_profiles => ("ForceFreeStates/Solutions/ForwardIntegration/xi_psi", "ForceFreeStates/Solutions/GalerkinIntegration/xi_psi"), + :solution_profiles => ("ForceFreeStates/Solutions/ForwardIntegration/xi_psi", "ForceFreeStates/Solutions/Match/xi_psi"), :fixed_boundary_criterion => "ForceFreeStates/Solutions/ForwardIntegration/crit", :edge_scan => "ForceFreeStates/EdgeScan/psi", :free_boundary => "ForceFreeStates/FreeBoundaryStability/eigenmode_energies", diff --git a/src/Display.jl b/src/Display.jl index f2bb509569..bd09cdfa08 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -276,7 +276,7 @@ function Base.show(io::IO, ::MIME"text/plain", r::PlasmaResponse) _row(io, "Coupling", isempty(r.C_resonant_area_weighted_field) ? _missing_coupling_note(r) : "C $(_shape(r.C_resonant_area_weighted_field))") isempty(r.dominant_singular_values) || _row(io, "Dominant σ", _list(_fmt.(r.dominant_singular_values); max=3)) _row(io, "Torque resp.", isempty(r.T_xe) ? "not computed" : "T_xe $(_shape(r.T_xe))") - r.odet_from_gal && _row(io, "Basis", "Galerkin-native solution") + r.unit_edge_basis && _row(io, "Basis", "matched solution, unit edge displacement") _plots_row(io, r) return nothing end diff --git a/src/ForceFreeStates/ForceFreeStates.jl b/src/ForceFreeStates/ForceFreeStates.jl index f1374dae3d..4f4e23356e 100644 --- a/src/ForceFreeStates/ForceFreeStates.jl +++ b/src/ForceFreeStates/ForceFreeStates.jl @@ -52,6 +52,7 @@ include("Free.jl") include("Riccati/Propagators.jl") include("Riccati/Crossings.jl") include("Riccati/DeltaPrimeBVP.jl") +include("Riccati/OuterBasis.jl") include("Riccati/Driver.jl") # RDCON outer-region singular Galerkin Δ′ solver (gal_solve port) diff --git a/src/ForceFreeStates/Galerkin/GalerkinSolution.jl b/src/ForceFreeStates/Galerkin/GalerkinSolution.jl index bed9c57780..4c2ac0a6b6 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinSolution.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinSolution.jl @@ -143,7 +143,7 @@ function gal_get_solution(ws::GalWorkspace, asymps::Vector{GalSingAsymp}, sings: end """ - gal_output_solution(ws, asymps, sings, intr, profiles, psihigh; delta=nothing) -> GalerkinSolution + gal_output_solution(ws, asymps, sings, intr, profiles, psihigh; delta=nothing) -> OuterSolutionBasis Build the gal-native packed radial grid (inner→edge; `GAL_INTERP_NP_RES` points per resonant/extension cell, `GAL_INTERP_NP` elsewhere, plus the edge point ψ=psihigh) and evaluate ξ AND the analytic ξ′ over @@ -220,5 +220,5 @@ function gal_output_solution(ws::GalWorkspace, asymps::Vector{GalSingAsymp}, sin end end - return GalerkinSolution(psi, q, issing, xi, xi_deriv, xi_cut, cut_range) + return OuterSolutionBasis(psi, q, issing, xi, xi_deriv, xi_cut, cut_range) end diff --git a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl index 5d4f6d2df5..27401d16ba 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl @@ -43,17 +43,19 @@ end Empty `GalerkinResult` for a domain with no resonant surfaces. """ function empty_galerkin_result() - return GalerkinResult(0, Float64[], Float64[], Int[], Int[], Float64[], ComplexF64[], nothing, "none") + return GalerkinResult(0, Float64[], Float64[], Int[], Int[], Float64[], ComplexF64[], "none") end """ galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines, - intr::ForceFreeStatesInternal; wv=nothing, cut_solution=false) -> (GalerkinResult, Union{Nothing,DeltaPrimeData}) + intr::ForceFreeStatesInternal; wv=nothing, cut_solution=false) + -> (GalerkinResult, Union{Nothing,DeltaPrimeData}, Union{Nothing,OuterSolutionBasis}) Compute the outer-region Δ′ matching matrix by the singular Galerkin method. Port of `gal_solve` (gal.f). Single toroidal mode only (`intr.npert == 1`). Returns the solver internals as a -`GalerkinResult` alongside the Δ′ payload as the shared [`DeltaPrimeData`](@ref); if there are no -resonant surfaces in the domain it returns an empty result and `nothing`. +`GalerkinResult`, the Δ′ payload as the shared [`DeltaPrimeData`](@ref) and the solutions on the Galerkin grid +as an [`OuterSolutionBasis`](@ref); if there are no resonant surfaces in the domain it returns an empty result +and two `nothing`s. `wv` is the vacuum energy matrix from `free_run`, which supplies the free-boundary edge term `wv_edge = wv · psio²`; pass `nothing` for a fixed-boundary edge. `cut_solution` also keeps the @@ -72,7 +74,7 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines msing = length(sings) if msing == 0 intr.verbose && @info "galerkin_solve: no resonant surfaces in domain; skipping Δ′ solve" - return empty_galerkin_result(), nothing + return empty_galerkin_result(), nothing, nothing end intr.verbose && @info "Starting outer-region Galerkin Δ′ solve (msing=$msing, automatic factorization)" @@ -172,14 +174,14 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines # Reconstruct ξ(ψ) AND analytic ξ′(ψ) on the gal-native grid (gal_output_solution); the cut # solution only when a later match needs the composite inner profiles. intr.verbose && @info "Reconstructing outer-region ξ and analytic ξ′ on the gal grid" - solution = gal_output_solution(ws, asymps, sings, intr, equil.profiles, psihigh; + basis = gal_output_solution(ws, asymps, sings, intr, equil.profiles, psihigh; delta=(cut_solution ? delta : nothing)) sing_psi = [s.psifac for s in sings] sing_q = [s.q for s in sings] sing_m = [s.m[1] for s in sings] sing_n = [s.n[1] for s in sings] - return GalerkinResult(msing, sing_psi, sing_q, sing_m, sing_n, di, alpha, solution, ws.solver), dp + return GalerkinResult(msing, sing_psi, sing_q, sing_m, sing_n, di, alpha, ws.solver), dp, basis end """ @@ -229,14 +231,14 @@ function gal_pest3_blocks(delta::Matrix{ComplexF64}, msing::Int) end """ - write_galerkin!(out_h5, result::GalerkinResult; basis_output=false) + write_galerkin!(out_h5, result::GalerkinResult, basis; basis_output=false) Write the Galerkin surface list (a subset of `SingularSurfaces/` when the domain or the m-band excludes rationals) under `ForceFreeStates/Solutions/GalerkinIntegration/`. The Δ′/PEST-3 matrices and closed ξ -profiles are written by the driver writer, not here. With `basis_output`, the raw per-interval -outer-region basis functions (solver internals) are written under `Basis/`. +profiles are written by the driver writer, not here. With `basis_output`, the solve's `basis` +(an [`OuterSolutionBasis`](@ref) or `nothing`) is written under `Basis/`. """ -function write_galerkin!(out_h5, result::GalerkinResult; basis_output::Bool=false) +function write_galerkin!(out_h5, result::GalerkinResult, basis::Union{Nothing,OuterSolutionBasis}; basis_output::Bool=false) gal = "ForceFreeStates/Solutions/GalerkinIntegration" out_h5["$gal/rational_count"] = result.msing out_h5["$gal/solver"] = result.solver @@ -250,8 +252,8 @@ function write_galerkin!(out_h5, result::GalerkinResult; basis_output::Bool=fals out_h5["$gal/rational_n"] = result.sing_n out_h5["$gal/D_I"] = result.di out_h5["$gal/alpha"] = result.alpha - if basis_output && result.solution !== nothing - sol = result.solution + if basis_output && basis !== nothing + sol = basis out_h5["$gal/Basis/psi"] = sol.psi out_h5["$gal/Basis/is_rational"] = collect(sol.issing) out_h5["$gal/Basis/xi_psi"] = permutedims(sol.xi, (1, 3, 2)) @@ -268,23 +270,6 @@ const GALERKIN_H5_ANNOTATIONS = [ "ForceFreeStates/Solutions/GalerkinIntegration/rational_count" => (; long_name="number of rational (singular) surfaces in the Galerkin solve"), "ForceFreeStates/Solutions/GalerkinIntegration/solver" => (; long_name="banded solver used for the Galerkin system: cholesky, LU, or none when no rational surfaces were present"), - "ForceFreeStates/Solutions/GalerkinIntegration/psi" => (; long_name="normalized poloidal flux ψ_N grid of the closed Galerkin solution", scale="psi_gal"), - "ForceFreeStates/Solutions/GalerkinIntegration/q" => - (; long_name="safety factor q on the Galerkin solution grid", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), - "ForceFreeStates/Solutions/GalerkinIntegration/xi_psi" => - (; - long_name="closed axis-to-edge ξ^ψ profiles (ideal or inner-layer closure; identity-at-edge basis)", - dims=("mode", "solution", "psi"), - attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",) - ), - "ForceFreeStates/Solutions/GalerkinIntegration/dxi_psidpsi" => - (; long_name="analytic ψ_N derivative of the closed ξ^ψ profiles", dims=("mode", "solution", "psi"), attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), - "ForceFreeStates/Solutions/GalerkinIntegration/xi_s" => - (; - long_name="surface displacement ξ_s from the outer ideal-MHD relation", - dims=("mode", "solution", "psi"), - attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",) - ), "ForceFreeStates/Solutions/GalerkinIntegration/Basis/psi" => (; long_name="normalized poloidal flux ψ_N grid of the raw Galerkin basis", scale="psi_gal_basis"), "ForceFreeStates/Solutions/GalerkinIntegration/Basis/is_rational" => (; long_name="flag: grid node lies on a rational surface", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/GalerkinIntegration/Basis/psi",)), diff --git a/src/ForceFreeStates/Galerkin/GalerkinStructs.jl b/src/ForceFreeStates/Galerkin/GalerkinStructs.jl index e0cb88afc9..6cf5b91838 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinStructs.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinStructs.jl @@ -110,30 +110,6 @@ struct GalSingAsymp left::SingAsymptotics end -""" - GalerkinSolution - -Reconstructed outer-region radial solution on the gal-native grid (ξ and analytic ξ′ consumed by -PerturbedEquilibrium). Populated by `gal_output_solution` (GalerkinSolution.jl). - - - `psi::Vector{Float64}`, `q::Vector{Float64}` — radial grid (inner→edge) and its safety factor. - - `issing::Vector{Bool}` — grid points sitting on a singular surface (skipped; left zero). - - `xi::Array{ComplexF64,3}`, `xi_deriv::Array{ComplexF64,3}` — `(mpert, ngrid, nsol)` ξ and dξ/dψ. - - `xi_cut::Array{ComplexF64,3}` — `(mpert, ngrid, nsol)` ξ with the leading-order resonant content removed, - the background the inner-layer solution is added to for the composite solution. `(0,0,0)` unless `cut_solution`. - - `cut_range::Matrix{Float64}` — `(msing, 2)` ψ bounds of the resonant + extension cells around each surface; - the composite inner solution is only meaningful inside them. `(0,0)` unless `cut_solution`. -""" -struct GalerkinSolution - psi::Vector{Float64} - q::Vector{Float64} - issing::Vector{Bool} - xi::Array{ComplexF64,3} - xi_deriv::Array{ComplexF64,3} - xi_cut::Array{ComplexF64,3} - cut_range::Matrix{Float64} -end - """ GalerkinResult @@ -147,8 +123,6 @@ Solver internals and FEM diagnostics of the outer-region Galerkin solve. The Δ - `sing_psi, sing_q::Vector{Float64}`, `sing_m, sing_n::Vector{Int}` — per-surface identifiers, core→edge, in the order the Δ′ matrices are indexed. - `di::Vector{Float64}`, `alpha::Vector{ComplexF64}` — Mercier index and exponent per surface. - - `solution::Union{Nothing,GalerkinSolution}` — reconstructed radial ξ(ψ) and analytic ξ′(ψ) on the - gal-native grid; `nothing` if no resonant surfaces. - `solver::String` — factorization actually used: `"cholesky"`, `"LU"`, or `"none"` when no resonant surfaces were present. """ struct GalerkinResult @@ -159,6 +133,5 @@ struct GalerkinResult sing_n::Vector{Int} di::Vector{Float64} alpha::Vector{ComplexF64} - solution::Union{Nothing,GalerkinSolution} solver::String end diff --git a/src/ForceFreeStates/Matching/DeltaPrime.jl b/src/ForceFreeStates/Matching/DeltaPrime.jl index 7358dceee5..1295d6a0c7 100644 --- a/src/ForceFreeStates/Matching/DeltaPrime.jl +++ b/src/ForceFreeStates/Matching/DeltaPrime.jl @@ -33,3 +33,31 @@ struct DeltaPrimeData B::Union{Nothing,Matrix{ComplexF64}} Gamma::Union{Nothing,Matrix{ComplexF64}} end + +""" + OuterSolutionBasis + +Outer-region solutions ξ(ψ) that a `MatchProblem` combines into the matched solution, from the Riccati Δ′ +boundary-value problem or the Galerkin solve. Solution `2j-1` (`2j`) carries a unit big solution left (right) of +surface `j` and none elsewhere; the rest, when present, carry no big solution and a unit displacement of one edge +mode each. + +## Fields + + - `psi::Vector{Float64}`, `q::Vector{Float64}` - Radial grid, core to edge, and its safety factor. + - `issing::Vector{Bool}` - Grid points on a singular surface, where the solutions are left zero. + - `xi::Array{ComplexF64,3}`, `xi_deriv::Array{ComplexF64,3}` - `(mpert, ngrid, nsol)` ξ and dξ/dψ. + - `xi_cut::Array{ComplexF64,3}` - `(mpert, ngrid, nsol)` ξ without the leading-order big and small resonant terms + near each surface, the background the inner-layer solution is added to. Empty when not computed. + - `cut_range::Matrix{Float64}` - `(msing, 2)` ψ bounds around each surface outside which `xi_cut` equals `xi`. + Empty when not computed. +""" +struct OuterSolutionBasis + psi::Vector{Float64} + q::Vector{Float64} + issing::Vector{Bool} + xi::Array{ComplexF64,3} + xi_deriv::Array{ComplexF64,3} + xi_cut::Array{ComplexF64,3} + cut_range::Matrix{Float64} +end diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index 522409c46d..b45e6c6a4d 100644 --- a/src/ForceFreeStates/Matching/MatchProblem.jl +++ b/src/ForceFreeStates/Matching/MatchProblem.jl @@ -95,8 +95,7 @@ closure_capable(::InnerLayer.SLAYERModel) = false solve(prob::MatchProblem, model) -> ForceFreeStatesResult Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched` (`:ideal` -with `ideal=true`), `bpen`, the [`MatchResult`](@ref) in `result.match` and, for a Galerkin -solve, the matched ξ. A `:matched` result drops the ideal δW (`wp`, `free_boundary`), so +with `ideal=true`), `bpen`, the [`MatchResult`](@ref) in `result.match` and the matched ξ. A `:matched` result drops the ideal δW (`wp`, `free_boundary`), so PerturbedEquilibrium skips its response rather than mixing ideal and matched physics. """ function CommonSolve.solve(prob::MatchProblem, model::InnerLayer.InnerLayerModel) @@ -117,7 +116,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) equil = ffs.equil chi1 = 2π * equil.psio - gal_sol = ffs.galerkin === nothing ? nothing : ffs.galerkin.solution + basis = ffs.basis if prob.ideal # Ideal limit (rmatch coil%ideal_flag): no inner layer, cout = 0. @@ -193,16 +192,16 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) reconnected_flux = Matrix{ComplexF64}(dp.coil .+ transpose(dp.raw) * cout) - # Matched outer ξ per coil: coil column + Σ cout·plasma columns (needs the Galerkin basis). - if gal_sol === nothing + # Matched outer ξ per coil: coil column + Σ cout·plasma columns. + if basis === nothing xi = Array{ComplexF64,3}(undef, 0, 0, 0) xi_deriv = Array{ComplexF64,3}(undef, 0, 0, 0) empty!(inner_psi) empty!(inner_xi) empty!(inner_b) else - sols = gal_sol.xi # (mpert, ngrid, nsol) - sols_deriv = gal_sol.xi_deriv + sols = basis.xi # (mpert, ngrid, nsol) + sols_deriv = basis.xi_deriv mpert = size(sols, 1) ngrid = size(sols, 2) xi = zeros(ComplexF64, mpert, ngrid, mcoil) @@ -219,7 +218,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) # Composite inner solution: add back the outer background the cut removed (match.f intotsol). if !isempty(inner_psi) - sols_cut = gal_sol.xi_cut + sols_cut = basis.xi_cut if isempty(sols_cut) @warn "MatchProblem: the solve retained no cut solution (set cut_solution=true on Galerkin), " * "so the composite inner-region profiles are skipped; bpen and the matched outer ξ are unaffected" maxlog = 1 @@ -227,9 +226,9 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) empty!(inner_xi) empty!(inner_b) else - cut_range = gal_sol.cut_range - keep = .!gal_sol.issing - psi_keep = gal_sol.psi[keep] + cut_range = basis.cut_range + keep = .!basis.issing + psi_keep = basis.psi[keep] for i in 1:msing m_res = round(Int, nn * sings[i].q) ires = m_res - ffs.mlow + 1 @@ -238,7 +237,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.GGJModel) inside = findall(p -> lo <= p <= hi, inner_psi[i]) if isempty(inside) @warn "MatchProblem: inner layer at ψ=$(round(sings[i].psifac, digits=5)) lies outside the " * - "resonant/extension cells (ψ ∈ [$lo, $hi]); raise gal_dx1/gal_dx2 to overlap the layer" surface = i + "cut window (ψ ∈ [$lo, $hi]); with Galerkin, raise gal_dx1/gal_dx2 to overlap the layer" surface = i continue end length(inside) < length(inner_psi[i]) && @info "MatchProblem: surface $i inner region clipped to the " * @@ -275,10 +274,8 @@ end # Copy of ffs with the match applied; the ideal reference keeps closure :ideal, its zero bpen and δW. function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult, ideal::Bool) - gal = ffs.galerkin # Without a matched ξ, the ideal solution stands only for the ideal reference. - solution = (gal !== nothing && gal.solution !== nothing && !isempty(match.xi)) ? - _matched_gal_profiles(gal, match, ffs.mats, ffs) : (ideal ? ffs.solution : nothing) + solution = isempty(match.xi) ? (ideal ? ffs.solution : nothing) : _matched_profiles(ffs.basis, match, ffs.mats) ideal && return _with(ffs; match=match, solution=solution) # The ideal δW does not describe the matched plasma; PE gates on its absence. return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, diff --git a/src/ForceFreeStates/Output.jl b/src/ForceFreeStates/Output.jl index ba8480148c..a42269525d 100644 --- a/src/ForceFreeStates/Output.jl +++ b/src/ForceFreeStates/Output.jl @@ -24,11 +24,10 @@ function save_to_hdf5( gal_data = result.galerkin diag = result.diagnostics msing = length(result.surfaces) - # Closed ξ profiles are written into the producing formalism's Solutions group with the - # same dataset names and (mode, solution, psi) axis order: ForwardIntegration for the - # axis-basis sweep, GalerkinIntegration for the matched gal solution (its own grid). + # Closed ξ profiles share dataset names and (mode, solution, psi) axis order across the Solutions groups: + # ForwardIntegration for an ODE integrator's columns, Match for a MatchProblem solution (on its basis's grid). xi_solution = (result.solution !== nothing && result.solution.basis === :el_axis) ? result.solution : nothing - gal_solution = (result.solution !== nothing && result.solution.basis === :gal_native) ? result.solution : nothing + matched_solution = (result.solution !== nothing && result.solution.basis === :unit_edge) ? result.solution : nothing # File-level metadata contract (schema_version, Conventions, title, date). @@ -39,16 +38,16 @@ function save_to_hdf5( # Outer-region Galerkin solver outputs (RDCON), if it ran if gal_data !== nothing - write_galerkin!(out_h5, gal_data; basis_output=result.control.algorithm.basis_output) + write_galerkin!(out_h5, gal_data, result.basis; basis_output=result.control.algorithm.basis_output) end - if gal_solution !== nothing - gal = "ForceFreeStates/Solutions/GalerkinIntegration" - out_h5["$gal/psi"] = gal_solution.psi_store - out_h5["$gal/q"] = gal_solution.q_store - out_h5["$gal/xi_psi"] = gal_solution.u_store[:, :, 1, :] - out_h5["$gal/dxi_psidpsi"] = gal_solution.du_store - out_h5["$gal/xi_s"] = gal_solution.xi_s_store + if matched_solution !== nothing + group = "ForceFreeStates/Solutions/Match" + out_h5["$group/psi"] = matched_solution.psi_store + out_h5["$group/q"] = matched_solution.q_store + out_h5["$group/xi_psi"] = matched_solution.u_store[:, :, 1, :] + out_h5["$group/dxi_psidpsi"] = matched_solution.du_store + out_h5["$group/xi_s"] = matched_solution.xi_s_store end save_equilibrium_ingest!(out_h5, equil) diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index 2251f1ee7a..00d80e3811 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -7,9 +7,8 @@ formalism produced the solution. ## Fields - - `basis::Symbol` - Which formalism's basis the profiles are in: `:el_axis` (forward - integrator, axis Euler-Lagrange basis) or `:gal_native` (inner-layer-matched Galerkin - solution, identity-at-edge basis). + - `basis::Symbol` - The basis the profiles are in: `:el_axis` (an ODE integrator's solution columns) or + `:unit_edge` (a `MatchProblem` solution; each column has unit displacement of one edge mode). - `step::Int` - Number of stored radial nodes. - `psi_store::Vector{Float64}` - ψ at each node. - `q_store::Vector{Float64}` - Safety factor at each node. @@ -64,6 +63,8 @@ Every final result records how its basis crosses the rational surfaces, so bpen - `match::Union{Nothing,MatchResult}` - The [`MatchResult`](@ref) of a `MatchProblem` solve; `nothing` otherwise. - `solution::Union{Nothing,SolutionProfiles}` - THE solve's ξ solution; `nothing` when the formalism produced none (Galerkin without a match). + - `basis::Union{Nothing,OuterSolutionBasis}` - The outer-region solutions a `MatchProblem` combines, from a + Galerkin solve or a Riccati solve that computed Δ′ with a vacuum edge; `nothing` otherwise. - `diagnostics::Union{Nothing,OdeState}` - The integrator's raw ODE state (ψ trace, `crit`, edge scan, asymptotic coefficients). Written to HDF5; not a consumable solution. - `wp::Union{Nothing,Matrix{ComplexF64}}` - Fixed-boundary plasma energy matrix `W_p = (U₂·U₁⁻¹)/ψ₀²` at @@ -114,6 +115,7 @@ struct ForceFreeStatesResult{E<:Equilibrium.PlasmaEquilibrium,F<:MatrixSplines,P wp::Union{Nothing,Matrix{ComplexF64}} free_boundary::Union{Nothing,FreeBoundaryResult} delta_prime::Union{Nothing,DeltaPrimeData} + basis::Union{Nothing,OuterSolutionBasis} galerkin::Union{Nothing,GalerkinResult} layer_overlap::L end @@ -143,21 +145,19 @@ function require_solution(result::ForceFreeStatesResult, calc::AbstractString) return false end -# Pack the matched Galerkin solution into `SolutionProfiles`: on-surface `issing` points are dropped, Ξ′ is the -# analytic Galerkin derivative, and Ξ_s = −A⁻¹(B·Ξ′ + C·Ξ) as in `sing_der!`. Grid runs inner→edge. -function _matched_gal_profiles(gal_result::GalerkinResult, m::MatchResult, mats::MatrixSplines, intr::ModeSpace) - sol = gal_result.solution - npert = intr.numpert_total +# Pack the matched solution `m`, on the grid of `basis`, into `SolutionProfiles`: on-surface `issing` points are +# dropped and Ξ_s = −A⁻¹(B·Ξ′ + C·Ξ) as in `sing_der!`. +function _matched_profiles(basis::OuterSolutionBasis, m::MatchResult, mats::MatrixSplines) + npert = size(m.xi, 1) - keep = .!sol.issing - psi_f = sol.psi[keep] - q_f = sol.q[keep] + keep = .!basis.issing + psi_f = basis.psi[keep] + q_f = basis.q[keep] xi_f = m.xi[:, keep, :] # (npert, ngrid_f, mcoil) dxi_f = m.xi_deriv[:, keep, :] ngrid_f = length(psi_f) - # u_store[:, :, 2] stays zero: the conjugate momentum has no consumer on this path and no - # Galerkin counterpart (matches Fortran's unused u2 in the gal branch). + # u_store[:, :, 2] stays zero: the conjugate momentum has no consumer on this path. u_store = zeros(ComplexF64, npert, npert, 2, ngrid_f) du_store = zeros(ComplexF64, npert, npert, ngrid_f) xi_s_store = zeros(ComplexF64, npert, npert, ngrid_f) @@ -171,11 +171,11 @@ function _matched_gal_profiles(gal_result::GalerkinResult, m::MatchResult, mats: @views compute_node_xi_s!(xi_s_store[:, :, ip], ξ′, ξ, mats, psi_f[ip]; hint=hint) end - return SolutionProfiles(:gal_native, ngrid_f, psi_f, q_f, u_store, du_store, xi_s_store) + return SolutionProfiles(:unit_edge, ngrid_f, psi_f, q_f, u_store, du_store, xi_s_store) end """ - build_result(integrator, ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime) + build_result(integrator, ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime, basis) -> ForceFreeStatesResult Assemble the published result once the solve is finished, with the ideal or regular closure (a @@ -183,7 +183,7 @@ Assemble the published result once the solve is finished, with the ideal or regu when the free-boundary stage did not run; everything else is copied or aliased. `odet` is the ODE state (`nothing` for Galerkin), `gal_data` the Galerkin internals (`nothing` otherwise), -and `delta_prime` the Δ′ payload of a Riccati or Galerkin solve (`nothing` otherwise). +and `delta_prime` and `basis` the Δ′ payload and outer solutions of a Riccati or Galerkin solve (`nothing` otherwise). """ function build_result( integrator::Symbol, @@ -195,7 +195,8 @@ function build_result( odet::Union{Nothing,OdeState}, free_energies::Union{Nothing,FreeBoundaryResult}, gal_data::Union{Nothing,GalerkinResult}, - delta_prime::Union{Nothing,DeltaPrimeData} + delta_prime::Union{Nothing,DeltaPrimeData}, + basis::Union{Nothing,OuterSolutionBasis} ) # The ODE integrators' stores need materializing; doing it here keeps # `SolutionProfiles.du_store`/`xi_s_store` populated by construction. @@ -229,6 +230,6 @@ function build_result( intr.psilow, intr.psilim, intr.qlim, intr.q1lim, intr.wall_settings, metric, mats, intr.sing, kinetic, closure, bpen, nothing, - solution, odet, wp, free_energies, delta_prime, gal_data, nothing + solution, odet, wp, free_energies, delta_prime, basis, gal_data, nothing ) end diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index 50ec5e4d76..346100a733 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -4,17 +4,19 @@ asymptotic_bases(chunks, ctrl, equil, mats, intr) -> Dict{Int,NamedTuple} Asymptotic basis `(; left, right)`, each N × 2N × 2, on both sides of every crossed surface, where its crossing -chunk ends. Keyed by the surface's index in `intr.sing`. +chunk ends, with the series they are evaluated from (`left_series`, `right_series`). Keyed by the surface's index +in `intr.sing`. """ function asymptotic_bases(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) - bases = Dict{Int,@NamedTuple{left::Array{ComplexF64,3}, right::Array{ComplexF64,3}}}() + bases = Dict{Int,@NamedTuple{left::Array{ComplexF64,3}, right::Array{ComplexF64,3}, left_series::SingAsymptotics, right_series::SingAsymptotics}}() for chunk in chunks chunk.needs_crossing || continue singp = intr.sing[chunk.ising] dpsi = singp.psifac - chunk.psi_end - bases[chunk.ising] = (; left=sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0), dpsi), - right=sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0), dpsi)) + left_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0) + right_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0) + bases[chunk.ising] = (; left=sing_get_ua(left_series, dpsi), right=sing_get_ua(right_series, dpsi), left_series, right_series) end return bases end diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index d2269e0c07..f18f4271e9 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -4,7 +4,7 @@ const DELTA_PRIME_RESPONSE_MISMATCH = 1e-6 """ - compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> Union{Nothing,DeltaPrimeData} + compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> (delta_prime, coefficients) Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]. @@ -14,15 +14,18 @@ Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix - `intr`: Read for its mode space and singular surfaces. - `propagators`, `chunks`, `axis_state`: From `riccati_eulerlagrange_integration`. - `wv`: Singfac-scaled vacuum response for the edge condition `wp + wv = 0`; `nothing` puts a conducting wall there. - - `wp`: Plasma response from `free_run`. A warning is issued when the BVP's own differs from it by more than - `DELTA_PRIME_RESPONSE_MISMATCH`. + - `wp`: The run's plasma response, used only as a check: a warning is issued when the edge momentum of the Δ_EF + solve differs from it by more than `DELTA_PRIME_RESPONSE_MISMATCH`. - `psio`: Poloidal flux normalization. - `extended_precision`: Solve in `Complex{Double64}`. ### Returns -A [`DeltaPrimeData`](@ref) whose `coil` is Δ_EF (empty without `wv`), or `nothing` when no surface is crossed -or, with a warning, when a surface carries more than one resonant mode. + - `delta_prime`: A [`DeltaPrimeData`](@ref) whose `coil` is Δ_EF (empty without `wv`). + - `coefficients`: The BVP's solution vectors, one column per solution: the 2·msing Δ' solves, side-major, then the + N of Δ_EF. Input of `outer_solution_basis`; `nothing` without `wv`. + +Both are `nothing` when no surface is crossed or, with a warning, when a surface carries more than one resonant mode. """ function compute_delta_prime_matrix( intr::ForceFreeStatesInternal, @@ -34,11 +37,11 @@ function compute_delta_prime_matrix( psio::Float64=0.0, extended_precision::Bool=false ) - intr.msing == 0 && return nothing - _has_unsupported_multi_resonance(intr) && return nothing + intr.msing == 0 && return nothing, nothing + _has_unsupported_multi_resonance(intr) && return nothing, nothing sing, i_crossings, msing = _select_active_surfaces(intr, chunks) - msing == 0 && return nothing + msing == 0 && return nothing, nothing N = intr.numpert_total ipert_all = [1 + sing[j].m[1] - intr.mlow + (sing[j].n[1] - intr.nlow) * intr.mpert for j in 1:msing] @@ -48,11 +51,12 @@ function compute_delta_prime_matrix( # Δ_EF: needs a vacuum edge in the assembled matrix. delta_ef = Matrix{ComplexF64}(undef, 0, 0) + delta_ef_solutions = nothing if wv !== nothing - delta_ef, edge_coefficients = _solve_bvp_delta_ef(M, col_edge, msing, N, ipert_all) + delta_ef, delta_ef_solutions = _solve_bvp_delta_ef(M, col_edge, msing, N, ipert_all) if wp !== nothing # Unit edge displacement, so the edge U₂ is the plasma response times ψ₀². - wp_bvp = uShootR[msing][(N+1):(2N), :] * edge_coefficients ./ psio^2 + wp_bvp = uShootR[msing][(N+1):(2N), :] * delta_ef_solutions[_col_right(msing, N), :] ./ psio^2 mismatch = norm(wp_bvp - wp) / norm(wp) if mismatch > DELTA_PRIME_RESPONSE_MISMATCH @warn "Riccati: the plasma response from the Δ' system differs from the axis-to-edge one by $(@sprintf("%.1e", mismatch)) " * @@ -62,8 +66,9 @@ function compute_delta_prime_matrix( end end # The raw side-major D' (Fortran gal_write_delta layout) feeds `pest3_decompose`; Riccati leaves the blocks unfilled. - delta_prime, delta_prime_raw = _solve_bvp_and_combine_pest3(M, msing, N, ipert_all, extended_precision) - return DeltaPrimeData(delta_prime, delta_prime_raw, delta_ef, nothing, nothing, nothing) + delta_prime, delta_prime_raw, delta_prime_solutions = _solve_bvp_and_combine_pest3(M, msing, N, ipert_all, extended_precision) + coefficients = wv === nothing ? nothing : [delta_prime_solutions delta_ef_solutions] + return DeltaPrimeData(delta_prime, delta_prime_raw, delta_ef, nothing, nothing, nothing), coefficients end # Column index helpers for the BVP matrix. j is the 1-based singular-surface index, @@ -204,7 +209,7 @@ function _assemble_bvp(uShootR::Vector{Matrix{ComplexF64}}, end # Δ_EF (2·msing × N): the small-solution coefficient at each surface side per unit displacement of each edge mode, -# from the BVP with its edge fixed. Also returns the coefficients right of the last surface (2N × N). +# from the BVP with its edge fixed. Also returns the N solution vectors. function _solve_bvp_delta_ef(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int, ipert_all::Vector{Int}) nMat = size(M, 1) bot = (nMat-2msing-N+1):(nMat-2msing) # Eq. (38) bottom rows, carrying the W_V block @@ -221,10 +226,11 @@ function _solve_bvp_delta_ef(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int @views delta_ef[2j-1, :] .= X[row_left, :] @views delta_ef[2j, :] .= X[row_right, :] end - return delta_ef, X[_col_right(msing, N), :] + return delta_ef, X end -# Solve the BVP and apply the PEST3 four-term combination, in Complex{Double64} when `extended_precision`. +# Solve the BVP and apply the PEST3 four-term combination, in Complex{Double64} when `extended_precision`. Returns +# Δ', the raw side-major D' and the 2·msing solution vectors. function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}, extended_precision::Bool) nMat = size(M, 1) s2 = 2 * msing @@ -239,11 +245,13 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, # One solve per surface side, driving that side's big-solution coefficient. dp_raw = zeros(Tc, s2, s2) + solutions = zeros(ComplexF64, nMat, s2) b = zeros(Tc, nMat) for dRow in 1:s2 fill!(b, 0) b[nMat-s2+dRow] = 1 x = use_lu ? (M_lu \ b) : (M_pinv * b) + solutions[:, dRow] .= x for ksing in 1:msing ipert_k = ipert_all[ksing] dp_raw[dRow, 2ksing-1] = x[_col_left(ksing, N)[ipert_k+N]] @@ -256,7 +264,7 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, for i in 1:msing, j in 1:msing deltap[i, j] = dp_raw[2i, 2j] - dp_raw[2i, 2j-1] - dp_raw[2i-1, 2j] + dp_raw[2i-1, 2j-1] end - return ComplexF64.(deltap), ComplexF64.(dp_raw) + return ComplexF64.(deltap), ComplexF64.(dp_raw), solutions end """ diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index fb55eef23b..80a608e6a9 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -5,8 +5,9 @@ Integrate the Euler-Lagrange equations from the axis to `intr.psilim` with paral [Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507; Glasser & Kolemen 2018, Phys. Plasmas 25, 082502]. Returns `odet`, whose stores hold the solution at every stored solver step in columns that are continuous in ψ -and equal (S, I), S = U₁U₂⁻¹, at the edge, and `riccati`, the inputs of `compute_delta_prime_matrix`: -`(; propagators, chunks, columns)`, with `columns` from `_assemble_propagators_serially!`. +and equal (S, I), S = U₁U₂⁻¹, at the edge, and `riccati`, the inputs of `compute_delta_prime_matrix` and +`outer_solution_basis`: `(; propagators, chunks, columns, bases)`, with `columns` from +`_assemble_propagators_serially!` and `bases` from `asymptotic_bases`. """ function riccati_eulerlagrange_integration( ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, @@ -45,7 +46,7 @@ function riccati_eulerlagrange_integration( odet.nzero = evaluate_stability_criterion!(odet, equil.profiles) restore_solution_columns!(odet, propagators, chunks, columns) - return odet, (; propagators, chunks, columns) + return odet, (; propagators, chunks, columns, bases) end # OdeState at the axis start, with empty stores. diff --git a/src/ForceFreeStates/Riccati/OuterBasis.jl b/src/ForceFreeStates/Riccati/OuterBasis.jl new file mode 100644 index 0000000000..a5b9384af0 --- /dev/null +++ b/src/ForceFreeStates/Riccati/OuterBasis.jl @@ -0,0 +1,115 @@ +# The solutions of the Δ' boundary-value problem on the stored radial grid. + +""" + outer_solution_basis(coefficients, propagators, chunks, columns, bases, surfaces, equil, mats, modes) -> OuterSolutionBasis + +Rebuild the solutions of the Δ' boundary-value problem [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37] +at every stored step of the chunk propagators. The cut solution leaves out the leading-order big and small terms +over the two chunks next to each surface. + +### Arguments + + - `coefficients`: The BVP's solution vectors, one column per solution, from `compute_delta_prime_matrix`. + - `propagators`, `chunks`, `columns`, `bases`: From `riccati_eulerlagrange_integration`. + - `surfaces`: The singular surfaces `chunks` index. + - `modes`: Mode indexing. +""" +function outer_solution_basis(coefficients::Matrix{ComplexF64}, propagators::Vector{ChunkPropagator}, + chunks::Vector{IntegrationChunk}, columns, bases::AbstractDict, surfaces::Vector{SingType}, + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices) + (; stored, slots) = columns + N = modes.numpert_total + nsol = size(coefficients, 2) + ngrid = slots[end] + chunk_coefficients = basis_chunk_coefficients(coefficients, propagators, chunks, columns) + + psi = Vector{Float64}(undef, ngrid) + q = Vector{Float64}(undef, ngrid) + xi = Array{ComplexF64}(undef, N, ngrid, nsol) + xi_deriv = Array{ComplexF64}(undef, N, ngrid, nsol) + nblas = BLAS.get_num_threads() + BLAS.set_num_threads(1) + try + Threads.@threads for i in eachindex(chunks) + u = zeros(ComplexF64, N, nsol, 2) + du = zeros(ComplexF64, N, nsol, 2) + spline_hint, mats_hint = Ref(1), Ref(1) + for (j, k) in enumerate(stored[i]) + node = slots[i] + j + psi[node] = propagators[i].psi[k] + @views for half in 1:2 + mul!(u[:, :, half], propagators[i].steps[k][:, :, half], chunk_coefficients[i]) + end + q[node] = el_derivatives!(du, u, false, equil, mats, modes, psi[node], spline_hint, mats_hint) + @views xi[:, node, :] .= u[:, :, 1] + @views xi_deriv[:, node, :] .= du[:, :, 1] + end + end + finally + BLAS.set_num_threads(nblas) + end + + i_crossings = findall(c -> c.needs_crossing, chunks) + xi_cut = copy(xi) + cut_range = Matrix{Float64}(undef, length(i_crossings), 2) + for (j, ic) in enumerate(i_crossings) + surface = surfaces[chunks[ic].ising] + ipert = 1 + surface.m[1] - modes.mlow + (surface.n[1] - modes.nlow) * modes.mpert + cut_range[j, 1] = chunks[ic].psi_start + cut_range[j, 2] = chunks[ic+1].psi_end + for (i, series) in ((ic, bases[chunks[ic].ising].left_series), (ic + 1, bases[chunks[ic].ising].right_series)) + big = transpose(@view chunk_coefficients[i][ipert, :]) + small = transpose(@view chunk_coefficients[i][ipert+N, :]) + for node in (slots[i]+1):slots[i+1] + leading = sing_get_ua_res_cut(series, abs(psi[node] - surface.psifac)) + @views xi_cut[:, node, :] .-= leading[:, 1, 1] .* big .+ leading[:, 2, 1] .* small + end + end + end + return OuterSolutionBasis(psi, q, fill(false, ngrid), xi, xi_deriv, xi_cut, cut_range) +end + +""" + basis_chunk_coefficients(coefficients, propagators, chunks, columns) -> Vector{Matrix{ComplexF64}} + +Per chunk, the 2N × nsol matrix that its propagator's stored steps multiply to give the solutions `coefficients` +of the Δ' boundary-value problem there. +""" +function basis_chunk_coefficients(coefficients::Matrix{ComplexF64}, propagators::Vector{ChunkPropagator}, + chunks::Vector{IntegrationChunk}, columns) + (; axis_state, starts) = columns + N = size(axis_state, 2) + matrix(i) = [propagators[i].u[:, :, 1]; propagators[i].u[:, :, 2]] + i_crossings = findall(c -> c.needs_crossing, chunks) + msing = length(i_crossings) + chunk_coefficients = Vector{Matrix{ComplexF64}}(undef, length(chunks)) + + # Axis side: the BVP's axis coefficients multiply the orthonormalized `axis_state`; trace them to each chunk's + # start columns as `restore_solution_columns!` does. + axis_columns = qr(axis_state).R \ coefficients[1:N, :] + for i in (i_crossings[1]-1):-1:1 + chunk_end = matrix(i) * starts[i] + axis_columns = chunk_end[(N+1):(2N), :] \ axis_columns + chunk_coefficients[i] = starts[i] * axis_columns + end + + for j in 1:msing + ic = i_crossings[j] + # The crossing chunk starts from the left basis; the forward chunks before it, back to the matching point, + # from the state at their lower end. + chunk_coefficients[ic] = coefficients[_col_left(j, N), :] + state = matrix(ic) * chunk_coefficients[ic] + range_L = j == 1 ? (1:0) : _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:left) + for i in reverse(range_L) + state = matrix(i) \ state + chunk_coefficients[i] = state + end + # The chunk after the surface starts from the right basis; the rest multiply on. + range_R = _midpoint_shoot_range(chunks, i_crossings, j, msing; side=:right) + chunk_coefficients[ic+1] = coefficients[_col_right(j, N), :] + for i in range_R[2:end] + chunk_coefficients[i] = matrix(i - 1) * chunk_coefficients[i-1] + end + end + return chunk_coefficients +end diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 7fee4f550b..42c1855c4c 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -62,12 +62,13 @@ function run_force_free_states( free_energies = nothing gal_data = nothing delta_prime = nothing + basis = nothing if ctrl.algorithm isa Galerkin ctrl.kinetic === nothing || error("Galerkin() does not support kinetic runs; use Forward().") gal_start = time() wv = ctrl.vac_flag ? first(compute_scaled_wv(ctrl, equil, intr)) : nothing - gal_data, delta_prime = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) + gal_data, delta_prime, basis = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) gal_dt = time() - gal_start @info "Galerkin solve completed in $(@sprintf("%.3f", gal_dt)) s" else @@ -101,14 +102,18 @@ function run_force_free_states( if intr.verbose @info "Computing Δ' matrix (STRIDE BVP with vacuum coupling)" end - delta_prime = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; + delta_prime, coefficients = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) + if coefficients !== nothing + basis = outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, + intr.sing, equil, mats, ModeIndices(intr)) + end end end end # Publish the solve: from here on the downstream stages read the result, never `intr`. - result = build_result(_integrator_symbol(ctrl.algorithm), ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime) + result = build_result(_integrator_symbol(ctrl.algorithm), ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime, basis) return result end diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index b8d7fabe64..0c4364d2cd 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -70,10 +70,10 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: m_modes, n_modes = mode_arrays(ffs) # A run has at most one ξ solution, already closed at the rationals and carrying populated - # Ξ′ / Ξ_s stores. The gal-native basis takes the analytic Galerkin Ξ′ downstream. + # Ξ′ / Ξ_s stores. A matched solution's stored Ξ′ is used as is downstream. solution = ffs.solution resp = PlasmaResponse(; ffs, m_modes, n_modes, compute_singular_coupling, compute_torque_response, - odet_from_gal=solution !== nothing && solution.basis === :gal_native) + unit_edge_basis=solution !== nothing && solution.basis === :unit_edge) # A Riccati result carries ξ profiles, but the response operators are not validated on them yet. riccati = ffs.integrator === :riccati diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index b31ed49d3a..3de1ac75c1 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -48,8 +48,8 @@ spectra. - `ffs::ForceFreeStatesResult` - The result the operators were built from. - `m_modes`, `n_modes` - Poloidal and toroidal mode number of each entry of a spectrum [numpert_total]. - - `odet_from_gal::Bool` - The solution is the gal-native matched basis, whose `du_store` carries the - analytic Galerkin Ξ′; selects that branch of the singular-coupling Ξ′ evaluation. + - `unit_edge_basis::Bool` - The solution is a `MatchProblem` one (`basis = :unit_edge`); the singular coupling + then takes Ξ′ from its `du_store`. - `compute_singular_coupling::Bool`, `compute_torque_response::Bool` - The [`plasma_response`](@ref) options it was built with. - `flux_matrix::Matrix{ComplexF64}` - Control-surface flux of the free-boundary eigenmodes [mode × eigenmode]. - `plasma_inductance_flux`, `surface_inductance_flux`, `permeability_flux` - Λ, L and P = Λ·L⁻¹ acting @@ -101,7 +101,7 @@ on a `ResonantCoupling`): ffs::ForceFreeStatesResult m_modes::Vector{Int} = Int[] n_modes::Vector{Int} = Int[] - odet_from_gal::Bool = false + unit_edge_basis::Bool = false compute_singular_coupling::Bool = true compute_torque_response::Bool = false diff --git a/src/PerturbedEquilibrium/SingularCoupling.jl b/src/PerturbedEquilibrium/SingularCoupling.jl index ac1f26afba..d7e6f53cb7 100644 --- a/src/PerturbedEquilibrium/SingularCoupling.jl +++ b/src/PerturbedEquilibrium/SingularCoupling.jl @@ -77,14 +77,14 @@ function _chord_solution_at(psi::Float64, resnum::Int, odet::SolutionProfiles, n end """ - _gal_solution_at(psi, resnum, odet, nstep) -> (u, du) + _matched_solution_at(psi, resnum, odet, nstep) -> (u, du) -Evaluate the `resnum` row of Ξ_ψ and Ξ′_ψ at `psi` for a gal-matched solution: -cubic Hermite for the value and the analytic Ξ′ carried in `du_store` for the derivative +Evaluate the `resnum` row of Ξ_ψ and Ξ′_ψ at `psi` for a matched solution: +cubic Hermite for the value and the Ξ′ carried in `du_store` for the derivative (the `gal_flag` branch of Fortran `gpeq_sol`). Do not difference `u_store` instead: near-cancellation in `bwp1` (singfac·Ξ′ against n·q′·Ξ) amplifies that error into Δ′. """ -function _gal_solution_at(psi::Float64, resnum::Int, odet::SolutionProfiles, nstep::Int) +function _matched_solution_at(psi::Float64, resnum::Int, odet::SolutionProfiles, nstep::Int) il, ir, _ = _psi_bracket(odet.psi_store, psi, nstep) psi_a, psi_b = odet.psi_store[il], odet.psi_store[ir] @@ -340,10 +340,10 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) lpsi = sing_surf.psifac - spot_psi rpsi = sing_surf.psifac + spot_psi - # Ξ, Ξ′ at lpsi/rpsi as in Fortran gpeq_sol: gal-matched → analytic Ξ′, ideal → EL relation, kinetic → stored Ξ′. - if resp.odet_from_gal - u_l, ud_l = _gal_solution_at(lpsi, resnum, solution, nstep) - u_r, ud_r = _gal_solution_at(rpsi, resnum, solution, nstep) + # Ξ, Ξ′ at lpsi/rpsi as in Fortran gpeq_sol: matched → its stored Ξ′, ideal → EL relation, kinetic → stored Ξ′. + if resp.unit_edge_basis + u_l, ud_l = _matched_solution_at(lpsi, resnum, solution, nstep) + u_r, ud_r = _matched_solution_at(rpsi, resnum, solution, nstep) elseif use_el u_l, ud_l = _el_solution_at(lpsi, resnum, solution, mats, equil, ffs, nstep) u_r, ud_r = _el_solution_at(rpsi, resnum, solution, mats, equil, ffs, nstep) diff --git a/src/Utilities/HDF5Schema.jl b/src/Utilities/HDF5Schema.jl index f17b535113..a66f2c86f0 100644 --- a/src/Utilities/HDF5Schema.jl +++ b/src/Utilities/HDF5Schema.jl @@ -193,6 +193,18 @@ const MAIN_H5_ANNOTATIONS = [ attach=(3 => "ForceFreeStates/Solutions/ForwardIntegration/psi",)), "ForceFreeStates/Solutions/ForwardIntegration/crit" => (; long_name="DCON zero-crossing criterion at saved snapshots", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/ForwardIntegration/psi",)), + # --- ForceFreeStates/Solutions/Match/ (the solution a MatchProblem closes, on the grid of its outer basis) --- + "ForceFreeStates/Solutions/Match/psi" => (; long_name="normalized poloidal flux ψ_N grid of the matched solution", scale="psi_match"), + "ForceFreeStates/Solutions/Match/q" => + (; long_name="safety factor q on the matched-solution grid", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/Match/psi",)), + "ForceFreeStates/Solutions/Match/xi_psi" => + (; long_name="closed axis-to-edge ξ^ψ profiles (ideal or inner-layer closure; identity-at-edge basis)", dims=("mode", "solution", "psi"), + attach=(3 => "ForceFreeStates/Solutions/Match/psi",)), + "ForceFreeStates/Solutions/Match/dxi_psidpsi" => + (; long_name="ψ_N derivative of the closed ξ^ψ profiles", dims=("mode", "solution", "psi"), attach=(3 => "ForceFreeStates/Solutions/Match/psi",)), + "ForceFreeStates/Solutions/Match/xi_s" => + (; long_name="surface displacement ξ_s from the outer ideal-MHD relation", dims=("mode", "solution", "psi"), + attach=(3 => "ForceFreeStates/Solutions/Match/psi",)), # --- ForceFreeStates/EdgeScan/ (power-normalized (W, N) pencil energies) --- "ForceFreeStates/EdgeScan/psi" => (; long_name="normalized poloidal flux ψ_N of the edge truncation scan", scale="psi"), "ForceFreeStates/EdgeScan/q" => (; long_name="safety factor at scan points", dims=("psi",), attach=(1 => "ForceFreeStates/EdgeScan/psi",)), diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 9a11dbcd1b..660ab754a1 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -33,8 +33,8 @@ end delta = reshape([raw[2, 2] - raw[2, 1] - raw[1, 2] + raw[1, 1]], 1, 1) return ComplexF64.(delta), ComplexF64.(raw) end - extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], true) - ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], false) + extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], true)[1:2] + ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], false)[1:2] @test extended == reference @test ordinary != reference @test all(isapprox.(ordinary, reference; rtol=1e-8)) diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index 4cf9ffbfc7..9f1ae2d927 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -195,7 +195,8 @@ include("display_check.jl") sol = ffs.solution @test sol isa FFS.SolutionProfiles - @test sol.basis === :gal_native + @test sol.basis === :unit_edge + @test ffs.basis !== nothing && sol.psi_store == ffs.basis.psi[.!ffs.basis.issing] @test sol.step == length(sol.psi_store) == size(sol.u_store, 4) @test !iszero(sol.du_store) # analytic galerkin Ξ′ @test !iszero(sol.xi_s_store) @@ -243,14 +244,17 @@ include("display_check.jl") # The closed profiles land in the shared Solutions layout: same names and # (mode, solution, psi) axis order as ForwardIntegration, on the gal grid. gal = "ForceFreeStates/Solutions/GalerkinIntegration" + matched = "ForceFreeStates/Solutions/Match" HDF5.h5open(GeneralizedPerturbedEquilibrium.run_settings(TOML.parsefile(joinpath(dir, "gpec.toml")), dir).output_file, "r") do f @test ffs.galerkin.solver in ("cholesky", "LU") @test read(f["$gal/solver"]) == ffs.galerkin.solver @test haskey(attrs(f["$gal/solver"]), "long_name") - @test read(f["$gal/psi"]) == sol.psi_store - @test read(f["$gal/xi_psi"]) == sol.u_store[:, :, 1, :] - @test read(f["$gal/dxi_psidpsi"]) == sol.du_store - @test read(f["$gal/xi_s"]) == sol.xi_s_store + @test read(f["$matched/psi"]) == sol.psi_store + @test read(f["$matched/xi_psi"]) == sol.u_store[:, :, 1, :] + @test read(f["$matched/dxi_psidpsi"]) == sol.du_store + @test read(f["$matched/xi_s"]) == sol.xi_s_store + @test isempty(_collect_metadata_violations(f["ForceFreeStates/Solutions/Match"])) + @test !haskey(f, "$gal/psi") # Matching diagnostics sit with the other per-surface results, and the # raw outer basis is debug-gated off by default. @test haskey(f, "SingularSurfaces/Match/cout") diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index ec60ed0196..12edb678b6 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -153,7 +153,7 @@ end ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example", nchunks) odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv - result = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) + result, _ = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) return result.matrix, riccati.chunks end dp_auto, chunks_auto = delta_prime(0) @@ -163,6 +163,35 @@ end @test isapprox(dp_few, dp_auto; rtol=1e-4) end + @testset "the Δ′ solutions on the stored grid" begin + ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example") + odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) + wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv + delta_prime, coefficients = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) + basis = FFS.outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, + FFS.ModeIndices(intr)) + N, msing = intr.numpert_total, intr.msing + ideal = (2msing+1):(2msing+N) + @test basis.psi == odet.psi_store && size(basis.xi) == size(basis.xi_deriv) == size(basis.xi_cut) == (N, odet.step, 2msing + N) + # The Δ_EF solutions carry no big solution and a unit edge displacement: the ideal solution, which the + # integrator's own columns give when scaled the same way. + @test basis.xi[:, end, ideal] ≈ I(N) + edge = odet.u_store[:, :, 1, end] + @test all(k -> isapprox(basis.xi[:, k, ideal], odet.u_store[:, :, 1, k] / edge; rtol=1e-6), 1:odet.step) + # The cut solution differs from the solution only next to the surfaces, where it is what remains of the + # resonant harmonic once the leading big and small terms are gone. + for (j, s) in enumerate(intr.sing) + lo, hi = basis.cut_range[j, :] + @test lo < s.psifac < hi + ires = 1 + s.m[1] - intr.mlow + right = findfirst(>(s.psifac), basis.psi) + @test abs(basis.xi_cut[ires, right, 2j]) < 1e-2 * abs(basis.xi[ires, right, 2j]) + @test abs(basis.xi_cut[ires, right-1, 2j-1]) < 1e-2 * abs(basis.xi[ires, right-1, 2j-1]) + end + outside = [all(j -> !(basis.cut_range[j, 1] <= p <= basis.cut_range[j, 2]), 1:msing) for p in basis.psi] + @test any(outside) && basis.xi_cut[:, outside, :] == basis.xi[:, outside, :] + end + @testset "truncation at the edge energy peak" begin # The chunks, their propagators and the Δ′ system follow the edge to the peak. ctrl, intr, equil, _, mats = prepared_solovev(; over=Dict{String,Any}("truncate_at_dW_peak" => true)) @@ -175,10 +204,12 @@ end free = FFS.free_run(odet, ctrl, equil, mats, intr) @test isfinite(free.et[1]) # The Δ′ system reproduces the plasma response of the axis-to-edge products, and says so when it does not. - delta_prime = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; + delta_prime, coefficients = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=free.wp, psio=equil.psio) @test size(delta_prime.matrix) == (intr.msing, intr.msing) && all(isfinite, delta_prime.matrix) @test size(delta_prime.coil) == (2 * intr.msing, intr.numpert_total) + basis = FFS.outer_solution_basis(coefficients, propagators, chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, FFS.ModeIndices(intr)) + @test basis.psi == odet.psi_store && all(isfinite, basis.xi) @test_logs (:warn, r"differs from the axis-to-edge one") FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=1.01 .* free.wp, psio=equil.psio) end diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 6fa6f17397..941750475f 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -467,7 +467,12 @@ include("display_check.jl") @test matched.closure === :matched @test matched.match !== nothing && matched.bpen == matched.match.bpen @test matched.wp === nothing && matched.free_boundary === nothing - @test matched.solution === nothing # no Galerkin basis to build a matched ξ from + # The matched ξ is built from the Riccati solve's own outer solutions, on its stored grid. + @test ric.basis !== nothing && size(ric.basis.xi, 3) == 2 * length(ric.surfaces) + ric.numpert_total + @test matched.solution.basis === :unit_edge && matched.solution.psi_store == ric.basis.psi + @test matched.solution.u_store[:, :, 1, :] == permutedims(matched.match.xi, (1, 3, 2)) + # A Riccati basis always carries its cut solution, so the composite inner profiles need no option. + @test length(solve(MatchProblem(ric; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel(; real_profiles=true)).match.inner_xi) == length(ric.surfaces) # It carries no ideal δW, so no plasma response can be built from it. @test_throws ErrorException plasma_response(matched) # A matched result is a new solution, not an outer solve to match again. @@ -496,7 +501,7 @@ include("display_check.jl") @test matched.match !== nothing # The ideal reference keeps the ideal δW (only a :matched closure drops it). @test matched.wp === gal.wp && matched.free_boundary === gal.free_boundary - @test matched.solution !== nothing && matched.solution.basis === :gal_native + @test matched.solution !== nothing && matched.solution.basis === :unit_edge end end @@ -575,6 +580,8 @@ include("display_check.jl") @test reference.closure === :matched @test api.bpen ≈ reference.bpen rtol = 1e-12 @test api.match.cout ≈ reference.match.cout rtol = 1e-12 + @test !isempty(api.match.xi) + @test api.match.xi ≈ reference.match.xi rtol = 1e-12 end # A forward solve has no Δ′ to match against, so the deck stops at parse time instead of after the solve. From d0f04565d8030714ce34a782f0ef4b8c3816eb0d Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 18:59:10 +0100 Subject: [PATCH 07/27] ForceFreeStates - FEATURE! - Cross ideal singular surfaces in the asymptotic basis in Forward and default singfac_min to 5e-4 --- docs/src/api.md | 13 +- docs/src/stability.md | 4 +- examples/DIIID-like_SLAYER_example/gpec.toml | 2 +- .../DIIID-like_error_field_example/gpec.toml | 2 +- .../gpec.toml | 2 +- examples/DIIID-like_ideal_example/gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../DIIID-like_truncation_example/gpec.toml | 2 +- examples/LAR_beta_scan/gpec.toml | 2 +- examples/LAR_epsilon_scan/gpec.toml | 2 +- examples/LAR_ideal_match_test/gpec.toml | 2 +- examples/LAR_resistive_match_test/gpec.toml | 2 +- examples/LAR_reversed_shear_example/gpec.toml | 2 +- examples/Solovev_ideal_example/gpec.toml | 2 +- examples/Solovev_ideal_example_3D/gpec.toml | 2 +- .../Solovev_ideal_example_multi_n/gpec.toml | 2 +- .../single_n_1/gpec.toml | 2 +- .../single_n_2/gpec.toml | 2 +- examples/TJ_ideal_example/gpec.toml | 2 +- examples/TJ_kinetic_NTV_example/gpec.toml | 2 +- .../TJ_kinetic_calculated_example/gpec.toml | 2 +- .../TJ_kinetic_multiion_example/gpec.toml | 2 +- examples/a10_kinetic_example/gpec.toml | 2 +- src/Equilibrium/Grid/GridRefinement.jl | 4 +- src/ForceFreeStates/CoreTypes.jl | 7 +- src/ForceFreeStates/EulerLagrange.jl | 139 ++++++++++-------- src/ForceFreeStates/ForceBalance.jl | 11 ++ src/ForceFreeStates/Riccati/Crossings.jl | 14 +- test/runtests_eulerlagrange.jl | 57 +++---- test/runtests_riccati.jl | 30 ++-- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../regression_tj_ideal_example/gpec.toml | 2 +- .../gpec.toml | 2 +- 37 files changed, 179 insertions(+), 156 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 916f34e1fb..0ea0454754 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -48,12 +48,12 @@ ForceFreeStatesResult Riccati, ideal closure Modes n = 1, m = -4:3 (8 total) Domain ψ ∈ [0.0001, 0.9995], q_lim = 3.262 Surfaces 2: 2/1 @ ψ = 0.1221, 3/1 @ ψ = 0.8804 - Fixed boundary not reported (the Riccati (S, I) history cannot show crossings) + Fixed boundary 8 crit sign changes (unvalidated, not a stability verdict) Free boundary stable: et₁ = 16.4, ep₁ = 14.04, ev₁ = 2.365, vacuum λ = 2.315 - Δ′_ii (ψ_N) 2/1: 0.1781, 3/1: -215.7 - Solution not computed (Riccati stores no ξ profiles) + Δ′_ii (ψ_N) 2/1: 0.1781, 3/1: -317.9 + Solution ξ profiles stored (448 ψ nodes, el_axis basis) Wall ConformalWall, standoff = 0.2415 a - Plots 13 of 15 available (see available_plots) + Plots 14 of 15 available (see available_plots) ``` The fields themselves are documented in each type's docstring. @@ -64,13 +64,14 @@ Every plot in [`Analysis`](analysis.md) takes the result in memory or the path o ```julia-repl julia> available_plots(ffs) -Plots for ForceFreeStatesResult (riccati): 13 of 15 available +Plots for ForceFreeStatesResult (riccati): 14 of 15 available ForceFreeStates ✓ plot_ffs_summary the stability panels the run supplies - ✗ plot_mode_displacement needs stored ξ profiles: use the Forward integrator or a matched Galerkin solve (Riccati and unmatched Galerkin store none) ✓ plot_critical_determinant critical determinant against ψ_N ⋮ + ✗ plot_cond_fbar needs the kinetic singular-surface scan: run with a kinetic source and singfac_min > 0 + ⋮ ``` A plot the source cannot draw throws an `ArgumentError` with the same reason, and a summary leaves out the panels it cannot draw: diff --git a/docs/src/stability.md b/docs/src/stability.md index af7a98d45e..04fb962702 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -42,7 +42,7 @@ Its global boundary-value problem over all surfaces gives the Δ′ matrix of [G `[ForceFreeStates] integrator` selects the radial method; its numerical settings sit in a section of the same name. - `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the solution at every solver step, like Forward, so its result carries ``\xi`` profiles; `plasma_response` does not accept a Riccati result yet. -- `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction at each rational surface. It returns dense displacement profiles, and is the only integrator whose result `plasma_response` accepts (the response operators are built from the dense ``\xi`` solution; a wall is refused too) and the only one that supports the kinetic solve. +- `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction as the solutions grow, crossing each rational surface in its asymptotic basis as Riccati does. It returns dense displacement profiles, and is the only integrator whose result `plasma_response` accepts (the response operators are built from the dense ``\xi`` solution; a wall is refused too) and the only one that supports the kinetic solve. - `"Galerkin"` (`[Galerkin]`) solves the outer region variationally on a finite-element basis, giving the resistive Δ′ matrix and the PEST-3 blocks but no free-boundary energies; see [Galerkin Solver](galerkin.md). `kinetic = "KineticForces"` replaces the ideal energy matrices by their drift-kinetic form, which needs `[Equilibrium] kinetic_file`; see [Kinetic Forces](kinetic_forces.md). @@ -140,7 +140,7 @@ The perpendicular diffusivities that set the layer widths are described with the - The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from products of the same propagators, matched midway between the surfaces. - With `vac_flag = true` the solutions of that boundary-value problem are rebuilt on the stored grid from the same propagators and published as `ffs.basis`, the outer solutions a `[Match]` combines. - Both integrators use the adaptive ninth-order `Vern9` solver at `eulerlagrange_tolerance`; the Riccati integrator reduces its state to ``(S, I)`` after every chunk, and Forward applies Gaussian reduction whenever a solution norm grows past `renorm_threshold`. -- The two integrators cross a rational surface differently. Riccati carries the nonresonant asymptotic coefficients across it (Glasser and Kolemen (2018), Eq. 36), so its energies do not depend on `singfac_min`. Forward takes a trapezoidal step between the two sides, with an error of first order in `singfac_min`, so its energies converge to Riccati's as `singfac_min` shrinks. +- Both ODE integrators cross a rational surface in its asymptotic series: the solutions are expanded in the series on the near side, the one carrying the large solution ends there, and the nonresonant coefficients continue into the series on the far side (Glasser and Kolemen (2018), Eq. 36). Their energies therefore agree and do not depend on `singfac_min`, the distance at which the crossing is made. The default, 5e-4, keeps the crossing inside the radial-grid cell that holds the surface, where the series matches the splined equilibrium; much smaller values cost steps and lose accuracy in Δ′. Kinetic crossings still take a trapezoidal step. Local stability (Mercier, resistive interchange and ballooning) is a separate stage on the same equilibrium; see [Local Stability](ballooning.md). diff --git a/examples/DIIID-like_SLAYER_example/gpec.toml b/examples/DIIID-like_SLAYER_example/gpec.toml index 0f5f28d085..883835f724 100644 --- a/examples/DIIID-like_SLAYER_example/gpec.toml +++ b/examples/DIIID-like_SLAYER_example/gpec.toml @@ -46,7 +46,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_error_field_example/gpec.toml b/examples/DIIID-like_error_field_example/gpec.toml index 070ffa8172..f8315025b1 100644 --- a/examples/DIIID-like_error_field_example/gpec.toml +++ b/examples/DIIID-like_error_field_example/gpec.toml @@ -57,7 +57,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_gal_resistive_example/gpec.toml b/examples/DIIID-like_gal_resistive_example/gpec.toml index 0abc47dc1c..c7e2efdebf 100644 --- a/examples/DIIID-like_gal_resistive_example/gpec.toml +++ b/examples/DIIID-like_gal_resistive_example/gpec.toml @@ -44,7 +44,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 4 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at plasma-vacuum interface. -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_ideal_example/gpec.toml b/examples/DIIID-like_ideal_example/gpec.toml index e878691667..2b020622ca 100644 --- a/examples/DIIID-like_ideal_example/gpec.toml +++ b/examples/DIIID-like_ideal_example/gpec.toml @@ -53,7 +53,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_ideal_multi_n_example/gpec.toml b/examples/DIIID-like_ideal_multi_n_example/gpec.toml index c6bfa903ee..54aae84513 100644 --- a/examples/DIIID-like_ideal_multi_n_example/gpec.toml +++ b/examples/DIIID-like_ideal_multi_n_example/gpec.toml @@ -46,7 +46,7 @@ delta_mlow = 4 # Expands lower bound of Fourier harmonics delta_mhigh = 6 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml index ddc2ee098a..fca015a0c5 100644 --- a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml +++ b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml @@ -45,7 +45,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/DIIID-like_truncation_example/gpec.toml b/examples/DIIID-like_truncation_example/gpec.toml index eb6539369c..ec1d684c7c 100644 --- a/examples/DIIID-like_truncation_example/gpec.toml +++ b/examples/DIIID-like_truncation_example/gpec.toml @@ -34,7 +34,7 @@ nn = 1 # Toroidal mode number, or consecutive numbers as delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/LAR_beta_scan/gpec.toml b/examples/LAR_beta_scan/gpec.toml index 5906bf4c4c..6d491b40a0 100644 --- a/examples/LAR_beta_scan/gpec.toml +++ b/examples/LAR_beta_scan/gpec.toml @@ -59,7 +59,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Order of the singular-surface (Frobenius) series expansion integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/LAR_epsilon_scan/gpec.toml b/examples/LAR_epsilon_scan/gpec.toml index a5a19e9ac9..6a116042ae 100644 --- a/examples/LAR_epsilon_scan/gpec.toml +++ b/examples/LAR_epsilon_scan/gpec.toml @@ -60,7 +60,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Order of the singular-surface (Frobenius) series expansion integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/LAR_ideal_match_test/gpec.toml b/examples/LAR_ideal_match_test/gpec.toml index d266d6af90..c3741147be 100644 --- a/examples/LAR_ideal_match_test/gpec.toml +++ b/examples/LAR_ideal_match_test/gpec.toml @@ -56,7 +56,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Power-series order for the singular-surface asymptotics integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/LAR_resistive_match_test/gpec.toml b/examples/LAR_resistive_match_test/gpec.toml index 248f1cd143..167a20a35a 100644 --- a/examples/LAR_resistive_match_test/gpec.toml +++ b/examples/LAR_resistive_match_test/gpec.toml @@ -57,7 +57,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Power-series order for the singular-surface asymptotics integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/LAR_reversed_shear_example/gpec.toml b/examples/LAR_reversed_shear_example/gpec.toml index 87abaaa560..78c376cace 100644 --- a/examples/LAR_reversed_shear_example/gpec.toml +++ b/examples/LAR_reversed_shear_example/gpec.toml @@ -23,7 +23,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ), "Riccati" (chunked propagator BVP, singular-surface Δ′), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/examples/Solovev_ideal_example/gpec.toml b/examples/Solovev_ideal_example/gpec.toml index f4fabe17a9..b4ce76caa7 100644 --- a/examples/Solovev_ideal_example/gpec.toml +++ b/examples/Solovev_ideal_example/gpec.toml @@ -57,7 +57,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/Solovev_ideal_example_3D/gpec.toml b/examples/Solovev_ideal_example_3D/gpec.toml index e5a6681c68..79d63b4269 100644 --- a/examples/Solovev_ideal_example_3D/gpec.toml +++ b/examples/Solovev_ideal_example_3D/gpec.toml @@ -41,7 +41,7 @@ delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface nzeta_vacuum = 96 # Number of points used in splines over toroidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/examples/Solovev_ideal_example_multi_n/gpec.toml b/examples/Solovev_ideal_example_multi_n/gpec.toml index 569280fc47..c49a8132ac 100644 --- a/examples/Solovev_ideal_example_multi_n/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/gpec.toml @@ -47,7 +47,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details). # The multi-n Δ' matrix has open issues and is skipped with a warning; the energies stay valid. diff --git a/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml b/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml index 8e611f4956..0d37f5c8a6 100644 --- a/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/single_n_1/gpec.toml @@ -47,7 +47,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 10 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the Riccati integrator [Riccati] diff --git a/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml b/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml index 0aa031281d..e2501b9c0f 100644 --- a/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/single_n_2/gpec.toml @@ -47,7 +47,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the Riccati integrator [Riccati] diff --git a/examples/TJ_ideal_example/gpec.toml b/examples/TJ_ideal_example/gpec.toml index 7516d63c3b..0ba417cdb1 100644 --- a/examples/TJ_ideal_example/gpec.toml +++ b/examples/TJ_ideal_example/gpec.toml @@ -43,7 +43,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/examples/TJ_kinetic_NTV_example/gpec.toml b/examples/TJ_kinetic_NTV_example/gpec.toml index b9d3e66598..a5ed48d3e4 100644 --- a/examples/TJ_kinetic_NTV_example/gpec.toml +++ b/examples/TJ_kinetic_NTV_example/gpec.toml @@ -32,7 +32,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/examples/TJ_kinetic_calculated_example/gpec.toml b/examples/TJ_kinetic_calculated_example/gpec.toml index 3b8a45e27b..518e102b73 100644 --- a/examples/TJ_kinetic_calculated_example/gpec.toml +++ b/examples/TJ_kinetic_calculated_example/gpec.toml @@ -44,7 +44,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/examples/TJ_kinetic_multiion_example/gpec.toml b/examples/TJ_kinetic_multiion_example/gpec.toml index 5b32e39f7a..f37e0b511b 100644 --- a/examples/TJ_kinetic_multiion_example/gpec.toml +++ b/examples/TJ_kinetic_multiion_example/gpec.toml @@ -44,7 +44,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 8 # Expands lower bound of Fourier harmonics delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/examples/a10_kinetic_example/gpec.toml b/examples/a10_kinetic_example/gpec.toml index 24b0c408f1..a990d5a642 100644 --- a/examples/a10_kinetic_example/gpec.toml +++ b/examples/a10_kinetic_example/gpec.toml @@ -57,7 +57,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator [Forward] diff --git a/src/Equilibrium/Grid/GridRefinement.jl b/src/Equilibrium/Grid/GridRefinement.jl index 772635b8c4..167c55405c 100644 --- a/src/Equilibrium/Grid/GridRefinement.jl +++ b/src/Equilibrium/Grid/GridRefinement.jl @@ -421,7 +421,7 @@ end """ refined_psi_grid(equil::PlasmaEquilibrium; tau, kin=nothing, mandatory=Float64[], pinned=Float64[], - singfac_min=1e-4, n_min=1, bracket_coef=BRACKET_COEF, + singfac_min=5e-4, n_min=1, bracket_coef=BRACKET_COEF, min_spacing=MIN_KNOT_SPACING, N_cap=REFINED_N_CAP) -> Vector{Float64} Build the refined pass-2 ψ grid from a formed pass-1 equilibrium: knot density, equidistribution, @@ -441,7 +441,7 @@ function refined_psi_grid(equil::PlasmaEquilibrium; kin::Union{Nothing,KineticProfileSplines}=nothing, mandatory::Vector{Float64}=Float64[], pinned::Vector{Float64}=Float64[], - singfac_min::Float64=1e-4, + singfac_min::Float64=5e-4, n_min::Int=1, bracket_coef::Float64=BRACKET_COEF, min_spacing::Float64=MIN_KNOT_SPACING, diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index c1d0e8f17e..66333db109 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -94,8 +94,9 @@ Physical and workflow controls for a force-balance solve, together with its sele - `nn_high::Int` - Upper bound for toroidal modes - `delta_mlow::Int` - Expands lower bound of Fourier harmonics by delta_mlow - `delta_mhigh::Int` - Expands upper bound of Fourier harmonics by delta_mhigh - - `singfac_min::Float64` - Fractional distance from rational q at which the ideal jump condition is enforced. Default 1e-4 suits the Riccati Δ′ (smaller values add a - spurious imaginary part); Forward runs feeding PerturbedEquilibrium need about 1e-6 for the outer-surface singular coupling to converge. + - `singfac_min::Float64` - Distance `|m − nq|` from each rational surface at which the ideal integration stops and + the surface is crossed through its asymptotic series. Energies do not depend on it; Δ′ loses accuracy below + about 1e-5, and the series does beyond the first radial-grid knot. - `truncate_at_rational_offset::Bool` - Truncate the domain at `(last_rational_q + rational_offset_fraction) / n` instead of at `qhigh` / `psihigh`, avoiding a spurious δW kink when the integration ends just below a rational. Right for diverted equilibria (default `true`); set `false` for limited/analytic equilibria with finite edge q (Solovev, LAR), where it cuts too much edge. Multi-n runs warn and fall back to `qhigh` / `psihigh`. @@ -127,7 +128,7 @@ Physical and workflow controls for a force-balance solve, together with its sele nn_high::Int = 0 delta_mlow::Int = 0 delta_mhigh::Int = 0 - singfac_min::Float64 = 1e-4 # Required nonzero for the Riccati path. + singfac_min::Float64 = 5e-4 # Required nonzero for the Riccati path. truncate_at_rational_offset::Bool = true psilim_from_layer_overlap::Union{Bool,InnerLayer.SLAYERModel} = false rational_offset_fraction::Float64 = 0.2 diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index ef90625414..cb71b6d773 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -553,11 +553,13 @@ function chunk_el_integration_bounds(odet::OdeState, ctrl::ForceFreeStatesContro end """ - cross_ideal_singular_surf!(odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) + cross_ideal_singular_surf!(odet, ctrl, equil, mats, intr, ising) -Cross ideal singular surface `ising`: reduce on the resonant rows, record the left asymptotic -coefficients, replace the resonant solutions by the small asymptotic solutions on the far side, -and record the right coefficients. Port of Fortran `ode_ideal_cross`. +Cross ideal singular surface `ising` in its asymptotic basis [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, +Eq. 36]: the solutions are expanded in the left basis, the column carrying each resonance's big solution ends at +the surface, the nonresonant coefficients continue into the right basis, and each small solution starts there in +the freed column. Records both coefficient sets in `odet.ca_l` and `odet.ca_r`, and the column reduction for +`transform_u!`. """ function cross_ideal_singular_surf!( odet::OdeState, @@ -567,50 +569,73 @@ function cross_ideal_singular_surf!( intr::ForceFreeStatesInternal, ising::Int ) - singp = intr.sing[ising] + N = intr.numpert_total ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - nres = length(ipert_res) - - # Reduce on the resonant rows so the solutions removed below are the resonant ones - compute_solution_norms!(odet.u, odet, ctrl, intr, true; resonant_rows=ipert_res) - - sing_asymp_right = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0) - sing_asymp_left = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0) dpsi = singp.psifac - odet.psifac # ψ_res - ψ (positive) + ua_left = sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0), dpsi) + ua_right = sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0), dpsi) - ua = sing_get_ua(sing_asymp_left, dpsi) - odet.ca_l[:, :, :, ising] .= sing_get_ca(odet.u, ua, intr) - - # The reduction put the column pivoted on ipert_res[i] at index position i; zeroed_idx records it for transform_u! - odet.zeroed_idx[odet.ifix] = collect(1:nres) - for i in 1:nres - odet.u[:, odet.index[i, odet.ifix], :] .= 0 - end + # Reduce first: columns left nearly parallel by the integration would lose their difference in the basis change. + compute_solution_norms!(odet.u, odet, ctrl, intr, true) + ca = sing_get_ca(odet.u, ua_left, intr) + next_fixup!(odet, ctrl) + pivots = reduce_big_solutions!(ca, odet, ipert_res) + odet.ca_l[:, :, :, ising] .= ca + start_small_solutions!(ca, ipert_res, pivots) + odet.ca_r[:, :, :, ising] .= ca + odet.ca_populated = true - # Trapezoidal step across the surface - params = (ctrl, equil, mats, intr, odet, IntegrationChunk(0.0, 0.0, false, ising, 1)) - du1 = zeros(ComplexF64, intr.numpert_total, intr.numpert_total, 2) - du2 = zeros(ComplexF64, intr.numpert_total, intr.numpert_total, 2) - sing_der!(du1, odet.u, params, odet.psifac) odet.psifac += 2 * dpsi - sing_der!(du2, odet.u, params, odet.psifac) - odet.u .+= (du1 .+ du2) .* dpsi - - # Swap in the small resonant asymptotic solution on the right side - ua = sing_get_ua(sing_asymp_right, dpsi) - for i in 1:nres - odet.u[ipert_res[i], :, :] .= 0 - odet.u[:, odet.index[i, odet.ifix], :] .= ua[:, ipert_res[i]+intr.numpert_total, :] + @views for k in 1:2 + mul!(odet.u[:, :, k], ua_right[:, 1:N, k], ca[:, :, 1]) + mul!(odet.u[:, :, k], ua_right[:, (N+1):(2N), k], ca[:, :, 2], 1, 1) end - odet.ca_r[:, :, :, ising] .= sing_get_ca(odet.u, ua, intr) - odet.ca_populated = true + # The next solver step records fresh reference norms. + odet.new = true # No Δ' here: it needs the Riccati propagators; see compute_delta_prime_matrix odet.q = equil.profiles.q_spline(odet.psifac; hint=odet.spline_hint) store_ode_data!(odet, odet.psifac, odet.u) end +""" + reduce_big_solutions!(ca, odet, ipert_res) -> pivots + +Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the +basis) so that one column carries the big solution of each resonance `ipert_res[i]`, and record the reduction as +fixup `odet.ifix` for `transform_u!`. Returns those columns. +""" +function reduce_big_solutions!(ca::Array{ComplexF64,3}, odet::OdeState, ipert_res) + ifix = odet.ifix + N = size(ca, 2) + nres = length(ipert_res) + odet.sing_flag[ifix] = true + # The previous region ends at the step before this fixup + odet.fixstep[ifix] = odet.step - 1 + odet.fixfac[:, :, ifix] .= 0 + for isol in 1:N + odet.fixfac[isol, isol, ifix] = 1 + end + + col_free = trues(N) + for (i, ipert) in enumerate(ipert_res) + pivot = argmax(j -> col_free[j] ? abs(ca[ipert, j, 1]) : -Inf, 1:N) + odet.index[i, ifix] = pivot + col_free[pivot] = false + for j in findall(col_free) + factor = -ca[ipert, j, 1] / ca[ipert, pivot, 1] + odet.fixfac[pivot, j, ifix] = factor + @views ca[:, j, :] .+= factor .* ca[:, pivot, :] + ca[ipert, j, 1] = 0 + end + end + odet.index[(nres+1):N, ifix] .= findall(col_free) + # transform_u! drops the columns that end at the surface + odet.zeroed_idx[ifix] = collect(1:nres) + return odet.index[1:nres, ifix] +end + """ cross_kinetic_singular_surf!(odet, ctrl, equil, mats, intr, ising) @@ -754,7 +779,7 @@ function integrate_el_region!( end """ - compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal, sing_flag::Bool; resonant_rows=Int[]) + compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal, sing_flag::Bool) Compute the column norms of u₁ and apply `apply_gaussian_reduction!` to `u` in place when their growth since the last reduction exceeds `ctrl.algorithm.renorm_threshold`, and always when `sing_flag` is set. @@ -765,10 +790,8 @@ the previous reduction's pivot order. Errors if any norm is zero. Port of Fortra - `u` - Solution array, updated in place (the integrator state, to avoid copies) - `sing_flag` - Whether this call is at a singular surface - - `resonant_rows` - Resonant rows at an ideal crossing, pivoted on first """ -function compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal, sing_flag::Bool; - resonant_rows=Int[]) +function compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal, sing_flag::Bool) odet.unorm .= norm.(eachcol(u[:, :, 1])) if minimum(odet.unorm) == 0 @@ -791,28 +814,29 @@ function compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::F end if fix_required - if odet.ifix < ctrl.algorithm.numunorms_init - odet.ifix += 1 - else - @warn "unorm storage reached, no longer saving fixfac data. Stability outputs and unorming will be correct, but cannot reconstruct `u`. \n - Increase `numunorms_init` if needed. Automatic resizing will be added in a future version." - end - apply_gaussian_reduction!(u, odet, intr, sing_flag; resonant_rows) + next_fixup!(odet, ctrl) + apply_gaussian_reduction!(u, odet, intr, sing_flag) odet.new = true end end +# Advance to the next slot of the reduction record; once the storage is full the last slot is reused. +function next_fixup!(odet::OdeState, ctrl::ForceFreeStatesControl) + if odet.ifix < ctrl.algorithm.numunorms_init + odet.ifix += 1 + else + @warn "unorm storage reached, no longer saving fixfac data. Stability outputs and unorming will be correct, but cannot reconstruct `u`. \n + Increase `numunorms_init` if needed. Automatic resizing will be added in a future version." + end +end + """ - apply_gaussian_reduction!(u::Array{ComplexF64,3}, odet::OdeState, intr::ForceFreeStatesInternal, sing_flag::Bool; resonant_rows=Int[]) + apply_gaussian_reduction!(u::Array{ComplexF64,3}, odet::OdeState, intr::ForceFreeStatesInternal, sing_flag::Bool) Triangularize the solution columns of `u` in place by Gaussian reduction, recording the factors in `odet.fixfac`/`odet.index` for `transform_u!`. Port of Fortran `ode_fixup`. - -At an ideal crossing, the first pivots are the `resonant_rows`, each on the remaining column largest -there. Growth order cannot pick the resonant solution if a `renorm_threshold` reduction fired just before the -crossing, since every column has then grown alike. """ -function apply_gaussian_reduction!(u::Array{ComplexF64,3}, odet::OdeState, intr::ForceFreeStatesInternal, sing_flag::Bool; resonant_rows=Int[]) +function apply_gaussian_reduction!(u::Array{ComplexF64,3}, odet::OdeState, intr::ForceFreeStatesInternal, sing_flag::Bool) ifix = odet.ifix odet.sing_flag[ifix] = sing_flag @@ -823,18 +847,13 @@ function apply_gaussian_reduction!(u::Array{ComplexF64,3}, odet::OdeState, intr: odet.fixfac[isol, isol, ifix] = 1 end - # Triangularize primary solutions, resonant rows first, then columns from largest to smallest growth + # Triangularize primary solutions, columns from largest to smallest growth growth_order = sortperm(odet.unorm; rev=true) row_free = trues(intr.numpert_total) col_free = trues(intr.numpert_total) for isol in 1:intr.numpert_total - if isol <= length(resonant_rows) - kpert = resonant_rows[isol] - ksol = argmax(j -> col_free[j] ? abs(u[kpert, j, 1]) : -Inf, 1:intr.numpert_total) - else - ksol = growth_order[findfirst(j -> col_free[j], growth_order)] - @views kpert = argmax(abs.(u[:, ksol, 1]) .* row_free) - end + ksol = growth_order[isol] + @views kpert = argmax(abs.(u[:, ksol, 1]) .* row_free) odet.index[isol, ifix] = ksol col_free[ksol] = false row_free[kpert] = false diff --git a/src/ForceFreeStates/ForceBalance.jl b/src/ForceFreeStates/ForceBalance.jl index f4db1a240b..c5393c1564 100644 --- a/src/ForceFreeStates/ForceBalance.jl +++ b/src/ForceFreeStates/ForceBalance.jl @@ -233,6 +233,17 @@ function prepare_force_free_states!( sing_min!(intr, ctrl, equil) remove_singular_surfs!(intr; psimin=intr.psilow) + # The asymptotic series each ideal crossing uses expands the equilibrium about its surface, so it loses accuracy + # past a radial knot. The auto grid keeps its knots clear; a fixed grid may not. + if ctrl.kinetic === nothing && ctrl.singfac_min > 0 && !(ctrl.algorithm isa Galerkin) + crowded = [s.psifac for s in intr.sing[1:intr.msing] if + any(x -> abs(x - s.psifac) < ctrl.singfac_min / abs(minimum(s.n) * s.q1), equil.profiles.xs)] + isempty(crowded) || + @warn "A radial grid knot lies within the crossing distance singfac_min/|n q'| of the rational surfaces at " * + "ψ = $(round.(crowded; digits=5)), where the asymptotic series is less accurate; lower singfac_min or use the " * + "auto grid (mpsi = 0)." + end + # GGJ geometric coefficients (E, F, G, H, K, M) of each surviving singular surface; `ggj_parameters` adds τ_A / τ_R. if intr.msing > 0 resist_eval_all!(intr, equil) diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index 346100a733..eb421623ac 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -72,18 +72,18 @@ function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) end """ - start_small_solutions!(ca, ipert_res) + start_small_solutions!(ca, ipert_res, columns=ipert_res) Turn reduced left-side coefficients `ca` into right-side ones: the resonant coefficients vanish and column -`ipert_res[i]` becomes the small solution of resonance `i`. +`columns[i]`, which carried the big solution of resonance `i`, becomes its small solution. """ -function start_small_solutions!(ca::Array{ComplexF64,3}, ipert_res) - for ipert in ipert_res +function start_small_solutions!(ca::Array{ComplexF64,3}, ipert_res, columns=ipert_res) + for (ipert, column) in zip(ipert_res, columns) ca[ipert, :, :] .= 0 - ca[:, ipert, :] .= 0 + ca[:, column, :] .= 0 end - for ipert in ipert_res - ca[ipert, ipert, 2] = 1 + for (ipert, column) in zip(ipert_res, columns) + ca[ipert, column, 2] = 1 end return ca end diff --git a/test/runtests_eulerlagrange.jl b/test/runtests_eulerlagrange.jl index 75f0edc93d..f09f957912 100644 --- a/test/runtests_eulerlagrange.jl +++ b/test/runtests_eulerlagrange.jl @@ -392,41 +392,30 @@ end @test odet.index[:, 2] == [3, 1, 2] end - @testset "ideal-crossing reduction isolates the resonant harmonic" begin + @testset "ideal-crossing reduction leaves each big solution in one column" begin FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates - # Column 1 has the largest norm but no resonant (row 3) component; column 2 carries the resonance. - # Growth order alone would lead with column 1 and pivot it on row 1, leaving row 3 in columns 2 and 3. - u0 = zeros(ComplexF64, 3, 3, 2) - u0[:, 1, 1] .= [6.0, 0.5, 0.0] - u0[:, 2, 1] .= [0.4, 0.3, 5.0] - u0[:, 3, 1] .= [0.2, 2.0, 1.5] - u0[:, :, 2] .= 1.0 - intr = FFS.ForceFreeStatesInternal(; numpert_total=3) - ctrl = FFS.ForceFreeStatesControl(; algorithm=Forward(; renorm_threshold=1e3)) - fresh(u) = (odet = FFS.OdeState(3, 10, 10, 1); odet.u .= u; odet) - - odet = fresh(u0) - odet.new = false - odet.unorm0 .= norm.(eachcol(u0[:, :, 1])) # every column grown alike since the last reduction - FFS.compute_solution_norms!(odet.u, odet, ctrl, intr, true; resonant_rows=[3]) - @test odet.index[1, 1] == 2 - @test odet.u[3, 2, 1] == u0[3, 2, 1] - @test odet.u[3, 1, 1] == 0 && odet.u[3, 3, 1] == 0 # only the lead column keeps the resonant harmonic - @test odet.sing_flag[1] - - # A crossing right after a renorm_threshold reduction (new = true) still reduces on the resonant row. - odet = fresh(u0) - FFS.compute_solution_norms!(odet.u, odet, ctrl, intr, true; resonant_rows=[3]) - @test odet.ifix == 1 && odet.index[1, 1] == 2 && odet.new - @test odet.u[3, 1, 1] == 0 && odet.u[3, 3, 1] == 0 - - # Without resonant rows the growth-ordered reduction is unchanged. - odet = fresh(u0) - odet.new = false - odet.unorm0 .= 1.0 - FFS.compute_solution_norms!(odet.u, odet, ctrl, intr, true) - @test odet.index[1, 1] == 1 - @test odet.u[3, 2, 1] != 0 + # Asymptotic coefficients of three solutions; the resonance is basis row 3 and column 2 has most of its big solution. + ca0 = zeros(ComplexF64, 3, 3, 2) + ca0[:, 1, 1] .= [6.0, 0.5, 0.2] + ca0[:, 2, 1] .= [0.4, 0.3, 5.0] + ca0[:, 3, 1] .= [0.2, 2.0, 1.5] + ca0[:, :, 2] .= [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0] + odet = FFS.OdeState(3, 10, 10, 1) + odet.ifix = 1 + ca = copy(ca0) + pivots = FFS.reduce_big_solutions!(ca, odet, [3]) + @test pivots == [2] && odet.index[:, 1] == [2, 1, 3] + @test odet.sing_flag[1] && odet.zeroed_idx[1] == [1] + @test ca[3, 1, 1] == 0 && ca[3, 3, 1] == 0 && ca[:, 2, :] == ca0[:, 2, :] + # The recorded factors are the reduction transform_u! undoes: column j gained fixfac[2, j] times column 2. + for j in (1, 3) + @test ca[:, j, :] ≈ ca0[:, j, :] .+ odet.fixfac[2, j, 1] .* ca0[:, 2, :] + end + # Right of the surface the freed column is the small solution and no other column has a resonant coefficient. + FFS.start_small_solutions!(ca, [3], pivots) + @test all(iszero, ca[3, [1, 3], :]) + @test ca[:, 2, 1] == zeros(3) && ca[:, 2, 2] == [0, 0, 1] + @test ca[1:2, [1, 3], :] ≈ (ca0[:, [1, 3], :].+reshape(odet.fixfac[2, [1, 3], 1], 1, 2, 1).*ca0[:, [2], :])[1:2, :, :] end @testset "OdeState construction" begin diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index 12edb678b6..59dcfb6395 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -89,19 +89,19 @@ end et_far = solovev_energies("Riccati", 1e-3) et_near = solovev_energies("Riccati", 1e-5) @test isapprox(et_far[1], et_near[1]; rtol=1e-6) - # Forward's trapezoid crossing reaches the same energy only as the distance shrinks. - et_forward = solovev_energies("Forward", 1e-6) - @test isapprox(real(et_far[1]), real(et_forward[1]); rtol=1e-3) + # Forward crosses the same way, so it gives the same energy at either distance. + @test isapprox(solovev_energies("Forward", 1e-3)[1], et_far[1]; rtol=1e-6) + @test isapprox(solovev_energies("Forward", 1e-5)[1], et_far[1]; rtol=1e-6) end @testset "surface with two resonances" begin fixture = "regression_solovev_ideal_example_multi_n" et_far = solovev_energies("Riccati", 1e-3; fixture) et_near = solovev_energies("Riccati", 1e-5; fixture) - et_forward = solovev_energies("Forward", 1e-6; fixture) + et_forward = solovev_energies("Forward", 1e-3; fixture) # The least-stable multi-n eigenvalue is near marginal, so its relative tolerances are looser. @test isapprox(et_far[1], et_near[1]; rtol=1e-4) - @test isapprox(real(et_far[1]), real(et_forward[1]); rtol=5e-3) + @test isapprox(et_far[1], et_forward[1]; rtol=1e-4) end @testset "stored solution" begin @@ -120,19 +120,21 @@ end @test isapprox(direct, odet_ric.u_store[:, :, :, k+1]; rtol=1e-5) end - # Across the surfaces they are the solutions Forward stores: scaled to a unit edge displacement, the - # conjugate momenta agree on each side of every surface. (ξ itself differs there by Forward's crossing - # condition, which leaves a big-solution term next to each surface.) - function edge_scaled_momentum(integrator) - ctrl, intr, equil, _, mats = prepared_solovev(; integrator, singfac_min=1e-6) + # They are the solutions Forward stores: scaled to a unit edge displacement, ξ and its conjugate momentum + # agree at the nodes the two integrators share, which lie on each side of every surface. + function edge_scaled(integrator) + ctrl, intr, equil, _, mats = prepared_solovev(; integrator) odet = first(FFS.eulerlagrange_integration(ctrl, equil, mats, intr)) - return odet, intr, [odet.u_store[:, :, 2, k] / odet.u_store[:, :, 1, odet.step] for k in 1:odet.step] + edge = odet.u_store[:, :, 1, odet.step] + return odet, intr, [cat(odet.u_store[:, :, 1, k] / edge, odet.u_store[:, :, 2, k] / edge; dims=3) for k in 1:odet.step] end - ric, intr, momentum_ric = edge_scaled_momentum("Riccati") - fwd, _, momentum_fwd = edge_scaled_momentum("Forward") + ric, intr, state_ric = edge_scaled("Riccati") + fwd, _, state_fwd = edge_scaled("Forward") shared = [(findfirst(==(p), ric.psi_store), k) for (k, p) in enumerate(fwd.psi_store[1:fwd.step]) if p in ric.psi_store] @test length(shared) >= 2 * intr.msing - @test maximum(norm(momentum_ric[i] - momentum_fwd[k]) / norm(momentum_fwd[k]) for (i, k) in shared) < 1e-2 + for component in 1:2 + @test maximum(norm(state_ric[i][:, :, component] - state_fwd[k][:, :, component]) / norm(state_fwd[k][:, :, component]) for (i, k) in shared) < 1e-4 + end end # Note: a Solovev per-surface Δ' regression testset previously lived here, diff --git a/test/test_data/regression_solovev_ideal_example/gpec.toml b/test/test_data/regression_solovev_ideal_example/gpec.toml index b2663d180e..72493fecdb 100644 --- a/test/test_data/regression_solovev_ideal_example/gpec.toml +++ b/test/test_data/regression_solovev_ideal_example/gpec.toml @@ -42,7 +42,7 @@ delta_mlow = 0 # Expands lower bound of Fourier harmonics delta_mhigh = 0 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml b/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml index 0571479748..4caa2594fc 100644 --- a/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml +++ b/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml @@ -42,7 +42,7 @@ delta_mlow = 0 # Expands lower bound of Fourier harmonics delta_mhigh = 0 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) diff --git a/test/test_data/regression_solovev_kinetic_calculated/gpec.toml b/test/test_data/regression_solovev_kinetic_calculated/gpec.toml index 9285035b38..53a79dc809 100644 --- a/test/test_data/regression_solovev_kinetic_calculated/gpec.toml +++ b/test/test_data/regression_solovev_kinetic_calculated/gpec.toml @@ -46,7 +46,7 @@ mtheta_vacuum = 64 # Number of points used in splines over pol kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator [Forward] diff --git a/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml b/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml index 2e8954e36a..6d915442fe 100644 --- a/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml +++ b/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml @@ -46,7 +46,7 @@ mtheta_vacuum = 64 # Number of points used in splines over pol kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) -singfac_min = 1e-4 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator [Forward] diff --git a/test/test_data/regression_tj_ideal_example/gpec.toml b/test/test_data/regression_tj_ideal_example/gpec.toml index 4d75cae03f..162eac8018 100644 --- a/test/test_data/regression_tj_ideal_example/gpec.toml +++ b/test/test_data/regression_tj_ideal_example/gpec.toml @@ -30,7 +30,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 4 # Expands lower bound of Fourier harmonics delta_mhigh = 4 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria diff --git a/test/test_data/regression_tj_kinetic_calculated/gpec.toml b/test/test_data/regression_tj_kinetic_calculated/gpec.toml index 3fe8fdfad0..7dae5f9a84 100644 --- a/test/test_data/regression_tj_kinetic_calculated/gpec.toml +++ b/test/test_data/regression_tj_kinetic_calculated/gpec.toml @@ -31,7 +31,7 @@ nn = 1 # Toroidal mode number, or consecutive n delta_mlow = 4 # Expands lower bound of Fourier harmonics delta_mhigh = 4 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface -singfac_min = 1e-6 # Fractional distance from rational q at which ideal jump enforced +singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria From 8948627bd61214fe7054c5857c8787c4dd6c9524 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 20:02:26 +0100 Subject: [PATCH 08/27] ForceFreeStates - FEATURE! - Fill the stored solutions inside each crossing distance from the asymptotic series --- docs/src/stability.md | 4 +- src/ForceFreeStates/CoreTypes.jl | 5 + src/ForceFreeStates/EulerLagrange.jl | 75 ++++------ src/ForceFreeStates/ForceFreeStates.jl | 1 + src/ForceFreeStates/Riccati/Crossings.jl | 80 ++--------- src/ForceFreeStates/Riccati/Driver.jl | 5 +- src/ForceFreeStates/Riccati/OuterBasis.jl | 70 +++++++--- src/ForceFreeStates/Riccati/Propagators.jl | 5 +- src/ForceFreeStates/Run.jl | 2 +- src/ForceFreeStates/Surfaces/Crossing.jl | 151 +++++++++++++++++++++ test/runtests_eulerlagrange.jl | 17 +-- test/runtests_riccati.jl | 27 +++- test/runtests_solve_api.jl | 19 +++ 13 files changed, 300 insertions(+), 161 deletions(-) create mode 100644 src/ForceFreeStates/Surfaces/Crossing.jl diff --git a/docs/src/stability.md b/docs/src/stability.md index 04fb962702..76850be4c8 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -140,7 +140,7 @@ The perpendicular diffusivities that set the layer widths are described with the - The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from products of the same propagators, matched midway between the surfaces. - With `vac_flag = true` the solutions of that boundary-value problem are rebuilt on the stored grid from the same propagators and published as `ffs.basis`, the outer solutions a `[Match]` combines. - Both integrators use the adaptive ninth-order `Vern9` solver at `eulerlagrange_tolerance`; the Riccati integrator reduces its state to ``(S, I)`` after every chunk, and Forward applies Gaussian reduction whenever a solution norm grows past `renorm_threshold`. -- Both ODE integrators cross a rational surface in its asymptotic series: the solutions are expanded in the series on the near side, the one carrying the large solution ends there, and the nonresonant coefficients continue into the series on the far side (Glasser and Kolemen (2018), Eq. 36). Their energies therefore agree and do not depend on `singfac_min`, the distance at which the crossing is made. The default, 5e-4, keeps the crossing inside the radial-grid cell that holds the surface, where the series matches the splined equilibrium; much smaller values cost steps and lose accuracy in Δ′. Kinetic crossings still take a trapezoidal step. +- Both ODE integrators cross a rational surface in its asymptotic series: the solutions are expanded in the series on the near side, the one carrying the large solution ends there, and the nonresonant coefficients continue into the series on the far side (Glasser and Kolemen (2018), Eq. 36). Their energies therefore agree and do not depend on `singfac_min`, the distance at which the crossing is made. The default, 5e-4, keeps the crossing inside the radial-grid cell that holds the surface, where the series matches the splined equilibrium; much smaller values cost steps and lose accuracy in Δ′. Inside that distance the stored solution is filled in from the series, at `crossing_fill_points` log-spaced distances per side down to `crossing_fill_min`. Kinetic crossings still take a trapezoidal step and get no fill. Local stability (Mercier, resistive interchange and ballooning) is a separate stage on the same equilibrium; see [Local Stability](ballooning.md). @@ -150,5 +150,5 @@ The Galerkin solver's functions are documented on the [Galerkin Solver](galerkin ```@autodocs Modules = [GeneralizedPerturbedEquilibrium.ForceFreeStates] -Pages = ["ForceFreeStates.jl", "CoreTypes.jl", "Surfaces/Types.jl", "Riccati/Types.jl", "Matching/DeltaPrime.jl", "Result.jl", "Surfaces/ResistEval.jl", "Matching/ResonantMatch.jl", "Matching/MatchProblem.jl", "EulerLagrange.jl", "Surfaces/Finding.jl", "Surfaces/Asymptotics.jl", "Fourfit.jl", "Kinetic.jl", "FixedKineticMatrices.jl", "FixedBoundaryStability.jl", "Utils.jl", "Free.jl", "Riccati/Propagators.jl", "Riccati/Crossings.jl", "Riccati/DeltaPrimeBVP.jl", "Riccati/OuterBasis.jl", "Riccati/Driver.jl"] +Pages = ["ForceFreeStates.jl", "CoreTypes.jl", "Surfaces/Types.jl", "Riccati/Types.jl", "Matching/DeltaPrime.jl", "Result.jl", "Surfaces/ResistEval.jl", "Matching/ResonantMatch.jl", "Matching/MatchProblem.jl", "EulerLagrange.jl", "Surfaces/Finding.jl", "Surfaces/Asymptotics.jl", "Surfaces/Crossing.jl", "Fourfit.jl", "Kinetic.jl", "FixedKineticMatrices.jl", "FixedBoundaryStability.jl", "Utils.jl", "Free.jl", "Riccati/Propagators.jl", "Riccati/Crossings.jl", "Riccati/DeltaPrimeBVP.jl", "Riccati/OuterBasis.jl", "Riccati/Driver.jl"] ``` diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 66333db109..1338896137 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -97,6 +97,9 @@ Physical and workflow controls for a force-balance solve, together with its sele - `singfac_min::Float64` - Distance `|m − nq|` from each rational surface at which the ideal integration stops and the surface is crossed through its asymptotic series. Energies do not depend on it; Δ′ loses accuracy below about 1e-5, and the series does beyond the first radial-grid knot. + - `crossing_fill_points::Int` - Stored states added on each side of each crossed rational surface from its asymptotic + series, log-spaced in distance between `singfac_min` and `crossing_fill_min`. Zero adds none. + - `crossing_fill_min::Float64` - Distance `|m − nq|` from the surface of the closest of those states. - `truncate_at_rational_offset::Bool` - Truncate the domain at `(last_rational_q + rational_offset_fraction) / n` instead of at `qhigh` / `psihigh`, avoiding a spurious δW kink when the integration ends just below a rational. Right for diverted equilibria (default `true`); set `false` for limited/analytic equilibria with finite edge q (Solovev, LAR), where it cuts too much edge. Multi-n runs warn and fall back to `qhigh` / `psihigh`. @@ -129,6 +132,8 @@ Physical and workflow controls for a force-balance solve, together with its sele delta_mlow::Int = 0 delta_mhigh::Int = 0 singfac_min::Float64 = 5e-4 # Required nonzero for the Riccati path. + crossing_fill_points::Int = 5 + crossing_fill_min::Float64 = 1e-5 truncate_at_rational_offset::Bool = true psilim_from_layer_overlap::Union{Bool,InnerLayer.SLAYERModel} = false rational_offset_fraction::Float64 = 0.2 diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index cb71b6d773..2855965b3f 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -131,8 +131,9 @@ OdeState(numpert_total::Int, numsteps_init::Int, numunorms_init::Int, msing::Int compute_delta_prime_from_ca!(odet, intr, equil) **Stub, not physically valid.** Fill each surface's `delta_prime` with the per-surface estimate -`(ca_r[i,i,2,s] - ca_l[i,i,2,s]) / (4π²·psio)` from the asymptotic coefficients. It ignores inter-surface -coupling and the vacuum, so it does not agree with the physical `ForceFreeStatesResult.delta_prime`. +`(1 - ca_l[i,c,2,s]) / (4π²·psio)` from the asymptotic coefficients, `c` being the column in which the small +solution of resonance `i` starts. It ignores inter-surface coupling and the vacuum, so it does not agree with the +physical `ForceFreeStatesResult.delta_prime`. """ function compute_delta_prime_from_ca!(odet::OdeState, intr::ForceFreeStatesInternal, equil::Equilibrium.PlasmaEquilibrium) denom = (2π)^2 * equil.psio # = twopi * chi1 in SingularCoupling.jl @@ -142,12 +143,8 @@ function compute_delta_prime_from_ca!(odet::OdeState, intr::ForceFreeStatesInter resize!(intr.sing[s].delta_prime, n_modes) for i in 1:n_modes ipert_res = 1 + sing.m[i] - intr.mlow + (sing.n[i] - intr.nlow) * intr.mpert - if 1 <= ipert_res <= intr.numpert_total - Δca = odet.ca_r[ipert_res, ipert_res, 2, s] - odet.ca_l[ipert_res, ipert_res, 2, s] - intr.sing[s].delta_prime[i] = Δca / denom - else - intr.sing[s].delta_prime[i] = 0.0 + 0.0im - end + column = 1 <= ipert_res <= intr.numpert_total ? findfirst(isone, @view odet.ca_r[ipert_res, :, 2, s]) : nothing + intr.sing[s].delta_prime[i] = column === nothing ? 0.0 + 0.0im : (1 - odet.ca_l[ipert_res, column, 2, s]) / denom end end end @@ -263,6 +260,7 @@ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil:: initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) chunks = chunk_el_integration_bounds(odet, ctrl, intr) + bases = ctrl.kinetic === nothing ? asymptotic_bases(chunks, ctrl, equil, mats, intr) : nothing if verbose @info " ψ = $((@sprintf "%.3f" odet.psifac)), q = $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac)))" @@ -279,7 +277,7 @@ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil:: if ctrl.kinetic !== nothing cross_kinetic_singular_surf!(odet, ctrl, equil, mats, intr, chunk.ising) else - cross_ideal_singular_surf!(odet, ctrl, equil, mats, intr, chunk.ising) + cross_ideal_singular_surf!(odet, ctrl, equil, intr, chunk.ising, bases[chunk.ising]) end end end @@ -297,6 +295,7 @@ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil:: # Undo Gaussian reduction to get true solution vectors transform_u!(odet, intr) + bases === nothing || fill_crossings!(odet, bases, crossing_fill_fractions(ctrl), equil, intr) return odet, nothing end @@ -553,44 +552,38 @@ function chunk_el_integration_bounds(odet::OdeState, ctrl::ForceFreeStatesContro end """ - cross_ideal_singular_surf!(odet, ctrl, equil, mats, intr, ising) + cross_ideal_singular_surf!(odet, ctrl, equil, intr, ising, basis) Cross ideal singular surface `ising` in its asymptotic basis [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]: the solutions are expanded in the left basis, the column carrying each resonance's big solution ends at the surface, the nonresonant coefficients continue into the right basis, and each small solution starts there in -the freed column. Records both coefficient sets in `odet.ca_l` and `odet.ca_r`, and the column reduction for -`transform_u!`. +the freed column. `basis` is the surface's entry of `asymptotic_bases`. Records both coefficient sets in +`odet.ca_l` and `odet.ca_r`, and the column reduction for `transform_u!`. """ function cross_ideal_singular_surf!( odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, - mats::MatrixSplines, intr::ForceFreeStatesInternal, - ising::Int + ising::Int, + basis ) singp = intr.sing[ising] - N = intr.numpert_total ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - dpsi = singp.psifac - odet.psifac # ψ_res - ψ (positive) - ua_left = sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0), dpsi) - ua_right = sing_get_ua(compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0), dpsi) # Reduce first: columns left nearly parallel by the integration would lose their difference in the basis change. compute_solution_norms!(odet.u, odet, ctrl, intr, true) - ca = sing_get_ca(odet.u, ua_left, intr) + ca = sing_get_ca(odet.u, basis.left, intr) + pivots, factors = eliminate_big_solutions!(ca, ipert_res) next_fixup!(odet, ctrl) - pivots = reduce_big_solutions!(ca, odet, ipert_res) + record_crossing!(odet, pivots, factors) odet.ca_l[:, :, :, ising] .= ca start_small_solutions!(ca, ipert_res, pivots) odet.ca_r[:, :, :, ising] .= ca odet.ca_populated = true - odet.psifac += 2 * dpsi - @views for k in 1:2 - mul!(odet.u[:, :, k], ua_right[:, 1:N, k], ca[:, :, 1]) - mul!(odet.u[:, :, k], ua_right[:, (N+1):(2N), k], ca[:, :, 2], 1, 1) - end + odet.psifac += 2 * basis.dpsi + state_from_basis!(odet.u, basis.right, [ca[:, :, 1]; ca[:, :, 2]]) # The next solver step records fresh reference norms. odet.new = true @@ -600,16 +593,14 @@ function cross_ideal_singular_surf!( end """ - reduce_big_solutions!(ca, odet, ipert_res) -> pivots + record_crossing!(odet, pivots, factors) -Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the -basis) so that one column carries the big solution of each resonance `ipert_res[i]`, and record the reduction as -fixup `odet.ifix` for `transform_u!`. Returns those columns. +Record the reduction `eliminate_big_solutions!` made at an ideal crossing as fixup `odet.ifix`, in the form +`transform_u!` undoes, with the `pivots` columns ending there. """ -function reduce_big_solutions!(ca::Array{ComplexF64,3}, odet::OdeState, ipert_res) +function record_crossing!(odet::OdeState, pivots::Vector{Int}, factors::Matrix{ComplexF64}) ifix = odet.ifix - N = size(ca, 2) - nres = length(ipert_res) + N = size(factors, 2) odet.sing_flag[ifix] = true # The previous region ends at the step before this fixup odet.fixstep[ifix] = odet.step - 1 @@ -617,23 +608,11 @@ function reduce_big_solutions!(ca::Array{ComplexF64,3}, odet::OdeState, ipert_re for isol in 1:N odet.fixfac[isol, isol, ifix] = 1 end - - col_free = trues(N) - for (i, ipert) in enumerate(ipert_res) - pivot = argmax(j -> col_free[j] ? abs(ca[ipert, j, 1]) : -Inf, 1:N) - odet.index[i, ifix] = pivot - col_free[pivot] = false - for j in findall(col_free) - factor = -ca[ipert, j, 1] / ca[ipert, pivot, 1] - odet.fixfac[pivot, j, ifix] = factor - @views ca[:, j, :] .+= factor .* ca[:, pivot, :] - ca[ipert, j, 1] = 0 - end + for (i, pivot) in enumerate(pivots) + @views odet.fixfac[pivot, :, ifix] .+= factors[i, :] end - odet.index[(nres+1):N, ifix] .= findall(col_free) - # transform_u! drops the columns that end at the surface - odet.zeroed_idx[ifix] = collect(1:nres) - return odet.index[1:nres, ifix] + odet.index[:, ifix] .= [pivots; setdiff(1:N, pivots)] + odet.zeroed_idx[ifix] = collect(eachindex(pivots)) end """ diff --git a/src/ForceFreeStates/ForceFreeStates.jl b/src/ForceFreeStates/ForceFreeStates.jl index 4f4e23356e..fcc155bedb 100644 --- a/src/ForceFreeStates/ForceFreeStates.jl +++ b/src/ForceFreeStates/ForceFreeStates.jl @@ -37,6 +37,7 @@ include("EulerLagrange.jl") # Singular-surface machinery: finding/filtering, Frobenius asymptotics, GGJ coefficients include("Surfaces/Finding.jl") include("Surfaces/Asymptotics.jl") +include("Surfaces/Crossing.jl") include("Surfaces/ResistEval.jl") # Outer<->inner resistive matching diff --git a/src/ForceFreeStates/Riccati/Crossings.jl b/src/ForceFreeStates/Riccati/Crossings.jl index eb421623ac..1729baf5ec 100644 --- a/src/ForceFreeStates/Riccati/Crossings.jl +++ b/src/ForceFreeStates/Riccati/Crossings.jl @@ -1,25 +1,4 @@ -# Singular-surface crossing of the Riccati integrator, in the asymptotic basis. - -""" - asymptotic_bases(chunks, ctrl, equil, mats, intr) -> Dict{Int,NamedTuple} - -Asymptotic basis `(; left, right)`, each N × 2N × 2, on both sides of every crossed surface, where its crossing -chunk ends, with the series they are evaluated from (`left_series`, `right_series`). Keyed by the surface's index -in `intr.sing`. -""" -function asymptotic_bases(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) - bases = Dict{Int,@NamedTuple{left::Array{ComplexF64,3}, right::Array{ComplexF64,3}, left_series::SingAsymptotics, right_series::SingAsymptotics}}() - for chunk in chunks - chunk.needs_crossing || continue - singp = intr.sing[chunk.ising] - dpsi = singp.psifac - chunk.psi_end - left_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0) - right_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0) - bases[chunk.ising] = (; left=sing_get_ua(left_series, dpsi), right=sing_get_ua(right_series, dpsi), left_series, right_series) - end - return bases -end +# Singular-surface crossing of the Riccati integrator. """ cross_singular_surface!(odet, intr, ising) -> Matrix{ComplexF64} @@ -32,58 +11,17 @@ columns on return to their continuation left of the surface, in the columns on e function cross_singular_surface!(odet::OdeState, intr::ForceFreeStatesInternal, ising::Int) singp = intr.sing[ising] ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert - continuation = eliminate_big_solutions!(odet.u, ipert_res) + pivots, factors = eliminate_big_solutions!(odet.u, ipert_res) odet.ca_l[:, :, :, ising] .= odet.u - start_small_solutions!(odet.u, ipert_res) + start_small_solutions!(odet.u, ipert_res, pivots) odet.ca_r[:, :, :, ising] .= odet.u odet.ca_populated = true - # The small solutions introduced on the right do not exist on the left. - continuation[:, ipert_res] .= 0 - return continuation -end - -""" - eliminate_big_solutions!(ca, ipert_res) -> Matrix{ComplexF64} -Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the -basis) so that only column `ipert_res[i]` carries the big solution of resonance `i`. Returns the N × N column -transformation applied. -""" -function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) - transform = Matrix{ComplexF64}(I, size(ca, 2), size(ca, 2)) - for (i, ipert) in enumerate(ipert_res) - candidates = setdiff(axes(ca, 2), @view ipert_res[1:(i-1)]) - pivot = candidates[argmax(abs.(@view ca[ipert, candidates, 1]))] - for col in axes(ca, 2) - col == pivot && continue - factor = ca[ipert, col, 1] / ca[ipert, pivot, 1] - @views ca[:, col, :] .-= factor .* ca[:, pivot, :] - @views transform[:, col] .-= factor .* transform[:, pivot] - ca[ipert, col, 1] = 0 - end - if pivot != ipert - swapped = ca[:, pivot, :] - @views ca[:, pivot, :] .= ca[:, ipert, :] - ca[:, ipert, :] .= swapped - transform[:, [pivot, ipert]] .= transform[:, [ipert, pivot]] - end + continuation = Matrix{ComplexF64}(I, size(odet.u, 2), size(odet.u, 2)) + for (i, pivot) in enumerate(pivots) + continuation .+= continuation[:, pivot] * transpose(@view factors[i, :]) end - return transform -end - -""" - start_small_solutions!(ca, ipert_res, columns=ipert_res) - -Turn reduced left-side coefficients `ca` into right-side ones: the resonant coefficients vanish and column -`columns[i]`, which carried the big solution of resonance `i`, becomes its small solution. -""" -function start_small_solutions!(ca::Array{ComplexF64,3}, ipert_res, columns=ipert_res) - for (ipert, column) in zip(ipert_res, columns) - ca[ipert, :, :] .= 0 - ca[:, column, :] .= 0 - end - for (ipert, column) in zip(ipert_res, columns) - ca[ipert, column, 2] = 1 - end - return ca + # The small solutions started on the right do not exist on the left. + continuation[:, pivots] .= 0 + return continuation end diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index 80a608e6a9..bd4c4bf4b5 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -45,6 +45,7 @@ function riccati_eulerlagrange_integration( end odet.nzero = evaluate_stability_criterion!(odet, equil.profiles) restore_solution_columns!(odet, propagators, chunks, columns) + fill_crossings!(odet, bases, crossing_fill_fractions(ctrl), equil, intr) return odet, (; propagators, chunks, columns, bases) end @@ -142,9 +143,7 @@ function store_propagated!(u_store::Array{ComplexF64,4}, propagators::Vector{Chu Threads.@threads for i in eachindex(propagators) u = zeros(ComplexF64, N, N, 2) for (j, k) in enumerate(stored[i]) - @views for half in 1:2 - mul!(u[:, :, half], propagators[i].steps[k][:, :, half], coefficients[i]) - end + state_from_basis!(u, propagators[i].steps[k], coefficients[i]) reduce && renormalize_riccati_inplace!(u, N) @views u_store[:, :, :, slots[i]+j] .= u end diff --git a/src/ForceFreeStates/Riccati/OuterBasis.jl b/src/ForceFreeStates/Riccati/OuterBasis.jl index a5b9384af0..79b387145c 100644 --- a/src/ForceFreeStates/Riccati/OuterBasis.jl +++ b/src/ForceFreeStates/Riccati/OuterBasis.jl @@ -1,11 +1,13 @@ # The solutions of the Δ' boundary-value problem on the stored radial grid. """ - outer_solution_basis(coefficients, propagators, chunks, columns, bases, surfaces, equil, mats, modes) -> OuterSolutionBasis + outer_solution_basis(coefficients, propagators, chunks, columns, bases, surfaces, equil, mats, modes, fill_fractions) + -> OuterSolutionBasis Rebuild the solutions of the Δ' boundary-value problem [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37] -at every stored step of the chunk propagators. The cut solution leaves out the leading-order big and small terms -over the two chunks next to each surface. +at every stored step of the chunk propagators and, inside the crossing distance of each surface, from its asymptotic +series at the fractions `fill_fractions` of that distance, big solution included. The cut solution leaves out the leading-order big and small +terms over the two chunks next to each surface. ### Arguments @@ -13,60 +15,84 @@ over the two chunks next to each surface. - `propagators`, `chunks`, `columns`, `bases`: From `riccati_eulerlagrange_integration`. - `surfaces`: The singular surfaces `chunks` index. - `modes`: Mode indexing. + - `fill_fractions`: From `crossing_fill_fractions`. """ function outer_solution_basis(coefficients::Matrix{ComplexF64}, propagators::Vector{ChunkPropagator}, chunks::Vector{IntegrationChunk}, columns, bases::AbstractDict, surfaces::Vector{SingType}, - equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices) + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, modes::ModeIndices, fill_fractions::Vector{Float64}) (; stored, slots) = columns N = modes.numpert_total nsol = size(coefficients, 2) - ngrid = slots[end] + i_crossings = findall(c -> c.needs_crossing, chunks) + nfill = 2 * length(fill_fractions) + ngrid = slots[end] + nfill * length(i_crossings) chunk_coefficients = basis_chunk_coefficients(coefficients, propagators, chunks, columns) psi = Vector{Float64}(undef, ngrid) q = Vector{Float64}(undef, ngrid) xi = Array{ComplexF64}(undef, N, ngrid, nsol) xi_deriv = Array{ComplexF64}(undef, N, ngrid, nsol) + # ξ and ξ′ of the state `u` at ψ, into `node`. + function store!(node, psi_node, u, du, hints) + psi[node] = psi_node + q[node] = el_derivatives!(du, u, false, equil, mats, modes, psi_node, hints...) + @views xi[:, node, :] .= u[:, :, 1] + @views xi_deriv[:, node, :] .= du[:, :, 1] + end nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try Threads.@threads for i in eachindex(chunks) - u = zeros(ComplexF64, N, nsol, 2) - du = zeros(ComplexF64, N, nsol, 2) - spline_hint, mats_hint = Ref(1), Ref(1) + # `local`: each task owns its work arrays. + local u = zeros(ComplexF64, N, nsol, 2) + local du = zeros(ComplexF64, N, nsol, 2) + local hints = (Ref(1), Ref(1)) for (j, k) in enumerate(stored[i]) - node = slots[i] + j - psi[node] = propagators[i].psi[k] - @views for half in 1:2 - mul!(u[:, :, half], propagators[i].steps[k][:, :, half], chunk_coefficients[i]) - end - q[node] = el_derivatives!(du, u, false, equil, mats, modes, psi[node], spline_hint, mats_hint) - @views xi[:, node, :] .= u[:, :, 1] - @views xi_deriv[:, node, :] .= du[:, :, 1] + store!(slots[i] + j, propagators[i].psi[k], state_from_basis!(u, propagators[i].steps[k], chunk_coefficients[i]), du, hints) end end finally BLAS.set_num_threads(nblas) end - i_crossings = findall(c -> c.needs_crossing, chunks) - xi_cut = copy(xi) + # Inside the crossing distance the solutions are their series on each side, with every coefficient they carry. + series_du = zeros(ComplexF64, N, nsol, 2) + series_hints = (Ref(1), Ref(1)) + node = slots[end] + for ic in i_crossings + surface = surfaces[chunks[ic].ising] + basis = bases[chunks[ic].ising] + for (sig, series, i) in ((-1.0, basis.left_series, ic), (1.0, basis.right_series, ic + 1)) + for (psi_node, u) in crossing_fill(series, chunk_coefficients[i], surface.psifac, sig, basis.dpsi, fill_fractions) + node += 1 + store!(node, psi_node, u, series_du, series_hints) + end + end + end + order = sortperm(psi) + grid = psi[order] + xi_grid = xi[:, order, :] + + xi_cut = copy(xi_grid) cut_range = Matrix{Float64}(undef, length(i_crossings), 2) for (j, ic) in enumerate(i_crossings) surface = surfaces[chunks[ic].ising] ipert = 1 + surface.m[1] - modes.mlow + (surface.n[1] - modes.nlow) * modes.mpert cut_range[j, 1] = chunks[ic].psi_start cut_range[j, 2] = chunks[ic+1].psi_end - for (i, series) in ((ic, bases[chunks[ic].ising].left_series), (ic + 1, bases[chunks[ic].ising].right_series)) + basis = bases[chunks[ic].ising] + sides = ((basis.left_series, ic, findall(p -> cut_range[j, 1] <= p < surface.psifac, grid)), + (basis.right_series, ic + 1, findall(p -> surface.psifac < p <= cut_range[j, 2], grid))) + for (series, i, nodes) in sides big = transpose(@view chunk_coefficients[i][ipert, :]) small = transpose(@view chunk_coefficients[i][ipert+N, :]) - for node in (slots[i]+1):slots[i+1] - leading = sing_get_ua_res_cut(series, abs(psi[node] - surface.psifac)) + for node in nodes + leading = sing_get_ua_res_cut(series, abs(grid[node] - surface.psifac)) @views xi_cut[:, node, :] .-= leading[:, 1, 1] .* big .+ leading[:, 2, 1] .* small end end end - return OuterSolutionBasis(psi, q, fill(false, ngrid), xi, xi_deriv, xi_cut, cut_range) + return OuterSolutionBasis(grid, q[order], fill(false, ngrid), xi_grid, xi_deriv[:, order, :], xi_cut, cut_range) end """ diff --git a/src/ForceFreeStates/Riccati/Propagators.jl b/src/ForceFreeStates/Riccati/Propagators.jl index 65662fd779..eb4200cffa 100644 --- a/src/ForceFreeStates/Riccati/Propagators.jl +++ b/src/ForceFreeStates/Riccati/Propagators.jl @@ -57,10 +57,7 @@ end Multiply `odet.u` by the chunk propagator `prop` [Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507, Eq. 29]. """ function apply_propagator!(odet::OdeState, prop::ChunkPropagator) - x = [odet.u[:, :, 1]; odet.u[:, :, 2]] - @views for k in 1:2 - mul!(odet.u[:, :, k], prop.u[:, :, k], x) - end + state_from_basis!(odet.u, prop.u, [odet.u[:, :, 1]; odet.u[:, :, 2]]) end """ diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 42c1855c4c..294a158f16 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -106,7 +106,7 @@ function run_force_free_states( wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) if coefficients !== nothing basis = outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, - intr.sing, equil, mats, ModeIndices(intr)) + intr.sing, equil, mats, ModeIndices(intr), crossing_fill_fractions(ctrl)) end end end diff --git a/src/ForceFreeStates/Surfaces/Crossing.jl b/src/ForceFreeStates/Surfaces/Crossing.jl new file mode 100644 index 0000000000..4582248c8f --- /dev/null +++ b/src/ForceFreeStates/Surfaces/Crossing.jl @@ -0,0 +1,151 @@ +# Crossing an ideal singular surface through its asymptotic series: the parts the ODE integrators share. + +""" + asymptotic_bases(chunks, ctrl, equil, mats, intr) -> Dict{Int,NamedTuple} + +For every crossed surface, keyed by its index in `intr.sing`: the distance `dpsi` from it at which its crossing chunk +ends, the asymptotic series on each side (`left_series`, `right_series`), and those series evaluated at `dpsi` +(`left`, `right`, each N × 2N × 2). +""" +function asymptotic_bases(chunks::Vector{IntegrationChunk}, ctrl::ForceFreeStatesControl, + equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) + bases = Dict{Int, + @NamedTuple{dpsi::Float64, left::Array{ComplexF64,3}, right::Array{ComplexF64,3}, left_series::SingAsymptotics, right_series::SingAsymptotics}}() + for chunk in chunks + chunk.needs_crossing || continue + singp = intr.sing[chunk.ising] + dpsi = singp.psifac - chunk.psi_end + left_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=-1.0) + right_series = compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0) + bases[chunk.ising] = (; dpsi, left=sing_get_ua(left_series, dpsi), right=sing_get_ua(right_series, dpsi), left_series, right_series) + end + return bases +end + +""" + state_from_basis!(u, basis, coefficients) -> u + +State `u` (N × ncol × 2) of the solutions `basis · coefficients`, for a `basis` (N × 2N × 2) of 2N solutions and +`coefficients` (2N × ncol). +""" +function state_from_basis!(u::AbstractArray{ComplexF64,3}, basis::AbstractArray{ComplexF64,3}, coefficients::AbstractMatrix{ComplexF64}) + @views for half in 1:2 + mul!(u[:, :, half], basis[:, :, half], coefficients) + end + return u +end + +""" + eliminate_big_solutions!(ca, ipert_res) -> (pivots, factors) + +Column-reduce the asymptotic coefficients `ca` (N × N × 2: basis solution, solution, big or small half of the +basis) so that one column, `pivots[i]`, carries the big solution of each resonance `ipert_res[i]`. `factors[i, j]` +is the multiple of that column added to column `j`. +""" +function eliminate_big_solutions!(ca::Array{ComplexF64,3}, ipert_res) + N = size(ca, 2) + pivots = Int[] + factors = zeros(ComplexF64, length(ipert_res), N) + free = trues(N) + for (i, ipert) in enumerate(ipert_res) + pivot = argmax(j -> free[j] ? abs(ca[ipert, j, 1]) : -Inf, 1:N) + push!(pivots, pivot) + free[pivot] = false + for j in findall(free) + factors[i, j] = -ca[ipert, j, 1] / ca[ipert, pivot, 1] + @views ca[:, j, :] .+= factors[i, j] .* ca[:, pivot, :] + ca[ipert, j, 1] = 0 + end + end + return pivots, factors +end + +""" + start_small_solutions!(ca, ipert_res, pivots) + +Turn reduced left-side coefficients `ca` into right-side ones [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, +Eq. 36]: the resonant coefficients vanish and column `pivots[i]`, which carried the big solution of resonance `i`, +becomes its small solution. +""" +function start_small_solutions!(ca::Array{ComplexF64,3}, ipert_res, pivots) + for (ipert, pivot) in zip(ipert_res, pivots) + ca[ipert, :, :] .= 0 + ca[:, pivot, :] .= 0 + end + for (ipert, pivot) in zip(ipert_res, pivots) + ca[ipert, pivot, 2] = 1 + end + return ca +end + +""" + crossing_fill_fractions(ctrl) -> Vector{Float64} + +Distances from a crossed surface, as fractions of the crossing distance, of the states the asymptotic series adds: +`ctrl.crossing_fill_points` values, log-spaced down to `ctrl.crossing_fill_min / ctrl.singfac_min`. +""" +function crossing_fill_fractions(ctrl::ForceFreeStatesControl) + n = ctrl.crossing_fill_points + (n > 0 && 0 < ctrl.crossing_fill_min < ctrl.singfac_min) || return Float64[] + return (ctrl.crossing_fill_min / ctrl.singfac_min) .^ ((1:n) ./ n) +end + +""" + crossing_fill(series, coefficients, psifac, sig, dpsi, fractions) -> Vector{Tuple{Float64,Array{ComplexF64,3}}} + +ψ and state (N × ncol × 2), at the distances `fractions .* dpsi` from the surface at `psifac` on side `sig` (-1 +left, +1 right), of the solutions with asymptotic `coefficients` (2N × ncol) in the `series` of that side +[Glasser 2016, Phys. Plasmas 23, 112506, Eq. 45]. +""" +function crossing_fill(series::SingAsymptotics, coefficients::AbstractMatrix{ComplexF64}, psifac::Float64, sig::Float64, + dpsi::Float64, fractions::Vector{Float64}) + N = size(series.vmat, 1) + return [ + (psifac + sig * fraction * dpsi, state_from_basis!(zeros(ComplexF64, N, size(coefficients, 2), 2), sing_get_ua(series, fraction * dpsi), coefficients)) + for fraction in fractions + ] +end + +""" + fill_crossings!(odet, bases, fractions, equil, intr) + +Add states to the integrator's stored solution inside the crossing distance of every crossed surface, on both sides, +at `fractions` of that distance (`crossing_fill`). That solution is the ideal one, so its big-solution coefficient +is set to zero; solutions that carry a big solution are filled by `outer_solution_basis`. `crit_store` is +interpolated linearly across each surface. +""" +function fill_crossings!(odet::OdeState, bases::AbstractDict, fractions::Vector{Float64}, equil::Equilibrium.PlasmaEquilibrium, + intr::ForceFreeStatesInternal) + isempty(fractions) && return + nstep = odet.step + filled = Tuple{Float64,Array{ComplexF64,3}}[] + crit_fill = Float64[] + for (ising, basis) in bases + ising <= intr.msing || continue + singp = intr.sing[ising] + left = searchsortedlast(@view(odet.psi_store[1:nstep]), singp.psifac) + # Only surfaces the stored solution stops at on both sides. + (1 <= left < nstep && isapprox(singp.psifac - odet.psi_store[left], basis.dpsi; rtol=1e-9) && + isapprox(odet.psi_store[left+1] - singp.psifac, basis.dpsi; rtol=1e-9)) || continue + ipert_res = 1 .+ singp.m .- intr.mlow .+ (singp.n .- intr.nlow) .* intr.mpert + for (sig, node, ua, series) in ((-1.0, left, basis.left, basis.left_series), (1.0, left + 1, basis.right, basis.right_series)) + ca = sing_get_ca(odet.u_store[:, :, :, node], ua, intr) + ca[ipert_res, :, 1] .= 0 + points = crossing_fill(series, [ca[:, :, 1]; ca[:, :, 2]], singp.psifac, sig, basis.dpsi, fractions) + append!(filled, points) + for (psi, _) in points + weight = (psi - odet.psi_store[left]) / (odet.psi_store[left+1] - odet.psi_store[left]) + push!(crit_fill, (1 - weight) * odet.crit_store[left] + weight * odet.crit_store[left+1]) + end + end + end + isempty(filled) && return + + psi = [odet.psi_store[1:nstep]; first.(filled)] + order = sortperm(psi) + odet.psi_store = psi[order] + odet.crit_store = [odet.crit_store[1:nstep]; crit_fill][order] + odet.q_store = equil.profiles.q_spline.(odet.psi_store) + odet.u_store = cat(odet.u_store[:, :, :, 1:nstep], last.(filled)...; dims=4)[:, :, :, order] + odet.step = length(order) +end diff --git a/test/runtests_eulerlagrange.jl b/test/runtests_eulerlagrange.jl index f09f957912..2907961530 100644 --- a/test/runtests_eulerlagrange.jl +++ b/test/runtests_eulerlagrange.jl @@ -400,22 +400,23 @@ end ca0[:, 2, 1] .= [0.4, 0.3, 5.0] ca0[:, 3, 1] .= [0.2, 2.0, 1.5] ca0[:, :, 2] .= [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0] - odet = FFS.OdeState(3, 10, 10, 1) - odet.ifix = 1 ca = copy(ca0) - pivots = FFS.reduce_big_solutions!(ca, odet, [3]) - @test pivots == [2] && odet.index[:, 1] == [2, 1, 3] - @test odet.sing_flag[1] && odet.zeroed_idx[1] == [1] + pivots, factors = FFS.eliminate_big_solutions!(ca, [3]) + @test pivots == [2] && factors[1, 2] == 0 @test ca[3, 1, 1] == 0 && ca[3, 3, 1] == 0 && ca[:, 2, :] == ca0[:, 2, :] - # The recorded factors are the reduction transform_u! undoes: column j gained fixfac[2, j] times column 2. for j in (1, 3) - @test ca[:, j, :] ≈ ca0[:, j, :] .+ odet.fixfac[2, j, 1] .* ca0[:, 2, :] + @test ca[:, j, :] ≈ ca0[:, j, :] .+ factors[1, j] .* ca0[:, 2, :] end + # Forward records it in the form transform_u! undoes, with the pivot column ending at the surface. + odet = FFS.OdeState(3, 10, 10, 1) + odet.ifix = 1 + FFS.record_crossing!(odet, pivots, factors) + @test odet.index[:, 1] == [2, 1, 3] && odet.sing_flag[1] && odet.zeroed_idx[1] == [1] + @test odet.fixfac[2, :, 1] == [factors[1, 1], 1, factors[1, 3]] # Right of the surface the freed column is the small solution and no other column has a resonant coefficient. FFS.start_small_solutions!(ca, [3], pivots) @test all(iszero, ca[3, [1, 3], :]) @test ca[:, 2, 1] == zeros(3) && ca[:, 2, 2] == [0, 0, 1] - @test ca[1:2, [1, 3], :] ≈ (ca0[:, [1, 3], :].+reshape(odet.fixfac[2, [1, 3], 1], 1, 2, 1).*ca0[:, [2], :])[1:2, :, :] end @testset "OdeState construction" begin diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index 59dcfb6395..bcb62bccb1 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -120,6 +120,18 @@ end @test isapprox(direct, odet_ric.u_store[:, :, :, k+1]; rtol=1e-5) end + # Inside the crossing distance of each surface the stored states come from its asymptotic series, and they + # continue the integrated solution: integrating from where the integration stopped lands on the first of them. + for s in intr_ric.sing + near = findall(p -> abs(p - s.psifac) < (1 - 1e-9) * ctrl.singfac_min / abs(s.n[1] * s.q1), psi) + @test length(near) == 2 * ctrl.crossing_fill_points + k = first(near) - 1 + params = (ctrl, equil, mats, intr_ric, FFS.OdeState(N, 1, 1, 0), FFS.IntegrationChunk(psi[k], psi[k+1], false, 0, 1)) + direct = FFS.solve_el(FFS.ODEProblem(FFS.sing_der!, odet_ric.u_store[:, :, :, k], (psi[k], psi[k+1]), params), + ctrl.algorithm.eulerlagrange_tolerance).u[end] + @test isapprox(direct, odet_ric.u_store[:, :, :, k+1]; rtol=1e-5) + end + # They are the solutions Forward stores: scaled to a unit edge displacement, ξ and its conjugate momentum # agree at the nodes the two integrators share, which lie on each side of every surface. function edge_scaled(integrator) @@ -171,7 +183,7 @@ end wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv delta_prime, coefficients = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) basis = FFS.outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, - FFS.ModeIndices(intr)) + FFS.ModeIndices(intr), FFS.crossing_fill_fractions(ctrl)) N, msing = intr.numpert_total, intr.msing ideal = (2msing+1):(2msing+N) @test basis.psi == odet.psi_store && size(basis.xi) == size(basis.xi_deriv) == size(basis.xi_cut) == (N, odet.step, 2msing + N) @@ -210,7 +222,18 @@ end wv=free.wv, wp=free.wp, psio=equil.psio) @test size(delta_prime.matrix) == (intr.msing, intr.msing) && all(isfinite, delta_prime.matrix) @test size(delta_prime.coil) == (2 * intr.msing, intr.numpert_total) - basis = FFS.outer_solution_basis(coefficients, propagators, chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, FFS.ModeIndices(intr)) + basis = FFS.outer_solution_basis( + coefficients, + propagators, + chunks, + riccati.columns, + riccati.bases, + intr.sing, + equil, + mats, + FFS.ModeIndices(intr), + FFS.crossing_fill_fractions(ctrl) + ) @test basis.psi == odet.psi_store && all(isfinite, basis.xi) @test_logs (:warn, r"differs from the axis-to-edge one") FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=1.01 .* free.wp, psio=equil.psio) diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 941750475f..eb0d4d85d3 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -547,6 +547,25 @@ include("display_check.jl") end end + @testset "states filled in from the asymptotic series next to each surface" begin + ffs_overrides = Dict{String,Any}("singfac_min" => 5e-4, "crossing_fill_points" => 3, "crossing_fill_min" => 2e-5, "vac_flag" => false) + mktempdir() do dir + reference = GPEC.main([_stage_deck(dir; ffs_overrides=ffs_overrides)]).ffs + kwargs = merge(ffs_kwargs, Dict(Symbol(k) => v for (k, v) in ffs_overrides)) + api = solve(equil, forward; nn=1, wall=wall, kwargs...) + @test api.solution.psi_store == reference.solution.psi_store + @test api.solution.u_store ≈ reference.solution.u_store rtol = 1e-12 + # Three states on each side, the closest at crossing_fill_min, and none when switched off. + distance(sol, s) = abs.(sol.psi_store .- s.psifac) .* abs(s.n[1] * s.q1) + for s in api.surfaces + inside = filter(<(5e-4 * (1 - 1e-9)), distance(api.solution, s)) + @test length(inside) == 6 && minimum(inside) ≈ 2e-5 + end + bare = solve(equil, forward; nn=1, wall=wall, merge(kwargs, Dict{Symbol,Any}(:crossing_fill_points => 0))...) + @test all(s -> minimum(distance(bare.solution, s)) ≈ 5e-4, bare.surfaces) + end + end + @testset "deck matching under [Match]" begin layer = (eta=1e-7, rho=1e-7, rotation=1.0) # The deck's [Match] section for `n` surfaces and the [GGJ] solver. From 07cf80d5de27e96893083f7fac2bfe95f8578615 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Tue, 17 Nov 2026 13:38:59 +0100 Subject: [PATCH 09/27] ForceFreeStates - PERF - Schedule the Riccati chunk loops greedily and thread the edge-scan vacuum matrices and the fixed-boundary criterion --- src/ForceFreeStates/FixedBoundaryStability.jl | 70 +++++++------------ src/ForceFreeStates/Free.jl | 21 +++++- src/ForceFreeStates/Riccati/Driver.jl | 7 +- src/ForceFreeStates/Riccati/OuterBasis.jl | 45 ++++++------ src/ForceFreeStates/Surfaces/Crossing.jl | 11 ++- 5 files changed, 78 insertions(+), 76 deletions(-) diff --git a/src/ForceFreeStates/FixedBoundaryStability.jl b/src/ForceFreeStates/FixedBoundaryStability.jl index 29896ac3db..297215a57e 100644 --- a/src/ForceFreeStates/FixedBoundaryStability.jl +++ b/src/ForceFreeStates/FixedBoundaryStability.jl @@ -8,19 +8,21 @@ non-Hermitian beyond tolerance at any step. function evaluate_stability_criterion!(odet::OdeState, profiles::Equilibrium.ProfileSplines) resize!(odet.crit_store, odet.step) - nzero = 0 - nonherm_count = 0 - - for istep in 1:odet.step - zero_cross, nonherm = check_for_zero_crossings!(odet, profiles, istep) - if zero_cross - nzero += 1 - end - if nonherm - nonherm_count += 1 + nonherm = fill(false, odet.step) + # The criterion of each stored state is independent of the others. + nblas = BLAS.get_num_threads() + BLAS.set_num_threads(1) + try + Threads.@threads for istep in 1:odet.step + crit, nonherm[istep] = compute_smallest_eigenvalue(@view odet.u_store[:, :, :, istep]) + odet.crit_store[istep] = crit * profiles.dVdpsi_spline(odet.psi_store[istep])^2 end + finally + BLAS.set_num_threads(nblas) end + nzero = count(istep -> is_zero_crossing(odet, profiles, istep), 2:odet.step) + nonherm_count = count(nonherm) if nonherm_count > 0 @warn "W inverse matrix was non-Hermitian beyond tolerance at $nonherm_count integration step(s)" end @@ -29,43 +31,23 @@ function evaluate_stability_criterion!(odet::OdeState, profiles::Equilibrium.Pro end """ - check_for_zero_crossings!(odet, profiles, istep) -> zero_cross, nonherm - -Compute `crit` (smallest-magnitude eigenvalue of W⁻¹, scaled by (dV/dψ)²) at step `istep` into -`odet.crit_store`, and report whether it changed sign since the previous step. A sign change counts -only if the interpolated midpoint confirms it is a genuine crossing rather than noise. - -### Returns + is_zero_crossing(odet, profiles, istep) -> Bool - - `zero_cross::Bool`: True if a physical zero crossing was detected - - `nonherm::Bool`: True if W⁻¹ was non-Hermitian beyond tolerance +Whether `odet.crit_store` (the smallest-magnitude eigenvalue of W⁻¹, scaled by (dV/dψ)²) changes sign between steps +`istep - 1` and `istep` at a genuine crossing rather than noise: its value at the interpolated crossing must lie +between its two neighbors and well below both. """ -@with_pool pool function check_for_zero_crossings!(odet::OdeState, profiles::Equilibrium.ProfileSplines, istep::Int) - - u = acquire!(pool, eltype(odet.u_store), size(odet.u_store)[1:3]) +function is_zero_crossing(odet::OdeState, profiles::Equilibrium.ProfileSplines, istep::Int) + crit, crit_prev = odet.crit_store[istep], odet.crit_store[istep-1] + crit * crit_prev < 0 || return false psi = odet.psi_store[istep] - u .= odet.u_store[:, :, :, istep] - dVdpsi = profiles.dVdpsi_spline(psi; hint=odet.spline_hint) - crit_val, nonherm = compute_smallest_eigenvalue(u) - odet.crit_store[istep] = crit_val * dVdpsi^2 - - zero_cross = false - if istep > 1 && odet.crit_store[istep] * odet.crit_store[istep-1] < 0 - crit = odet.crit_store[istep] - crit_prev = odet.crit_store[istep-1] - # Reject noise: crit at the interpolated crossing must lie between and well below both neighbors - fac = crit / (crit - crit_prev) - psi_mid = psi - fac * (psi - odet.psi_store[istep-1]) - u_mid = u .- fac .* (u .- @view(odet.u_store[:, :, :, istep-1])) - dVdpsi = profiles.dVdpsi_spline(psi_mid; hint=odet.spline_hint) - crit_mid_val, _ = compute_smallest_eigenvalue(u_mid) - crit_mid = crit_mid_val * dVdpsi^2 - if (crit_mid - crit) * (crit_mid - crit_prev) < 0 && abs(crit_mid) < 0.5 * min(abs(crit), abs(crit_prev)) - zero_cross = true - @info "Zero crossing detected at ψ = $(@sprintf("%.3f", psi_mid))" - end - end - return zero_cross, nonherm + fac = crit / (crit - crit_prev) + psi_mid = psi - fac * (psi - odet.psi_store[istep-1]) + u_mid = @views odet.u_store[:, :, :, istep] .- fac .* (odet.u_store[:, :, :, istep] .- odet.u_store[:, :, :, istep-1]) + crit_mid = first(compute_smallest_eigenvalue(u_mid)) * profiles.dVdpsi_spline(psi_mid; hint=odet.spline_hint)^2 + confirmed = (crit_mid - crit) * (crit_mid - crit_prev) < 0 && abs(crit_mid) < 0.5 * min(abs(crit), abs(crit_prev)) + confirmed && @info "Zero crossing detected at ψ = $(@sprintf("%.3f", psi_mid))" + return confirmed end """ diff --git a/src/ForceFreeStates/Free.jl b/src/ForceFreeStates/Free.jl index 0d971fa07f..619e4d6a19 100644 --- a/src/ForceFreeStates/Free.jl +++ b/src/ForceFreeStates/Free.jl @@ -224,11 +224,26 @@ for fast evaluation in `free_compute_total` during the edge dW scan. psi -> profiles.q_deriv(psi)), psii, Roots.Newton() ) + end - # Compute raw vacuum matrix at the actual scan psi (singfac NOT applied; free_compute_total applies it analytically) + # Raw vacuum matrix at each scan psi (singfac NOT applied; free_compute_total applies it analytically) + function vacuum_matrix!(i) vac_inputs = Vacuum.VacuumInput(equil, psi_array[i], ctrl.mtheta_vacuum, ctrl.nzeta_vacuum, intr.mlow:intr.mhigh, intr.nlow:intr.nhigh) - vac = Vacuum.compute_vacuum_response(vac_inputs, intr.wall_settings) - @views wv_array[i, :, :] .= vac.wv + @views wv_array[i, :, :] .= Vacuum.compute_vacuum_response(vac_inputs, intr.wall_settings).wv + end + if ctrl.nzeta_vacuum == 1 + # The matrices are independent, so each is its own task. The 3D kernel threads internally instead. + nblas = BLAS.get_num_threads() + BLAS.set_num_threads(1) + try + Threads.@threads :greedy for i in 1:(npsi+1) + vacuum_matrix!(i) + end + finally + BLAS.set_num_threads(nblas) + end + else + foreach(vacuum_matrix!, 1:(npsi+1)) end # Flatten 3D array to (npsi+1 × numpert_total^2) for series interpolant diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index bd4c4bf4b5..57b892408a 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -69,7 +69,8 @@ function chunk_propagators(chunks::Vector{IntegrationChunk}, bases::AbstractDict nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try - Threads.@threads for i in eachindex(chunks) + # Chunks differ in cost, so each task takes the next one when it is free. + Threads.@threads :greedy for i in eachindex(chunks) propagators[i] = chunk_propagator(chunks[i], propagator_start(chunks, i, bases, modes.numpert_total), rtol, equil, mats, modes) end finally @@ -82,7 +83,7 @@ end # `dW_edge_scan_start` on, and the upper end. `after_crossing` adds the first, the state right of the surface. function stored_step_indices(prop::ChunkPropagator, chunk::IntegrationChunk, after_crossing::Bool, ctrl::ForceFreeStatesControl) nstep = length(prop.psi) - order = chunk.direction == 1 ? ((after_crossing ? 1 : 2):nstep) : ((nstep-1):-1:1) + order = chunk.direction == 1 ? ((after_crossing ? 1 : 2):1:nstep) : ((nstep-1):-1:1) return [k for (i, k) in enumerate(order) if i == length(order) || i % ctrl.algorithm.save_interval == 0 || prop.psi[k] >= ctrl.dW_edge_scan_start] end @@ -140,7 +141,7 @@ function store_propagated!(u_store::Array{ComplexF64,4}, propagators::Vector{Chu nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try - Threads.@threads for i in eachindex(propagators) + Threads.@threads :greedy for i in eachindex(propagators) u = zeros(ComplexF64, N, N, 2) for (j, k) in enumerate(stored[i]) state_from_basis!(u, propagators[i].steps[k], coefficients[i]) diff --git a/src/ForceFreeStates/Riccati/OuterBasis.jl b/src/ForceFreeStates/Riccati/OuterBasis.jl index 79b387145c..a23cf190ca 100644 --- a/src/ForceFreeStates/Riccati/OuterBasis.jl +++ b/src/ForceFreeStates/Riccati/OuterBasis.jl @@ -24,10 +24,21 @@ function outer_solution_basis(coefficients::Matrix{ComplexF64}, propagators::Vec N = modes.numpert_total nsol = size(coefficients, 2) i_crossings = findall(c -> c.needs_crossing, chunks) - nfill = 2 * length(fill_fractions) - ngrid = slots[end] + nfill * length(i_crossings) chunk_coefficients = basis_chunk_coefficients(coefficients, propagators, chunks, columns) + # Inside the crossing distance the solutions are their series on each side, with every coefficient they carry. + fills = Tuple{Float64,Array{ComplexF64,3}}[] + for ic in i_crossings + surface = surfaces[chunks[ic].ising] + basis = bases[chunks[ic].ising] + for (sig, series, i) in ((-1.0, basis.left_series, ic), (1.0, basis.right_series, ic + 1)) + append!(fills, crossing_fill(series, chunk_coefficients[i], surface.psifac, sig, basis.dpsi, fill_fractions)) + end + end + # Where each node, the stored steps of every chunk and then the series nodes, falls on the grid sorted in ψ. + place = invperm(sortperm([[propagators[i].psi[k] for i in eachindex(chunks) for k in stored[i]]; first.(fills)])) + ngrid = length(place) + psi = Vector{Float64}(undef, ngrid) q = Vector{Float64}(undef, ngrid) xi = Array{ComplexF64}(undef, N, ngrid, nsol) @@ -42,38 +53,26 @@ function outer_solution_basis(coefficients::Matrix{ComplexF64}, propagators::Vec nblas = BLAS.get_num_threads() BLAS.set_num_threads(1) try - Threads.@threads for i in eachindex(chunks) + Threads.@threads :greedy for i in eachindex(chunks) # `local`: each task owns its work arrays. local u = zeros(ComplexF64, N, nsol, 2) local du = zeros(ComplexF64, N, nsol, 2) local hints = (Ref(1), Ref(1)) for (j, k) in enumerate(stored[i]) - store!(slots[i] + j, propagators[i].psi[k], state_from_basis!(u, propagators[i].steps[k], chunk_coefficients[i]), du, hints) + store!(place[slots[i]+j], propagators[i].psi[k], state_from_basis!(u, propagators[i].steps[k], chunk_coefficients[i]), du, hints) end end finally BLAS.set_num_threads(nblas) end - # Inside the crossing distance the solutions are their series on each side, with every coefficient they carry. series_du = zeros(ComplexF64, N, nsol, 2) series_hints = (Ref(1), Ref(1)) - node = slots[end] - for ic in i_crossings - surface = surfaces[chunks[ic].ising] - basis = bases[chunks[ic].ising] - for (sig, series, i) in ((-1.0, basis.left_series, ic), (1.0, basis.right_series, ic + 1)) - for (psi_node, u) in crossing_fill(series, chunk_coefficients[i], surface.psifac, sig, basis.dpsi, fill_fractions) - node += 1 - store!(node, psi_node, u, series_du, series_hints) - end - end + for (k, (psi_node, u)) in enumerate(fills) + store!(place[slots[end]+k], psi_node, u, series_du, series_hints) end - order = sortperm(psi) - grid = psi[order] - xi_grid = xi[:, order, :] - xi_cut = copy(xi_grid) + xi_cut = copy(xi) cut_range = Matrix{Float64}(undef, length(i_crossings), 2) for (j, ic) in enumerate(i_crossings) surface = surfaces[chunks[ic].ising] @@ -81,18 +80,18 @@ function outer_solution_basis(coefficients::Matrix{ComplexF64}, propagators::Vec cut_range[j, 1] = chunks[ic].psi_start cut_range[j, 2] = chunks[ic+1].psi_end basis = bases[chunks[ic].ising] - sides = ((basis.left_series, ic, findall(p -> cut_range[j, 1] <= p < surface.psifac, grid)), - (basis.right_series, ic + 1, findall(p -> surface.psifac < p <= cut_range[j, 2], grid))) + sides = ((basis.left_series, ic, findall(p -> cut_range[j, 1] <= p < surface.psifac, psi)), + (basis.right_series, ic + 1, findall(p -> surface.psifac < p <= cut_range[j, 2], psi))) for (series, i, nodes) in sides big = transpose(@view chunk_coefficients[i][ipert, :]) small = transpose(@view chunk_coefficients[i][ipert+N, :]) for node in nodes - leading = sing_get_ua_res_cut(series, abs(grid[node] - surface.psifac)) + leading = sing_get_ua_res_cut(series, abs(psi[node] - surface.psifac)) @views xi_cut[:, node, :] .-= leading[:, 1, 1] .* big .+ leading[:, 2, 1] .* small end end end - return OuterSolutionBasis(grid, q[order], fill(false, ngrid), xi_grid, xi_deriv[:, order, :], xi_cut, cut_range) + return OuterSolutionBasis(psi, q, fill(false, ngrid), xi, xi_deriv, xi_cut, cut_range) end """ diff --git a/src/ForceFreeStates/Surfaces/Crossing.jl b/src/ForceFreeStates/Surfaces/Crossing.jl index 4582248c8f..fe325f387b 100644 --- a/src/ForceFreeStates/Surfaces/Crossing.jl +++ b/src/ForceFreeStates/Surfaces/Crossing.jl @@ -116,7 +116,7 @@ interpolated linearly across each surface. """ function fill_crossings!(odet::OdeState, bases::AbstractDict, fractions::Vector{Float64}, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) - isempty(fractions) && return + isempty(fractions) && return nothing nstep = odet.step filled = Tuple{Float64,Array{ComplexF64,3}}[] crit_fill = Float64[] @@ -139,13 +139,18 @@ function fill_crossings!(odet::OdeState, bases::AbstractDict, fractions::Vector{ end end end - isempty(filled) && return + isempty(filled) && return nothing psi = [odet.psi_store[1:nstep]; first.(filled)] order = sortperm(psi) odet.psi_store = psi[order] odet.crit_store = [odet.crit_store[1:nstep]; crit_fill][order] odet.q_store = equil.profiles.q_spline.(odet.psi_store) - odet.u_store = cat(odet.u_store[:, :, :, 1:nstep], last.(filled)...; dims=4)[:, :, :, order] + u_store = similar(odet.u_store, size(odet.u_store)[1:3]..., length(order)) + for (k, node) in enumerate(order) + @views u_store[:, :, :, k] .= node <= nstep ? odet.u_store[:, :, :, node] : last(filled[node-nstep]) + end + odet.u_store = u_store odet.step = length(order) + return nothing end From 8fc6c5c3e152ed4a3c5e13ca27e861a3d4f248c9 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 18 Nov 2026 21:23:05 +0100 Subject: [PATCH 10/27] =?UTF-8?q?ForceFreeStates=20-=20BUGFIX!=20-=20Defau?= =?UTF-8?q?lt=20kinetic=20runs=20to=20a=201e-5=20crossing=20distance=20and?= =?UTF-8?q?=20Riccati=20to=20a=201e-10=20tolerance,=20warn=20where=20?= =?UTF-8?q?=CE=94=E2=80=B2=20is=20unresolved,=20and=20bracket=20the=20edge?= =?UTF-8?q?-scan=20root-find?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- regression-harness/cases/diiid_multi_n.toml | 3 ++- regression-harness/cases/diiid_n1.toml | 3 ++- src/ForceFreeStates/CoreTypes.jl | 16 ++++++++++---- src/ForceFreeStates/EulerLagrange.jl | 3 ++- src/ForceFreeStates/Free.jl | 13 ++++-------- src/ForceFreeStates/Integrators.jl | 4 ++-- src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl | 22 ++++++++++++++++++++ src/ForceFreeStates/Run.jl | 1 + test/runtests_eulerlagrange.jl | 8 +++++++ test/runtests_parallel_integration.jl | 4 ++-- test/runtests_riccati.jl | 10 +++++++++ test/runtests_solve_api.jl | 10 ++++----- 12 files changed, 72 insertions(+), 25 deletions(-) diff --git a/regression-harness/cases/diiid_multi_n.toml b/regression-harness/cases/diiid_multi_n.toml index ca363248f3..0b08712702 100644 --- a/regression-harness/cases/diiid_multi_n.toml +++ b/regression-harness/cases/diiid_multi_n.toml @@ -109,12 +109,13 @@ label = "PE surface energy (sum over n)" noise_threshold = 1e-10 order = 62 +# Zero for an ideal run: it is the non-Hermitian part of the plasma response, so the floor makes it a Hermiticity check. [quantities.pe_toroidal_torque] h5path = "PerturbedEquilibrium/Energies/toroidal_torque" type = "real_scalar" extract = "value" label = "PE toroidal torque sum_n -2n Im(Phi_n' Lambda_nn^-1 Phi_n)/4" -noise_threshold = 1e-12 +noise_threshold = 1e-9 order = 63 # Singular coupling: one row per resonant (surface, n); integer-q surfaces appear once per n diff --git a/regression-harness/cases/diiid_n1.toml b/regression-harness/cases/diiid_n1.toml index 72ccadc898..82afcb0746 100644 --- a/regression-harness/cases/diiid_n1.toml +++ b/regression-harness/cases/diiid_n1.toml @@ -347,12 +347,13 @@ label = "PE surface energy" noise_threshold = 1e-10 order = 93 +# Zero for an ideal run: it is the non-Hermitian part of the plasma response, so the floor makes it a Hermiticity check. [quantities.pe_toroidal_torque] h5path = "PerturbedEquilibrium/Energies/toroidal_torque" type = "real_scalar" extract = "value" label = "PE toroidal torque" -noise_threshold = 1e-12 +noise_threshold = 1e-9 order = 94 # NTV (neoclassical toroidal viscosity) toroidal torque T_φ [N·m] from the diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 1338896137..6f772bd4cd 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -15,6 +15,12 @@ abstract type ModeSpace end ModeIndices(modes::ModeSpace) Immutable copy of a mode space's indexing, for code that must not see the rest of its source. + +## Fields + + - `mlow::Int`, `mhigh::Int`, `mpert::Int` - Lowest and highest poloidal harmonic and their count. + - `nlow::Int`, `nhigh::Int`, `npert::Int` - Lowest and highest toroidal harmonic and their count. + - `numpert_total::Int` - Number of (m, n) harmonics, `mpert * npert`. """ struct ModeIndices <: ModeSpace mlow::Int @@ -96,7 +102,9 @@ Physical and workflow controls for a force-balance solve, together with its sele - `delta_mhigh::Int` - Expands upper bound of Fourier harmonics by delta_mhigh - `singfac_min::Float64` - Distance `|m − nq|` from each rational surface at which the ideal integration stops and the surface is crossed through its asymptotic series. Energies do not depend on it; Δ′ loses accuracy below - about 1e-5, and the series does beyond the first radial-grid knot. + about 1e-5, and the series does beyond the first radial-grid knot. Default 5e-4. A `kinetic` run stops this far + from each kinetic singular surface and steps across by a trapezoidal rule, whose error grows as the distance + cubed, so its default is 1e-5. - `crossing_fill_points::Int` - Stored states added on each side of each crossed rational surface from its asymptotic series, log-spaced in distance between `singfac_min` and `crossing_fill_min`. Zero adds none. - `crossing_fill_min::Float64` - Distance `|m − nq|` from the surface of the closest of those states. @@ -131,7 +139,9 @@ Physical and workflow controls for a force-balance solve, together with its sele nn_high::Int = 0 delta_mlow::Int = 0 delta_mhigh::Int = 0 - singfac_min::Float64 = 5e-4 # Required nonzero for the Riccati path. + kinetic::Any = nothing + kinetic_factor::Float64 = 1.0 + singfac_min::Float64 = kinetic === nothing ? 5e-4 : 1e-5 # Required nonzero for the Riccati path. crossing_fill_points::Int = 5 crossing_fill_min::Float64 = 1e-5 truncate_at_rational_offset::Bool = true @@ -139,8 +149,6 @@ Physical and workflow controls for a force-balance solve, together with its sele rational_offset_fraction::Float64 = 0.2 frobenius_order::Int = 6 qhigh::Float64 = 1e3 - kinetic::Any = nothing - kinetic_factor::Float64 = 1.0 qlow::Float64 = 0.0 dW_edge_scan_start::Float64 = 0.99 truncate_at_dW_peak::Bool = false diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index 2855965b3f..9391ce4544 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -558,7 +558,8 @@ Cross ideal singular surface `ising` in its asymptotic basis [Glasser & Kolemen Eq. 36]: the solutions are expanded in the left basis, the column carrying each resonance's big solution ends at the surface, the nonresonant coefficients continue into the right basis, and each small solution starts there in the freed column. `basis` is the surface's entry of `asymptotic_bases`. Records both coefficient sets in -`odet.ca_l` and `odet.ca_r`, and the column reduction for `transform_u!`. +`odet.ca_l` and `odet.ca_r`, and the column reduction for `transform_u!`. Fortran `ode_ideal_cross` steps across +with a trapezoidal rule instead. """ function cross_ideal_singular_surf!( odet::OdeState, diff --git a/src/ForceFreeStates/Free.jl b/src/ForceFreeStates/Free.jl index 619e4d6a19..a771920296 100644 --- a/src/ForceFreeStates/Free.jl +++ b/src/ForceFreeStates/Free.jl @@ -214,16 +214,11 @@ for fast evaluation in `free_compute_total` during the edge dW scan. psi_array = zeros!(pool, Float64, npsi + 1) wv_array = zeros!(pool, ComplexF64, npsi + 1, intr.numpert_total, intr.numpert_total) - for i in 1:(npsi+1) - # Space points evenly in q over [qedge, qlim] (i=1 → qedge, i=npsi+1 → qlim) + # Points evenly spaced in q over [qedge, qlim]; q is monotonic over the scan band, which brackets each root + psi_array[1], psi_array[npsi+1] = ctrl.dW_edge_scan_start, intr.psilim + for i in 2:npsi qi = qedge + (intr.qlim - qedge) * ((i - 1) / npsi) - - psii = ctrl.dW_edge_scan_start + (intr.psilim - ctrl.dW_edge_scan_start) * ((i - 1) / npsi) - psi_array[i] = find_zero( - (psi -> profiles.q_spline(psi) - qi, - psi -> profiles.q_deriv(psi)), - psii, Roots.Newton() - ) + psi_array[i] = find_zero(psi -> profiles.q_spline(psi) - qi, (ctrl.dW_edge_scan_start, intr.psilim), Roots.Brent()) end # Raw vacuum matrix at each scan psi (singfac NOT applied; free_compute_total applies it analytically) diff --git a/src/ForceFreeStates/Integrators.jl b/src/ForceFreeStates/Integrators.jl index 3705a5e76c..ad112307d3 100644 --- a/src/ForceFreeStates/Integrators.jl +++ b/src/ForceFreeStates/Integrators.jl @@ -34,13 +34,13 @@ Chunked Riccati integration and the singular-surface boundary-value solve. ## Fields - - `eulerlagrange_tolerance::Float64` - Relative tolerance for ODE integration. + - `eulerlagrange_tolerance::Float64` - Relative tolerance for ODE integration; the error of Δ′ scales with it. - `save_interval::Int` - Store every Nth solver step of each chunk; chunk ends and the edge-dW scan band are always stored. - `nchunks::Int` - Target chunk count; zero derives the count from the singular surfaces. - `extended_precision_bvp::Bool` - Solve the Delta-prime BVP in Complex{Double64} instead of ComplexF64; far slower, and needed only beyond about 150 poloidal harmonics. """ @kwdef struct Riccati <: AbstractIntegrator - eulerlagrange_tolerance::Float64 = 1e-8 + eulerlagrange_tolerance::Float64 = 1e-10 save_interval::Int = 1 nchunks::Int = 0 extended_precision_bvp::Bool = false diff --git a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index f18f4271e9..22657b0f12 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -2,6 +2,28 @@ # Relative difference between the two plasma response matrices above which `compute_delta_prime_matrix` warns. const DELTA_PRIME_RESPONSE_MISMATCH = 1e-6 +# Integration tolerance times the size of the big solution against the small one at the crossing distance, above which +# the small solution of a surface is not resolved. +const UNRESOLVED_SMALL_SOLUTION = 1.0 + +""" + warn_unresolved_surfaces(bases, surfaces, rtol) + +Warn for each crossed surface whose big asymptotic solution exceeds its small one, at the crossing distance, by more +than the integration tolerance `rtol` resolves, so that Δ' and the outer solutions there are unreliable. `bases` is +from `asymptotic_bases`; `surfaces` are the singular surfaces it indexes. +""" +function warn_unresolved_surfaces(bases::AbstractDict, surfaces::Vector{SingType}, rtol::Float64) + for ising in sort!(collect(keys(bases))) + ising <= length(surfaces) || continue + alpha = maximum(real, bases[ising].left_series.alpha) + ratio = bases[ising].dpsi^(-2 * alpha) + rtol * ratio > UNRESOLVED_SMALL_SOLUTION && + @warn "Riccati: at the rational surface ψ = $(@sprintf("%.4f", surfaces[ising].psifac)) (m = $(join(surfaces[ising].m, ", "))) the big solution is " * + "$(@sprintf("%.1e", ratio)) times the small one at the crossing distance (Mercier exponent α = $(@sprintf("%.2f", alpha))), more than " * + "eulerlagrange_tolerance = $rtol resolves. Δ' and the outer solutions at this surface are unreliable." + end +end """ compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> (delta_prime, coefficients) diff --git a/src/ForceFreeStates/Run.jl b/src/ForceFreeStates/Run.jl index 294a158f16..00b4df2ce8 100644 --- a/src/ForceFreeStates/Run.jl +++ b/src/ForceFreeStates/Run.jl @@ -102,6 +102,7 @@ function run_force_free_states( if intr.verbose @info "Computing Δ' matrix (STRIDE BVP with vacuum coupling)" end + warn_unresolved_surfaces(riccati.bases, intr.sing[1:intr.msing], ctrl.algorithm.eulerlagrange_tolerance) delta_prime, coefficients = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) if coefficients !== nothing diff --git a/test/runtests_eulerlagrange.jl b/test/runtests_eulerlagrange.jl index 2907961530..18618c8941 100644 --- a/test/runtests_eulerlagrange.jl +++ b/test/runtests_eulerlagrange.jl @@ -611,6 +611,14 @@ end @test chunks[1].needs_crossing && !chunks[2].needs_crossing end + @testset "a kinetic run crosses closer by default" begin + FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates + kinetic = FFS.TestKineticMatrices(; scale=1.0) + @test FFS.ForceFreeStatesControl().singfac_min == 5e-4 + @test FFS.ForceFreeStatesControl(; kinetic).singfac_min == 1e-5 + @test FFS.ForceFreeStatesControl(; kinetic, singfac_min=1e-4).singfac_min == 1e-4 + end + @testset "EdgeScanState" begin FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates # Default construction with sentinel values diff --git a/test/runtests_parallel_integration.jl b/test/runtests_parallel_integration.jl index 660ab754a1..60bcf1d9d7 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -212,8 +212,8 @@ end et_fwd, intr_fwd = run_solovev("Forward") et_ric, intr_ric = run_solovev("Riccati") - # Energy eigenvalue matches to 2% - @test isapprox(et_ric, et_fwd; rtol=0.02) + # Both integrators cross each surface the same way + @test isapprox(et_ric, et_fwd; rtol=1e-6) end @testset "ode_itime_cost is additive over sub-intervals" begin diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index bcb62bccb1..cfe9e86858 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -177,6 +177,16 @@ end @test isapprox(dp_few, dp_auto; rtol=1e-4) end + @testset "a surface whose small solution the tolerance cannot resolve is named" begin + function surface_warnings(fixture) + ctrl, intr, equil, _, mats = prepared_solovev(; fixture) + _, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) + return () -> FFS.warn_unresolved_surfaces(riccati.bases, intr.sing[1:intr.msing], ctrl.algorithm.eulerlagrange_tolerance) + end + @test_logs (:warn, r"big solution is .* times the small one") match_mode = :any surface_warnings("regression_solovev_ideal_example")() + @test_logs min_level = Logging.Warn surface_warnings("regression_tj_ideal_example")() + end + @testset "the Δ′ solutions on the stored grid" begin ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example") odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index eb0d4d85d3..88fd57a35b 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -69,8 +69,9 @@ include("display_check.jl") @testset "riccati solve produces the unified delta_prime" begin mktempdir() do dir - reference = GPEC.main([_stage_deck(dir; ffs_overrides=Dict{String,Any}("integrator" => "Riccati"))]).ffs - prob = ForceBalanceProblem(equil; nn=1, wall=wall, ffs_kwargs...) + # At the default crossing distance; the fixture's own 1e-6 is below where Δ′ keeps its accuracy. + reference = GPEC.main([_stage_deck(dir; ffs_overrides=Dict{String,Any}("integrator" => "Riccati", "singfac_min" => 5e-4))]).ffs + prob = ForceBalanceProblem(equil; nn=1, wall=wall, ffs_kwargs..., singfac_min=5e-4) api = solve(prob, Riccati(; riccati_kwargs..., nchunks=40)) @test api.integrator === :riccati @@ -81,10 +82,9 @@ include("display_check.jl") @test size(api.delta_prime.matrix) == (msing, msing) @test api.delta_prime.matrix ≈ FFS.pest3_decompose(api.delta_prime.raw).Δ - # Chunking is a decomposition of the same problem, so Δ′ tracks the TOML run to the accuracy - # the propagator products keep at this fixture's singfac_min = 1e-6. + # Chunking is a decomposition of the same problem, so Δ′ tracks the TOML run. @test size(reference.delta_prime.matrix) == size(api.delta_prime.matrix) - @test api.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-4 + @test api.delta_prime.matrix ≈ reference.delta_prime.matrix rtol = 1e-6 # With the deck's own (auto) chunking the two runs are the same computation. same = solve(prob, riccati) From b6bfdf98d9456b02f1dbe41e61f3f57dd146b83e Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 18 Nov 2026 21:29:42 +0100 Subject: [PATCH 11/27] PerturbedEquilibrium - FEATURE! - Accept Riccati results in plasma_response --- docs/src/api.md | 6 +-- docs/src/index.md | 2 +- docs/src/perturbed_equilibrium.md | 6 +-- docs/src/stability.md | 6 +-- docs/src/workflow.md | 6 +-- src/Display.jl | 1 - .../PerturbedEquilibrium.jl | 6 +-- test/runtests_result_struct.jl | 52 +++++++++---------- 8 files changed, 39 insertions(+), 46 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 94f436687a..3a37894470 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -125,12 +125,12 @@ The weights are linear-combination coefficients, not physical amplitudes: a coil The second argument of `solve` picks the formalism and its fields are that formalism's numerical settings; physical inputs belong on `ForceBalanceProblem`: ```julia -ffs = solve(eq, Forward(; eulerlagrange_tolerance=1e-8); nn=1, vac_flag=true) # dense ξ profiles: the only input plasma_response accepts; kinetic solves -ffs = solve(eq, Riccati(; nchunks=40); nn=1, vac_flag=true) # chunked propagators, Δ′ matrix (default) +ffs = solve(eq, Forward(; eulerlagrange_tolerance=1e-8); nn=1, vac_flag=true) # dense ξ profiles; kinetic solves +ffs = solve(eq, Riccati(; nchunks=40); nn=1, vac_flag=true) # chunked propagators, Δ′ matrix, ξ profiles (default) ffs = solve(eq, Galerkin(; nx=512); nn=1) # finite-element outer-region Δ′ ``` -A result carries `nothing` in the fields its integrator does not produce, and consumers warn and skip rather than erroring; `plasma_response` in particular needs a `Forward()` solve, or a `Galerkin(; error_field_response=true)` solve with `vac_flag=true`, with `wall=nothing` (it errors on a wall, any other Galerkin result or a matched one, and skips with a warning on a Riccati one), see [Stability](stability.md). +A result carries `nothing` in the fields its integrator does not produce, and consumers warn and skip rather than erroring; `plasma_response` in particular needs a `Riccati()` or `Forward()` solve, or a `Galerkin(; error_field_response=true)` solve, with `vac_flag=true` and `wall=nothing` (it errors on a wall, any other Galerkin result or a matched one), see [Stability](stability.md). A kinetic solve takes `Forward()` with the problem's `kinetic` keyword: `kinetic=KineticForcesControl(; ...)` evaluates the drift-kinetic matrices on the equilibrium's kinetic profiles, `kinetic=TestKineticMatrices(; scale)` uses synthetic matrices, `kinetic_factor` scales either, and `km = kinetic_matrices(prob)` evaluates the source once for reuse in later solves ([`KineticMatrices`](@ref GeneralizedPerturbedEquilibrium.ForceFreeStates.KineticMatrices)). ## Inner-layer matching diff --git a/docs/src/index.md b/docs/src/index.md index 65c06a44c7..ceca953263 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -24,7 +24,7 @@ The [Workflow](workflow.md) page maps every stage to its physics, deck sections | `ForceFreeStates` — ideal (or drift-kinetic) MHD stability by the Newcomb criterion, with the `Vacuum` response of the `[Wall]` (a wall case is a separate deck from a response case) | `[ForceFreeStates]` | `ForceFreeStates/FreeBoundaryStability/`, `SingularSurfaces/Delta_prime_matrix` | | `LocalStability` — Mercier, resistive-interchange and ballooning criteria | `[LocalStability]` | `LocalStability/` | | `Match` — the resistive inner layer matched to the outer-region Δ′ | `[Match]` | `SingularSurfaces/Match/` | -| `PerturbedEquilibrium` — the plasma response to the field of `[ForcingTerms]`: resonant fields, islands, overlap; needs a `"Forward"` (or `error_field_response` `"Galerkin"`) solve without a wall | `[PerturbedEquilibrium]` | `PerturbedEquilibrium/SingularCoupling/` | +| `PerturbedEquilibrium` — the plasma response to the field of `[ForcingTerms]`: resonant fields, islands, overlap; needs a `"Riccati"` or `"Forward"` (or `error_field_response` `"Galerkin"`) solve with `vac_flag = true` and without a wall | `[PerturbedEquilibrium]` | `PerturbedEquilibrium/SingularCoupling/` | | `KineticForces` — the neoclassical toroidal viscosity torque of that response | `[KineticForces]` | `KineticForces/` | | `ErrorFields` — coil tolerances, locking risk and correction limits | `[ErrorFields]` | `ErrorFields/Risk/` | | `Tearing` — tearing growth rates and critical resonant fields from an inner-layer model | `[Tearing]` | `Tearing/Roots/` | diff --git a/docs/src/perturbed_equilibrium.md b/docs/src/perturbed_equilibrium.md index db15d4a465..09a66e3375 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -91,15 +91,15 @@ The coupling matrices `C_*` map the applied ``\tilde b`` to each of these quanti ## Running it -The response needs a force-free-states solve with `integrator = "Forward"` and no `[Wall]`. -The operators are built from a dense ``\xi`` solution with its free-boundary δW, which a `"Forward"` solve and a `"Galerkin"` solve with `error_field_response = true` and `vac_flag = true` both provide: a `"Riccati"` solve (the deck default) makes `plasma_response` warn that the response is skipped and return empty operators, so the failure surfaces only when a field is applied, while a `"Galerkin"` solve without those flags or a `[Match]`ed solve, whose singular coupling is not defined yet, is an error. The ψ-resolved torque response (`compute_torque_response`) needs a `"Forward"` kinetic solve. +The response needs a force-free-states solve with `vac_flag = true` and no `[Wall]`. +The operators are built from a dense ``\xi`` solution with its free-boundary δW, which a `"Riccati"` solve (the deck default), a `"Forward"` solve and a `"Galerkin"` solve with `error_field_response = true` all provide when `vac_flag = true`: a `"Galerkin"` solve without those flags or a `[Match]`ed solve, whose singular coupling is not defined yet, is an error. The ψ-resolved torque response (`compute_torque_response`) needs a `"Forward"` kinetic solve. A solve with a wall is an error too, because the surface inductance is the free-space one and ``\Lambda`` from a wall run would mix two vacuum models; the wall case of a stability study is therefore a separate deck. From `examples/DIIID-like_ideal_example/gpec.toml`, after the `[ForceFreeStates]` solve and a `[ForcingTerms]` drive: ```toml [ForceFreeStates] -integrator = "Forward" # the dense ξ solution the response needs ("Riccati" is the default); no [Wall] +integrator = "Forward" # the dense ξ solution the response needs ("Riccati", the default, supplies one too); no [Wall] [PerturbedEquilibrium] compute_singular_coupling = true # resonant fields, islands and Chirikov parameter diff --git a/docs/src/stability.md b/docs/src/stability.md index 63327237be..e735016e9d 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -41,8 +41,8 @@ Its global boundary-value problem over all surfaces gives the Δ′ matrix of [G `[ForceFreeStates] integrator` selects the radial method; its numerical settings sit in a section of the same name. -- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the solution at every solver step, like Forward, so its result carries ``\xi`` profiles; `plasma_response` does not accept a Riccati result yet. -- `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction as the solutions grow, crossing each rational surface in its asymptotic basis as Riccati does. It returns dense displacement profiles, and is the only integrator whose result `plasma_response` accepts (the response operators are built from the dense ``\xi`` solution; a wall is refused too) and the only one that supports the kinetic solve. +- `"Riccati"` (the default; `[Riccati]`) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the solution at every solver step, like Forward, so its result carries ``\xi`` profiles and `plasma_response` accepts it. +- `"Forward"` (`[Forward]`) integrates the system directly in ``(U_1, U_2)`` with Gaussian reduction as the solutions grow, crossing each rational surface in its asymptotic basis as Riccati does. It returns dense displacement profiles, and is the only integrator that supports the kinetic solve. - `"Galerkin"` (`[Galerkin]`) solves the outer region variationally on a finite-element basis, giving the resistive Δ′ matrix and the PEST-3 blocks but no free-boundary energies; see [Galerkin Solver](galerkin.md). `kinetic = "KineticForces"` replaces the ideal energy matrices by their drift-kinetic form, which needs `[Equilibrium] kinetic_file`; see [Kinetic Forces](kinetic_forces.md). @@ -59,7 +59,7 @@ qlow = 1.02 # inner edge of the integration domain qhigh = 1e3 # outer bound of qlim (see Integration domain) delta_mlow = 8 # extra poloidal modes below the resonant range delta_mhigh = 8 # extra poloidal modes above it -integrator = "Forward" # "Riccati" is the default; "Forward" or an error_field_response "Galerkin" (and no [Wall]) is required for [PerturbedEquilibrium] +integrator = "Forward" # "Riccati" is the default; [PerturbedEquilibrium] takes either, or an error_field_response "Galerkin", and no [Wall] truncate_at_rational_offset = true rational_offset_fraction = 0.2 diff --git a/docs/src/workflow.md b/docs/src/workflow.md index 8a491300b4..c77982d014 100644 --- a/docs/src/workflow.md +++ b/docs/src/workflow.md @@ -29,7 +29,7 @@ Every stage after `Equilibrium` reads the force-free states, and `KineticForces` | What are the tearing growth rate and critical resonant field? | `[Tearing]` (+ `[SLAYER]` or `[GGJ]`) | `Tearing/Roots/gamma`, `Tearing/Roots/omega`, `Tearing/CriticalResonantField/` | | What does a resistive inner layer do to the response? | `[Match]` (+ `[GGJ]`) | `SingularSurfaces/Match/` | -`[PerturbedEquilibrium]` and the stages built on it need a `[ForceFreeStates]` solve with `integrator = "Forward"`, or `"Galerkin"` with `error_field_response = true` and `vac_flag = true`, and no `[Wall]`, while the Δ′ matrix, `[Tearing]` and wall stability need `"Riccati"` or `"Galerkin"` or a `[Wall]`. Only a `"Galerkin"` deck without a `[Wall]` does both; otherwise run the response and the Δ′ or wall cases as separate decks (`DIIID-like_ideal_example` and `DIIID-like_riccati_deltaprime_example` are such a pair). +`[PerturbedEquilibrium]` and the stages built on it need a `[ForceFreeStates]` solve with `vac_flag = true` and `integrator = "Riccati"` or `"Forward"`, or `"Galerkin"` with `error_field_response = true`, and no `[Wall]`, while the Δ′ matrix, `[Tearing]` and wall stability need `"Riccati"` or `"Galerkin"` or a `[Wall]`. A `"Riccati"` or `"Galerkin"` deck without a `[Wall]` does both; the wall case is a separate deck. ### Headline outputs @@ -76,7 +76,7 @@ Page: [Tearing](inner_layer.md). Computes the plasma response to an external non-axisymmetric field: `plasma_response` builds the permeability, inductance and reluctance operators on the control surface from the force-free states and the vacuum matrices, and `perturbed_equilibrium` applies them to the drive that `ForcingTerms` supplies, either a normal-field spectrum from a file or the Biot–Savart field of `[[ForcingTerms.coil_set]]` coils. The resonant fields, island half-widths and Chirikov parameter at each rational surface follow from the singular coupling (`compute_singular_coupling`), and `regularization_width` controls the regularization of the ideal response there. -The response is built from a `"Forward"` solve, or a `"Galerkin"` solve with `error_field_response = true` and `vac_flag = true`, without a wall: a `"Riccati"` result (the default) makes `plasma_response` skip the operators with a warning, and any other `"Galerkin"` result, a matched result or a wall is an error. +The response is built from a `"Riccati"` (the default) or `"Forward"` solve with `vac_flag = true`, or a `"Galerkin"` solve with `error_field_response = true` and `vac_flag = true`, without a wall: any other `"Galerkin"` result, a matched result or a wall is an error. Outputs: `PerturbedEquilibrium/ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`. Key references: [Park et al. (2007a)](citations.md#PerturbedEquilibrium), [Park et al. (2009)](citations.md#PerturbedEquilibrium). Pages: [Forcing Terms](forcing_terms.md), [Perturbed Equilibrium](perturbed_equilibrium.md). @@ -127,7 +127,7 @@ alpha_boundary_scan = true [ForceFreeStates] nn = 1 vac_flag = true -integrator = "Forward" # "Forward": [PerturbedEquilibrium] needs a dense ξ solution and no [Wall] ("Riccati" is the default) +integrator = "Forward" # [PerturbedEquilibrium] needs a dense ξ solution and no [Wall]; "Riccati" (the default) supplies one too [ForcingTerms] forcing_data_format = "coil" diff --git a/src/Display.jl b/src/Display.jl index e9348d5059..26a949ae39 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -256,7 +256,6 @@ _resonances(r::PlasmaResponse) = ["$(m)/$(n)" for (m, n) in zip(r.rational_m_res function _missing_operators_note(r::PlasmaResponse) r.ffs.free_boundary === nothing && return "not computed (needs a free-boundary result)" r.ffs.solution === nothing && return "not computed (needs stored ξ profiles)" - r.ffs.integrator === :riccati && return "not computed (a Riccati result is not accepted yet)" return "not computed" end diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 32f29b5460..dc7d771a40 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -79,11 +79,7 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: resp = PlasmaResponse(; ffs, m_modes, n_modes, compute_singular_coupling, compute_torque_response, unit_edge_basis=solution !== nothing && solution.basis === :unit_edge) - # A Riccati result carries ξ profiles, but the response operators are not validated on them yet. - riccati = ffs.integrator === :riccati - riccati && @warn "Skipping plasma response calculation: a Riccati result is not accepted yet; use the Forward integrator" - if !riccati && ForceFreeStates.require(ffs, :free_boundary, "plasma response calculation") && - ForceFreeStates.require_solution(ffs, "plasma response calculation") + if ForceFreeStates.require(ffs, :free_boundary, "plasma response calculation") && ForceFreeStates.require_solution(ffs, "plasma response calculation") build_response_operators!(resp; verbose) if compute_singular_coupling build_coupling_operators!(resp; verbose) diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index df2aa262ad..6d29521518 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -137,35 +137,33 @@ include("display_check.jl") end end - @testset "PerturbedEquilibrium warn-skips on a riccati result" begin - mktempdir() do dir - _stage_deck(dir, joinpath(@__DIR__, "test_data", "regression_tj_ideal_example"); - ffs_overrides=Dict{String,Any}("integrator" => "Riccati"), - extra_sections=Dict{String,Any}( - "ForcingTerms" => Dict{String,Any}( - "forcing_data_file" => "forcing.dat", - "forcing_data_format" => "ascii"), - "PerturbedEquilibrium" => Dict{String,Any}( - "compute_singular_coupling" => true))) - cp(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"), - joinpath(dir, "forcing.dat")) - - local ret - @test_logs (:warn,) match_mode = :any (ret = GeneralizedPerturbedEquilibrium.main([dir])) - # The stage runs to completion; both sub-calculations are simply not populated. - @test ret.pe !== nothing - @test isempty(ret.pe.response.permeability) - @test isempty(ret.pe.response.C_delta_prime) - @test ret.ffs.free_boundary !== nothing && ret.ffs.solution !== nothing - @test ret.resp.compute_singular_coupling - for result in (ret.resp, ret.pe) - plain = _check_display(result) - @test occursin("a Riccati result is not accepted yet", plain) - @test !occursin("needs a free-boundary result", plain) - @test !occursin("singular coupling off", plain) - @test !occursin(" 0 J", plain) + @testset "PerturbedEquilibrium on a riccati result matches the forward one" begin + run_pe(integrator) = + mktempdir() do dir + _stage_deck(dir, joinpath(@__DIR__, "test_data", "regression_tj_ideal_example"); + ffs_overrides=Dict{String,Any}("integrator" => integrator), + extra_sections=Dict{String,Any}( + "ForcingTerms" => Dict{String,Any}( + "forcing_data_file" => "forcing.dat", + "forcing_data_format" => "ascii"), + "PerturbedEquilibrium" => Dict{String,Any}( + "compute_singular_coupling" => true))) + cp(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"), + joinpath(dir, "forcing.dat")) + return GeneralizedPerturbedEquilibrium.main([dir]) end + forward, riccati = run_pe("Forward"), run_pe("Riccati") + + @test riccati.ffs.integrator === :riccati && riccati.pe !== nothing + @test riccati.resp.permeability ≈ forward.resp.permeability rtol = 1e-6 + @test riccati.resp.reluctance ≈ forward.resp.reluctance rtol = 1e-6 + # The singular coupling reads ξ and ξ′ off each surface, where the two integrators' stored nodes differ. + for name in (:C_delta_prime, :C_resonant_current, :C_resonant_area_weighted_field, :C_island_width_sq) + @test getfield(riccati.resp, name) ≈ getfield(forward.resp, name) rtol = 1e-3 end + @test riccati.pe.resonant_area_weighted_field ≈ forward.pe.resonant_area_weighted_field rtol = 1e-4 + @test riccati.pe.island_half_width ≈ forward.pe.island_half_width rtol = 1e-4 + foreach(_check_display, (riccati.resp, riccati.pe)) end @testset "display distinguishes disabled coupling from no resonances" begin From 02e8804b15c69fe62f29af1f24de3fceac8854e2 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 18 Nov 2026 22:43:31 +0100 Subject: [PATCH 12/27] =?UTF-8?q?PerturbedEquilibrium=20-=20REFACTOR!=20-?= =?UTF-8?q?=20Rename=20the=20forcing-driven=20=CE=94=E2=80=B2=20to=20?= =?UTF-8?q?=CE=94=5Fmn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/src/perturbed_equilibrium.md | 4 +-- ext/GPECMakieExt/perturbedequilibrium.jl | 4 +-- regression-harness/cases/diiid_multi_n.toml | 6 ++--- src/Analysis/PerturbedEquilibrium.jl | 22 ++++++++-------- .../PerturbedEquilibriumStructs.jl | 8 +++--- src/PerturbedEquilibrium/SingularCoupling.jl | 26 +++++++++---------- src/PerturbedEquilibrium/Utils.jl | 12 ++++----- test/runtests_result_struct.jl | 2 +- test/runtests_solve_api.jl | 2 +- 9 files changed, 43 insertions(+), 43 deletions(-) diff --git a/docs/src/perturbed_equilibrium.md b/docs/src/perturbed_equilibrium.md index 09a66e3375..e13baa86b6 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -41,7 +41,7 @@ The run writes up to five coupling matrices under `PerturbedEquilibrium/Singular | `C_resonant_current` | the pitch-resonant current | A/T | | `C_island_width_sq` | the squared island half-width | 1/T | | `C_penetrated_area_weighted_field` | the penetrated field, when the run computes it | dimensionless | -| `C_Delta_prime` | the forcing-driven Δ′ | 1/T | +| `C_Delta_mn` | the forcing-driven ``\Delta_{mn}`` | 1/T | `ResonantCoupling` wraps the first; any of the others decomposes over any window of surfaces through the bare-matrix form of `dominant_coupling`, with the ``\tilde b`` conform taken from a `ResonantCoupling` of the same file, since the bare matrix carries no (m, n) labels for `check_mode_basis` to guard the projection: @@ -141,7 +141,7 @@ with the `RMPField` built from coils or a file as on the [Scripting API](api.md) | `PerturbedEquilibrium/SingularCoupling/resonant_current` | the pitch-resonant current | A | | `PerturbedEquilibrium/SingularCoupling/island_width_sq`, `island_half_width` | ``w_s^2`` and ``w_s`` in ψ_N | | | `PerturbedEquilibrium/SingularCoupling/chirikov_parameter` | ``\sigma_s`` | | -| `PerturbedEquilibrium/SingularCoupling/Delta_prime` | the forcing-driven tearing Δ′ per surface | | +| `PerturbedEquilibrium/SingularCoupling/Delta_mn` | the forcing-driven ``\Delta_{mn}`` per surface | | | `PerturbedEquilibrium/SingularCoupling/C_*` | the coupling matrices from the applied ``\tilde b`` to each quantity above | | | `PerturbedEquilibrium/SingularCoupling/DominantMode/singular_values`, `right_singular_vectors`, `left_singular_vectors`, `rational_index`, `forcing_overlap` | the core-window SVD of the resonant-field coupling | | | `PerturbedEquilibrium/Energies/plasma_energy`, `vacuum_energy`, `surface_energy` | the perturbed energies | J | diff --git a/ext/GPECMakieExt/perturbedequilibrium.jl b/ext/GPECMakieExt/perturbedequilibrium.jl index 12512534b7..739e3b4c87 100644 --- a/ext/GPECMakieExt/perturbedequilibrium.jl +++ b/ext/GPECMakieExt/perturbedequilibrium.jl @@ -18,7 +18,7 @@ function _coupling_row(d, key) key === :current && return (_magnitude_row(abs.(d.current), rich("|I", subscript("res"), "|"), "A")..., nothing) key === :island_hw && return (d.island_hw, rich("w/2 (", PSIN, ")"), identity, nothing) key === :chirikov && return (d.chirikov, "effective island-overlap\nChirikov parameter", identity, 1.0) - return (real.(d.delta_prime), "driven Re Δ′", identity, 0.0) + return (real.(d.delta_mn), rich("driven Re Δ", subscript("mn")), identity, 0.0) end const _ROW_TITLES = Dict( @@ -26,7 +26,7 @@ const _ROW_TITLES = Dict( :field => "Resonant field at each rational surface", :current => "Resonant current at each rational surface", :island_hw => "Island half-width at each rational surface", - :delta_prime => "Forcing-driven Δ′ at each rational surface" + :delta_mn => rich("Forcing-driven Δ", subscript("mn"), " at each rational surface") ) function _coupling_title(d, keys) diff --git a/regression-harness/cases/diiid_multi_n.toml b/regression-harness/cases/diiid_multi_n.toml index ca363248f3..9a30d33a85 100644 --- a/regression-harness/cases/diiid_multi_n.toml +++ b/regression-harness/cases/diiid_multi_n.toml @@ -158,11 +158,11 @@ label = "Chirikov parameter per row" noise_threshold = 1e-8 order = 74 -[quantities.delta_prime_all] -h5path = "PerturbedEquilibrium/SingularCoupling/Delta_prime" +[quantities.delta_mn_all] +h5path = "PerturbedEquilibrium/SingularCoupling/Delta_mn" type = "complex_vector" extract = "all_complex" -label = "forcing-driven Delta' per row" +label = "forcing-driven Delta_mn per row" noise_threshold = 1e-8 order = 75 diff --git a/src/Analysis/PerturbedEquilibrium.jl b/src/Analysis/PerturbedEquilibrium.jl index 6ceabfe164..770150bd5b 100644 --- a/src/Analysis/PerturbedEquilibrium.jl +++ b/src/Analysis/PerturbedEquilibrium.jl @@ -25,7 +25,7 @@ function _coupling_data(s::PerturbedEquilibriumState) r = s.response return (; field=s.resonant_area_weighted_field, penetrated=_penetrated(s.penetrated_area_weighted_field), current=s.resonant_current, island_hw=s.island_half_width, chirikov=s.chirikov_parameter, - delta_prime=s.delta_prime, psi=r.rational_psi, q=r.rational_q, m=r.rational_m_res, n=r.rational_n) + delta_mn=s.delta_mn, psi=r.rational_psi, q=r.rational_q, m=r.rational_m_res, n=r.rational_n) end function _coupling_data(h5path::AbstractString) @@ -33,7 +33,7 @@ function _coupling_data(h5path::AbstractString) rd(name) = read(fid[_COUPLING*name]) pen = haskey(fid, _COUPLING * "penetrated_area_weighted_field") ? _penetrated(rd("penetrated_area_weighted_field")) : nothing (; field=rd("resonant_area_weighted_field"), penetrated=pen, current=rd("resonant_current"), island_hw=rd("island_half_width"), chirikov=rd("chirikov_parameter"), - delta_prime=rd("Delta_prime"), psi=rd("rational_psi"), q=rd("rational_q"), m=rd("rational_m"), n=rd("rational_n")) + delta_mn=rd("Delta_mn"), psi=rd("rational_psi"), q=rd("rational_q"), m=rd("rational_m"), n=rd("rational_n")) end end @@ -77,14 +77,14 @@ function _plot_resonant_coupling end function _plot_mode_spectrogram end function _plot_perturbed_equilibrium_summary end -const _COUPLING_ROWS = (:field, :current, :island_hw, :chirikov, :delta_prime) +const _COUPLING_ROWS = (:field, :current, :island_hw, :chirikov, :delta_mn) """ plot_resonant_area_weighted_field(src; save_path=nothing) Plot the resonant coupling at each rational surface in rows sharing a q = m/n axis: the resonant area-weighted field |b̄_res|, the resonant current |I_res|, the island half-width w/2, the effective island-overlap Chirikov parameter -and the forcing-driven Re Δ′. Toroidal mode numbers are distinguished by colour; the title counts the surfaces with +and the forcing-driven Re Δ_mn. Toroidal mode numbers are distinguished by colour; the title counts the surfaces with overlapping islands. ### Arguments @@ -172,10 +172,10 @@ function plot_chirikov_parameter(src::Source; save_path=nothing) end """ - plot_driven_delta_prime(src; save_path=nothing) + plot_driven_delta_mn(src; save_path=nothing) -Plot the forcing-driven Re Δ′ at each rational surface, the response to the applied forcing; for the -equilibrium's own Δ′ of a Riccati or Galerkin solve, see `ForceFreeStates.plot_delta_prime`. +Plot the forcing-driven Re Δ_mn at each rational surface, the jump of ∂b^ψ/∂ψ across it that the applied forcing +drives; for the equilibrium's Δ′ matrix of a Riccati or Galerkin solve, see `ForceFreeStates.plot_delta_prime`. ### Arguments @@ -189,9 +189,9 @@ equilibrium's own Δ′ of a Riccati or Galerkin solve, see `ForceFreeStates.plo A Makie `Figure`. """ -function plot_driven_delta_prime(src::Source; save_path=nothing) - _require(plot_driven_delta_prime, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), (:delta_prime,); save_path) +function plot_driven_delta_mn(src::Source; save_path=nothing) + _require(plot_driven_delta_mn, src) + return _draw(_plot_resonant_coupling, _coupling_data(src), (:delta_mn,); save_path) end const _STYLES = (:log_heatmap, :linear_heatmap, :lines) @@ -535,7 +535,7 @@ register!(plot_resonant_area_weighted_field, _PE_SOURCES, (:singular_coupling,), register!(plot_resonant_area_weighted_field_amplitude, _PE_SOURCES, (:singular_coupling,), "|b̄_res| per rational surface") register!(plot_island_widths, _PE_SOURCES, (:singular_coupling,), "island half-width per rational surface") register!(plot_chirikov_parameter, _PE_SOURCES, (:singular_coupling,), "effective island-overlap Chirikov parameter per rational surface") -register!(plot_driven_delta_prime, _PE_SOURCES, (:singular_coupling,), "forcing-driven Δ′ per rational surface") +register!(plot_driven_delta_mn, _PE_SOURCES, (:singular_coupling,), "forcing-driven Δ_mn per rational surface") register!(plot_mode_spectrogram, _PE_SOURCES, (:response_xi,), "response harmonics against ψ_N (component = :xi_psi, :b_psi, :Jb_theta, :Jb_zeta)") register!(plot_dominant_mode_surface, (PlasmaResponse, PerturbedEquilibriumState), (:dominant_mode,), "a dominant resonant-coupling mode as b_n on the control surface") diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index 09a7f6c706..016405435b 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -76,7 +76,7 @@ applied root-area-weighted field b̃_x to the resonant response at that surface. - `C_resonant_current` - Resonant current coupling (singcoup row 2) - `C_island_width_sq` - (w/2)² coupling (singcoup row 3) - `C_penetrated_area_weighted_field` - Penetrated area-weighted field coupling (singcoup row 4) - - `C_delta_prime` - Δ' coupling (singcoup row 5) + - `C_delta_mn` - Δ_mn coupling, the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4 over 2π·χ₁ (singcoup row 5) - `coupling_flux::NamedTuple` - The same five matrices acting on the physical flux Φ_x (keys without the `C_` prefix), used for the applied resonant vectors; empty when the coupling was not built. - `C_coeffs::Matrix{ComplexF64}` - Edge-to-solution coefficients `u_bnd⁻¹·edge_mn` of each unit forcing mode. @@ -124,7 +124,7 @@ on a `ResonantCoupling`): C_resonant_current::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) C_island_width_sq::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) C_penetrated_area_weighted_field::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) - C_delta_prime::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) + C_delta_mn::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) coupling_flux::NamedTuple = (;) C_coeffs::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) @@ -175,7 +175,7 @@ Response fields (mode space): Applied resonant vectors [n_rational] = C · forcing, on the rows of `response`. Matches Fortran `Phi_res`, `w_isl`, `K_isl`, `Delta`. - - `resonant_area_weighted_field`, `resonant_current`, `island_width_sq`, `penetrated_area_weighted_field`, `delta_prime` + - `resonant_area_weighted_field`, `resonant_current`, `island_width_sq`, `penetrated_area_weighted_field`, `delta_mn` - `forcing_solution_weights` - `C_coeffs`·Φ_x, the forcing's weights on the edge-driven solutions Diagnostics [n_rational]: @@ -229,7 +229,7 @@ Torque response (kinetic forward solves with `compute_torque_response`): resonant_current::Vector{ComplexF64} = ComplexF64[] island_width_sq::Vector{ComplexF64} = ComplexF64[] penetrated_area_weighted_field::Vector{ComplexF64} = ComplexF64[] - delta_prime::Vector{ComplexF64} = ComplexF64[] + delta_mn::Vector{ComplexF64} = ComplexF64[] forcing_solution_weights::Vector{ComplexF64} = ComplexF64[] # Diagnostics [n_rational] diff --git a/src/PerturbedEquilibrium/SingularCoupling.jl b/src/PerturbedEquilibrium/SingularCoupling.jl index d7e6f53cb7..d1924f8ddc 100644 --- a/src/PerturbedEquilibrium/SingularCoupling.jl +++ b/src/PerturbedEquilibrium/SingularCoupling.jl @@ -82,7 +82,7 @@ end Evaluate the `resnum` row of Ξ_ψ and Ξ′_ψ at `psi` for a matched solution: cubic Hermite for the value and the Ξ′ carried in `du_store` for the derivative (the `gal_flag` branch of Fortran `gpeq_sol`). Do not difference `u_store` instead: -near-cancellation in `bwp1` (singfac·Ξ′ against n·q′·Ξ) amplifies that error into Δ′. +near-cancellation in `bwp1` (singfac·Ξ′ against n·q′·Ξ) amplifies that error into Δ_mn. """ function _matched_solution_at(psi::Float64, resnum::Int, odet::SolutionProfiles, nstep::Int) il, ir, _ = _psi_bracket(odet.psi_store, psi, nstep) @@ -216,7 +216,7 @@ end Build the singular-layer coupling matrices of `resp.ffs` onto `resp`, matching Fortran GPEC's `C_f_x_out` [Park Phys. Plasmas 2009 056115]: one row per resonant (surface, n) pair, giving the -resonant area-weighted field, current, (w/2)², penetrated field and Δ' per unit forcing mode, plus +resonant area-weighted field, current, (w/2)², penetrated field and Δ_mn per unit forcing mode, plus the rational-surface metadata and the edge-to-solution coefficients `C_coeffs`. The matrices are stored acting on b̃_x, with flux-space copies in `resp.coupling_flux` for applying a forcing. @@ -224,7 +224,7 @@ stored acting on b̃_x, with flux-space copies in `resp.coupling_flux` for apply - Rows: the resonant and penetrated rows are a resonant flux divided by that surface's own area `rational_area[row]`, so both are fields in T. `C_resonant_current`, `C_island_width_sq` and - `C_delta_prime` carry their own normalizations. + `C_delta_mn` carry their own normalizations. - Columns: each field-space coupling matrix is right-multiplied by the control-surface `flux_conform`, so it acts on the root-area-weighted field b̃ in T and its singular values do not depend on `jac_type`. Applied vectors use the flux-space copies in `resp.coupling_flux` on the run's own forcing flux. @@ -286,7 +286,7 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resp.C_penetrated_area_weighted_field = zeros(ComplexF64, 0, 0) @warn "No inner-layer B_pen supplied; penetrated field not computed." maxlog = 1 end - resp.C_delta_prime = zeros(ComplexF64, n_rational, numpert_total) + resp.C_delta_mn = zeros(ComplexF64, n_rational, numpert_total) resp.rational_psi = zeros(Float64, n_rational) resp.rational_q = zeros(Float64, n_rational) resp.rational_m_res = zeros(Int, n_rational) @@ -377,9 +377,9 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resp.C_penetrated_area_weighted_field[row, :] = pen_row end - # Δ' is the ∂b^ψ/∂ψ jump over 2π·χ₁ [Glasser 2016]; j_c carries the surface Jacobian weighting of the current; + # Δ_mn is the ∂b^ψ/∂ψ jump, stored over 2π·χ₁; j_c carries the surface Jacobian weighting of the current; # resonant flux/area is a coordinate-invariant field in T [Park 2008; Pharr 2026]. - resp.C_delta_prime[row, :] = jump_vec ./ (twopi * chi1) + resp.C_delta_mn[row, :] = jump_vec ./ (twopi * chi1) resp.C_resonant_current[row, :] = jump_vec .* (-j_c / (twopi * m_res)) # Matches Fortran gpout_resp: singflx = L·fkaxmn, resonant area-weighted field = singflx/area, # islandhwids = 4·singflx/(2π·shear·q·chi1) @@ -397,8 +397,8 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resp.rational_surface_idx[row] = s if verbose - dp_diag = real(resp.C_delta_prime[row, resnum]) - @info "Row $row: q=$(@sprintf("%.3f", sing_surf.q)), ψ=$(@sprintf("%.3f", sing_surf.psifac)), m=$m_res, n=$nn, Δ'(diag)=$(@sprintf("%.3e", dp_diag))" + dp_diag = real(resp.C_delta_mn[row, resnum]) + @info "Row $row: q=$(@sprintf("%.3f", sing_surf.q)), ψ=$(@sprintf("%.3f", sing_surf.psifac)), m=$m_res, n=$nn, Δ_mn(diag)=$(@sprintf("%.3e", dp_diag))" end end finally @@ -408,12 +408,12 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) # Conform the stored matrices to b̃ space, C̃ = C·R with R = S·A (Pharr 2026); `coupling_flux` keeps the flux-space # copies so a forcing is applied without round-trip noise. resp.coupling_flux = (; resonant_area_weighted_field=resp.C_resonant_area_weighted_field, resonant_current=resp.C_resonant_current, - island_width_sq=resp.C_island_width_sq, penetrated_area_weighted_field=resp.C_penetrated_area_weighted_field, delta_prime=resp.C_delta_prime) + island_width_sq=resp.C_island_width_sq, penetrated_area_weighted_field=resp.C_penetrated_area_weighted_field, delta_mn=resp.C_delta_mn) flux_conform = resp.rootarea_to_area_weight .* resp.surface_area resp.C_resonant_area_weighted_field = resp.C_resonant_area_weighted_field * flux_conform resp.C_resonant_current = resp.C_resonant_current * flux_conform resp.C_island_width_sq = resp.C_island_width_sq * flux_conform - resp.C_delta_prime = resp.C_delta_prime * flux_conform + resp.C_delta_mn = resp.C_delta_mn * flux_conform have_inner_bpen && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * flux_conform) return resp @@ -441,7 +441,7 @@ function apply_coupling!(state::PerturbedEquilibriumState; verbose::Bool=false) state.resonant_area_weighted_field = C.resonant_area_weighted_field * forcing_flux state.resonant_current = C.resonant_current * forcing_flux state.island_width_sq = C.island_width_sq * forcing_flux - state.delta_prime = C.delta_prime * forcing_flux + state.delta_mn = C.delta_mn * forcing_flux isempty(C.penetrated_area_weighted_field) || (state.penetrated_area_weighted_field = C.penetrated_area_weighted_field * forcing_flux) state.forcing_solution_weights = resp.C_coeffs * forcing_flux @@ -450,8 +450,8 @@ function apply_coupling!(state::PerturbedEquilibriumState; verbose::Bool=false) if verbose max_island = isempty(state.island_half_width) ? 0.0 : maximum(state.island_half_width) - max_dp = isempty(state.delta_prime) ? 0.0 : maximum(abs.(real.(state.delta_prime))) - @info "Singular coupling complete. Max island half-width = $(@sprintf("%.3e", max_island)), max |Δ'| = $(@sprintf("%.3e", max_dp))" + max_dp = isempty(state.delta_mn) ? 0.0 : maximum(abs.(real.(state.delta_mn))) + @info "Singular coupling complete. Max island half-width = $(@sprintf("%.3e", max_island)), max |Δ_mn| = $(@sprintf("%.3e", max_dp))" end end diff --git a/src/PerturbedEquilibrium/Utils.jl b/src/PerturbedEquilibrium/Utils.jl index 1185379dd9..607506c3eb 100644 --- a/src/PerturbedEquilibrium/Utils.jl +++ b/src/PerturbedEquilibrium/Utils.jl @@ -125,14 +125,14 @@ function save_to_hdf5(file::Union{HDF5.File,HDF5.Group}, state::PerturbedEquilib !isempty(resp.C_resonant_current) && (coupling_group["C_resonant_current"] = resp.C_resonant_current) !isempty(resp.C_island_width_sq) && (coupling_group["C_island_width_sq"] = resp.C_island_width_sq) !isempty(resp.C_penetrated_area_weighted_field) && (coupling_group["C_penetrated_area_weighted_field"] = resp.C_penetrated_area_weighted_field) - !isempty(resp.C_delta_prime) && (coupling_group["C_Delta_prime"] = resp.C_delta_prime) + !isempty(resp.C_delta_mn) && (coupling_group["C_Delta_mn"] = resp.C_delta_mn) # Applied resonant vectors [n_rational] !isempty(state.resonant_area_weighted_field) && (coupling_group["resonant_area_weighted_field"] = state.resonant_area_weighted_field) !isempty(state.resonant_current) && (coupling_group["resonant_current"] = state.resonant_current) !isempty(state.island_width_sq) && (coupling_group["island_width_sq"] = state.island_width_sq) !isempty(state.penetrated_area_weighted_field) && (coupling_group["penetrated_area_weighted_field"] = state.penetrated_area_weighted_field) - !isempty(state.delta_prime) && (coupling_group["Delta_prime"] = state.delta_prime) + !isempty(state.delta_mn) && (coupling_group["Delta_mn"] = state.delta_mn) !isempty(state.forcing_solution_weights) && (coupling_group["forcing_solution_weights"] = state.forcing_solution_weights) !isempty(resp.rational_area) && (coupling_group["rational_area"] = resp.rational_area) !isempty(state.island_half_width) && (coupling_group["island_half_width"] = state.island_half_width) @@ -281,8 +281,8 @@ const PE_H5_ANNOTATIONS = [ "SingularCoupling/C_penetrated_area_weighted_field" => (; long_name="coupling matrix: applied b̃ → penetrated area-weighted field", dims=("surface", "mode"), attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), - "SingularCoupling/C_Delta_prime" => - (; long_name="coupling matrix: applied b̃ → forcing-driven Δ'", units="1/T", dims=("surface", "mode"), + "SingularCoupling/C_Delta_mn" => + (; long_name="coupling matrix: applied b̃ → Δ_mn, the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4 over 2π·χ₁", units="1/T", dims=("surface", "mode"), attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), "SingularCoupling/resonant_area_weighted_field" => (; long_name="resonant area-weighted field b̄^r = Φ^r/A^r per rational surface (coordinate-invariant)", units="T", dims=("surface",), @@ -296,8 +296,8 @@ const PE_H5_ANNOTATIONS = [ "SingularCoupling/penetrated_area_weighted_field" => (; long_name="penetrated area-weighted field per rational surface", units="T", dims=("surface",), attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), - "SingularCoupling/Delta_prime" => - (; long_name="forcing-driven tearing Δ' per rational surface (Riccati; response to applied forcing)", dims=("surface",), + "SingularCoupling/Delta_mn" => + (; long_name="forcing-driven Δ_mn per rational surface, the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4 over 2π·χ₁", dims=("surface",), attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), "SingularCoupling/forcing_solution_weights" => (; long_name="weights of the forcing solutions in the singular-coupling decomposition", dims=("surface",), diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index 6d29521518..81ee2960cd 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -158,7 +158,7 @@ include("display_check.jl") @test riccati.resp.permeability ≈ forward.resp.permeability rtol = 1e-6 @test riccati.resp.reluctance ≈ forward.resp.reluctance rtol = 1e-6 # The singular coupling reads ξ and ξ′ off each surface, where the two integrators' stored nodes differ. - for name in (:C_delta_prime, :C_resonant_current, :C_resonant_area_weighted_field, :C_island_width_sq) + for name in (:C_delta_mn, :C_resonant_current, :C_resonant_area_weighted_field, :C_island_width_sq) @test getfield(riccati.resp, name) ≈ getfield(forward.resp, name) rtol = 1e-3 end @test riccati.pe.resonant_area_weighted_field ≈ forward.pe.resonant_area_weighted_field rtol = 1e-4 diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index bfb88f843e..8f961c42a9 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -244,7 +244,7 @@ include("display_check.jl") @test resp isa PlasmaResponse && pe.response === resp @test !isempty(resp.permeability) @test resp.permeability ≈ reference.response.permeability rtol = 1e-10 - @test size(resp.C_delta_prime) == size(reference.response.C_delta_prime) + @test size(resp.C_delta_mn) == size(reference.response.C_delta_mn) @test !isempty(pe.resonant_area_weighted_field) # The deck reads and normalizes its forcing file exactly as a fresh RMPField does. From adc5e59af292b77a4579e2fcd2fce796f8eceb17 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 18 Nov 2026 22:45:36 +0100 Subject: [PATCH 13/27] =?UTF-8?q?PerturbedEquilibrium=20-=20FEATURE!=20-?= =?UTF-8?q?=20Add=20the=20asymptotic=20=CE=94=5Fmn=20metrics=20beside=20th?= =?UTF-8?q?e=20finite-width=20ones?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/src/perturbed_equilibrium.md | 3 + .../PerturbedEquilibriumStructs.jl | 20 +++++- src/PerturbedEquilibrium/ResonantCoupling.jl | 39 +++++++----- src/PerturbedEquilibrium/SingularCoupling.jl | 61 +++++++++++++++---- src/PerturbedEquilibrium/Utils.jl | 46 ++++++++++++++ test/runtests_dominant_coupling.jl | 61 +++++++++++++++++++ 6 files changed, 203 insertions(+), 27 deletions(-) diff --git a/docs/src/perturbed_equilibrium.md b/docs/src/perturbed_equilibrium.md index e13baa86b6..0d5c2e8e6c 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -43,6 +43,8 @@ The run writes up to five coupling matrices under `PerturbedEquilibrium/Singular | `C_penetrated_area_weighted_field` | the penetrated field, when the run computes it | dimensionless | | `C_Delta_mn` | the forcing-driven ``\Delta_{mn}`` | 1/T | +All but the penetrated field are built from the jump of ``\partial b^\psi/\partial\psi`` across ``|m - nq| = 5\times10^{-4}``. That jump depends on the width it is taken across wherever the Mercier index ``D_I \ne -1/4``, so a single-n run on a `"Riccati"` or `error_field_response` `"Galerkin"` solve also writes each of them with the suffix `_asymptotic`, built from the jump of the asymptotic small solution, which no width enters; the applied quantities carry the same suffix, and `ResonantCoupling(src; matrix=:resonant_area_weighted_field_asymptotic)` wraps that resonant-field matrix. + `ResonantCoupling` wraps the first; any of the others decomposes over any window of surfaces through the bare-matrix form of `dominant_coupling`, with the ``\tilde b`` conform taken from a `ResonantCoupling` of the same file, since the bare matrix carries no (m, n) labels for `check_mode_basis` to guard the projection: ```julia @@ -143,6 +145,7 @@ with the `RMPField` built from coils or a file as on the [Scripting API](api.md) | `PerturbedEquilibrium/SingularCoupling/chirikov_parameter` | ``\sigma_s`` | | | `PerturbedEquilibrium/SingularCoupling/Delta_mn` | the forcing-driven ``\Delta_{mn}`` per surface | | | `PerturbedEquilibrium/SingularCoupling/C_*` | the coupling matrices from the applied ``\tilde b`` to each quantity above | | +| `PerturbedEquilibrium/SingularCoupling/*_asymptotic` | the resonant field, current, island widths, Chirikov parameter, ``\Delta_{mn}`` and their `C_*` matrices from the jump of the asymptotic small solution | as above | | `PerturbedEquilibrium/SingularCoupling/DominantMode/singular_values`, `right_singular_vectors`, `left_singular_vectors`, `rational_index`, `forcing_overlap` | the core-window SVD of the resonant-field coupling | | | `PerturbedEquilibrium/Energies/plasma_energy`, `vacuum_energy`, `surface_energy` | the perturbed energies | J | | `PerturbedEquilibrium/Energies/toroidal_torque` | the boundary-response torque ``T_\phi`` | N·m | diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index 016405435b..73d640e5d5 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -77,8 +77,13 @@ applied root-area-weighted field b̃_x to the resonant response at that surface. - `C_island_width_sq` - (w/2)² coupling (singcoup row 3) - `C_penetrated_area_weighted_field` - Penetrated area-weighted field coupling (singcoup row 4) - `C_delta_mn` - Δ_mn coupling, the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4 over 2π·χ₁ (singcoup row 5) - - `coupling_flux::NamedTuple` - The same five matrices acting on the physical flux Φ_x (keys without the + - `coupling_flux::NamedTuple` - The same matrices acting on the physical flux Φ_x (keys without the `C_` prefix), used for the applied resonant vectors; empty when the coupling was not built. + - `C_resonant_area_weighted_field_asymptotic`, `C_resonant_current_asymptotic`, `C_island_width_sq_asymptotic`, + `C_delta_mn_asymptotic` - The same four built from the jump of the asymptotic small solution, + −2πi·χ₁·n·q′·(C_R − C_L), in place of the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. The two agree where D_I = −1/4; + elsewhere the finite-width matrices are (1/2 + √−D_I)·w^(√−D_I − 1/2) times these, w being that half-width in ψ_N. + Empty unless the result is single-`n` and carries `Delta_EF`. - `C_coeffs::Matrix{ComplexF64}` - Edge-to-solution coefficients `u_bnd⁻¹·edge_mn` of each unit forcing mode. Metadata [n_rational] — identifies each (surface, n) row: @@ -125,6 +130,10 @@ on a `ResonantCoupling`): C_island_width_sq::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) C_penetrated_area_weighted_field::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) C_delta_mn::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) + C_resonant_area_weighted_field_asymptotic::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) + C_resonant_current_asymptotic::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) + C_island_width_sq_asymptotic::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) + C_delta_mn_asymptotic::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) coupling_flux::NamedTuple = (;) C_coeffs::Matrix{ComplexF64} = zeros(ComplexF64, 0, 0) @@ -177,11 +186,14 @@ Matches Fortran `Phi_res`, `w_isl`, `K_isl`, `Delta`. - `resonant_area_weighted_field`, `resonant_current`, `island_width_sq`, `penetrated_area_weighted_field`, `delta_mn` - `forcing_solution_weights` - `C_coeffs`·Φ_x, the forcing's weights on the edge-driven solutions + - `resonant_area_weighted_field_asymptotic`, `resonant_current_asymptotic`, `island_width_sq_asymptotic`, `delta_mn_asymptotic` - + the same from the response's `_asymptotic` matrices; empty when it has none Diagnostics [n_rational]: - `island_half_width::Vector{Float64}` - w/2 = sqrt(|island_width_sq|) from applied forcing - `chirikov_parameter::Vector{Float64}` - Island overlap metric + - `island_half_width_asymptotic`, `chirikov_parameter_asymptotic` - the same from `island_width_sq_asymptotic` - `dominant_forcing_overlap` - Vᴴ·b̃_x, the applied forcing's coefficient on each dominant mode [rank] Control-surface forcing/response spectra [numpert_total], in the three Pharr (2026) field @@ -231,10 +243,16 @@ Torque response (kinetic forward solves with `compute_torque_response`): penetrated_area_weighted_field::Vector{ComplexF64} = ComplexF64[] delta_mn::Vector{ComplexF64} = ComplexF64[] forcing_solution_weights::Vector{ComplexF64} = ComplexF64[] + resonant_area_weighted_field_asymptotic::Vector{ComplexF64} = ComplexF64[] + resonant_current_asymptotic::Vector{ComplexF64} = ComplexF64[] + island_width_sq_asymptotic::Vector{ComplexF64} = ComplexF64[] + delta_mn_asymptotic::Vector{ComplexF64} = ComplexF64[] # Diagnostics [n_rational] island_half_width::Vector{Float64} = Float64[] chirikov_parameter::Vector{Float64} = Float64[] + island_half_width_asymptotic::Vector{Float64} = Float64[] + chirikov_parameter_asymptotic::Vector{Float64} = Float64[] dominant_forcing_overlap::Vector{ComplexF64} = ComplexF64[] # Vᴴ·b̃_x [rank] # Control-surface forcing/response spectra in the three weightings of field representations [numpert_total], tesla diff --git a/src/PerturbedEquilibrium/ResonantCoupling.jl b/src/PerturbedEquilibrium/ResonantCoupling.jl index 4ba63adbeb..05f73ae92a 100644 --- a/src/PerturbedEquilibrium/ResonantCoupling.jl +++ b/src/PerturbedEquilibrium/ResonantCoupling.jl @@ -28,30 +28,39 @@ struct ResonantCoupling flux_conform::Matrix{ComplexF64} end +# The coupling matrices that map b̃ to a field at the rational surfaces, by their name without the `C_` prefix. +const _FIELD_COUPLINGS = (:resonant_area_weighted_field, :resonant_area_weighted_field_asymptotic, :penetrated_area_weighted_field) +_check_field_coupling(matrix::Symbol) = matrix in _FIELD_COUPLINGS || throw(ArgumentError("matrix must be one of $(_FIELD_COUPLINGS), got :$matrix")) + """ - ResonantCoupling(resp::PlasmaResponse) + ResonantCoupling(resp::PlasmaResponse; matrix=:resonant_area_weighted_field) In-memory construction from a [`PlasmaResponse`](@ref): the coupling matrix, row and column labels -and conform operator all come from `resp`. Errors when `resp` carries no singular-coupling matrix. -""" -function ResonantCoupling(resp::PlasmaResponse) - isempty(resp.C_resonant_area_weighted_field) && - throw(ArgumentError("the plasma response carries no singular-coupling matrix (compute_singular_coupling off, or no resonant surfaces)")) - return ResonantCoupling(resp.C_resonant_area_weighted_field, resp.rational_psi, resp.rational_q, - resp.rational_m_res, resp.rational_n, resp.m_modes, resp.n_modes, resp.rootarea_to_area_weight .* resp.surface_area) +and conform operator all come from `resp`. `matrix` names the coupling to wrap, a `C_` field of `resp` without +the prefix: `:resonant_area_weighted_field`, `:resonant_area_weighted_field_asymptotic` or +`:penetrated_area_weighted_field`. Errors when `resp` does not carry it. +""" +function ResonantCoupling(resp::PlasmaResponse; matrix::Symbol=:resonant_area_weighted_field) + _check_field_coupling(matrix) + C = getfield(resp, Symbol(:C_, matrix)) + isempty(C) && throw(ArgumentError("the plasma response carries no C_$matrix (compute_singular_coupling off, no resonant surfaces, " * + "or a result that cannot supply it)")) + return ResonantCoupling(C, resp.rational_psi, resp.rational_q, resp.rational_m_res, resp.rational_n, resp.m_modes, resp.n_modes, + resp.rootarea_to_area_weight .* resp.surface_area) end """ - ResonantCoupling(h5path::AbstractString) + ResonantCoupling(h5path::AbstractString; matrix=:resonant_area_weighted_field) Post-hoc construction from a `gpec.h5` written with both the response and singular-coupling -steps enabled: reads `PerturbedEquilibrium/SingularCoupling/`, the stored conform operator under -`PerturbedEquilibrium/ResponseMatrices/`, and the column labels from `Info/mn_index`. +steps enabled: reads `C_` and the row labels from `PerturbedEquilibrium/SingularCoupling/`, the stored +conform operator under `PerturbedEquilibrium/ResponseMatrices/`, and the column labels from `Info/mn_index`. """ -function ResonantCoupling(h5path::AbstractString) +function ResonantCoupling(h5path::AbstractString; matrix::Symbol=:resonant_area_weighted_field) + _check_field_coupling(matrix) h5open(h5path, "r") do f - haskey(f, "PerturbedEquilibrium/SingularCoupling/C_resonant_area_weighted_field") || - throw(ArgumentError("$h5path has no singular-coupling matrix")) + haskey(f, "PerturbedEquilibrium/SingularCoupling/C_$matrix") || + throw(ArgumentError("$h5path has no singular-coupling matrix C_$matrix")) haskey(f, "PerturbedEquilibrium/ResponseMatrices/rootarea_to_area_weight_operator") || throw(ArgumentError("$h5path has no control-surface conform operator")) haskey(f, "Info/mn_index") || throw(ArgumentError("$h5path has no Info/mn_index mode labels")) @@ -59,7 +68,7 @@ function ResonantCoupling(h5path::AbstractString) mn = read(f["Info/mn_index"]) S = read(f["PerturbedEquilibrium/ResponseMatrices/rootarea_to_area_weight_operator"]) A = read(f["PerturbedEquilibrium/ResponseMatrices/surface_area"]) - return ResonantCoupling(read(sc["C_resonant_area_weighted_field"]), read(sc["rational_psi"]), read(sc["rational_q"]), + return ResonantCoupling(read(sc["C_$matrix"]), read(sc["rational_psi"]), read(sc["rational_q"]), read(sc["rational_m"]), read(sc["rational_n"]), mn[:, 1], mn[:, 2], S .* A) end end diff --git a/src/PerturbedEquilibrium/SingularCoupling.jl b/src/PerturbedEquilibrium/SingularCoupling.jl index d1924f8ddc..bb67609cc1 100644 --- a/src/PerturbedEquilibrium/SingularCoupling.jl +++ b/src/PerturbedEquilibrium/SingularCoupling.jl @@ -220,6 +220,10 @@ resonant area-weighted field, current, (w/2)², penetrated field and Δ_mn per u the rational-surface metadata and the edge-to-solution coefficients `C_coeffs`. The matrices are stored acting on b̃_x, with flux-space copies in `resp.coupling_flux` for applying a forcing. +Δ_mn, the current, the field and (w/2)² are built from the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. A single-`n` +result with `Delta_EF` also gets them from the jump of the asymptotic small solution, −2πi·χ₁·n·q′·(C_R − C_L), +in the `_asymptotic` matrices; those are empty otherwise. + ## Normalization - Rows: the resonant and penetrated rows are a resonant flux divided by that surface's own area @@ -293,6 +297,14 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resp.rational_n = zeros(Int, n_rational) resp.rational_surface_idx = zeros(Int, n_rational) resp.rational_area = zeros(Float64, n_rational) + # The asymptotic rows need Δ_EF, each surface's left and right small-solution coefficients per unit edge displacement. + dp = ffs.delta_prime + have_ef = ffs.npert == 1 && dp !== nothing && size(dp.ef) == (2msing, numpert_total) + asymptotic_size = have_ef ? (n_rational, numpert_total) : (0, 0) + resp.C_resonant_area_weighted_field_asymptotic = zeros(ComplexF64, asymptotic_size) + resp.C_resonant_current_asymptotic = zeros(ComplexF64, asymptotic_size) + resp.C_island_width_sq_asymptotic = zeros(ComplexF64, asymptotic_size) + resp.C_delta_mn_asymptotic = zeros(ComplexF64, asymptotic_size) # Edge-to-solution coefficients C_coeffs = u_bnd⁻¹·edge_mn, edge_mn = P/(chi1·singfac_lim·2πi) (Fortran gpout_resp) psi_lim = solution.psi_store[solution.step] @@ -378,15 +390,26 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) end # Δ_mn is the ∂b^ψ/∂ψ jump, stored over 2π·χ₁; j_c carries the surface Jacobian weighting of the current; - # resonant flux/area is a coordinate-invariant field in T [Park 2008; Pharr 2026]. - resp.C_delta_mn[row, :] = jump_vec ./ (twopi * chi1) - resp.C_resonant_current[row, :] = jump_vec .* (-j_c / (twopi * m_res)) - # Matches Fortran gpout_resp: singflx = L·fkaxmn, resonant area-weighted field = singflx/area, - # islandhwids = 4·singflx/(2π·shear·q·chi1) - singflx_pre = (L_mm / (twopi * nn)) .* resp.C_resonant_current[row, :] - resp.C_resonant_area_weighted_field[row, :] = singflx_pre ./ area - if abs(shear) > 1e-10 - resp.C_island_width_sq[row, :] = (4.0 / (twopi * shear * sing_surf.q * chi1)) .* singflx_pre + # resonant flux/area is a coordinate-invariant field in T [Park 2008; Pharr 2026]. Matches Fortran gpout_resp: + # singflx = L·fkaxmn, resonant area-weighted field = singflx/area, islandhwids = 4·singflx/(2π·shear·q·chi1). + function coupling_rows(jump) + resonant_current = jump .* (-j_c / (twopi * m_res)) + singflx = (L_mm / (twopi * nn)) .* resonant_current + island_width_sq = abs(shear) > 1e-10 ? (4.0 / (twopi * shear * sing_surf.q * chi1)) .* singflx : zero(singflx) + return (; delta_mn=jump ./ (twopi * chi1), resonant_current, resonant_area_weighted_field=singflx ./ area, island_width_sq) + end + rows = coupling_rows(jump_vec) + resp.C_delta_mn[row, :] = rows.delta_mn + resp.C_resonant_current[row, :] = rows.resonant_current + resp.C_resonant_area_weighted_field[row, :] = rows.resonant_area_weighted_field + resp.C_island_width_sq[row, :] = rows.island_width_sq + if have_ef + # Asymptotic jump −2πi·χ₁·n·q′·(C_R − C_L): the right and left rows of Δ_EF on the edge displacement of each forcing mode. + rows = coupling_rows((-2π * im * chi1 * nn * sing_surf.q1) .* (transpose(edge_mn) * (dp.ef[2s, :] .- dp.ef[2s-1, :]))) + resp.C_delta_mn_asymptotic[row, :] = rows.delta_mn + resp.C_resonant_current_asymptotic[row, :] = rows.resonant_current + resp.C_resonant_area_weighted_field_asymptotic[row, :] = rows.resonant_area_weighted_field + resp.C_island_width_sq_asymptotic[row, :] = rows.island_width_sq end resp.rational_psi[row] = sing_surf.psifac @@ -408,12 +431,20 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) # Conform the stored matrices to b̃ space, C̃ = C·R with R = S·A (Pharr 2026); `coupling_flux` keeps the flux-space # copies so a forcing is applied without round-trip noise. resp.coupling_flux = (; resonant_area_weighted_field=resp.C_resonant_area_weighted_field, resonant_current=resp.C_resonant_current, - island_width_sq=resp.C_island_width_sq, penetrated_area_weighted_field=resp.C_penetrated_area_weighted_field, delta_mn=resp.C_delta_mn) + island_width_sq=resp.C_island_width_sq, penetrated_area_weighted_field=resp.C_penetrated_area_weighted_field, delta_mn=resp.C_delta_mn, + resonant_area_weighted_field_asymptotic=resp.C_resonant_area_weighted_field_asymptotic, resonant_current_asymptotic=resp.C_resonant_current_asymptotic, + island_width_sq_asymptotic=resp.C_island_width_sq_asymptotic, delta_mn_asymptotic=resp.C_delta_mn_asymptotic) flux_conform = resp.rootarea_to_area_weight .* resp.surface_area resp.C_resonant_area_weighted_field = resp.C_resonant_area_weighted_field * flux_conform resp.C_resonant_current = resp.C_resonant_current * flux_conform resp.C_island_width_sq = resp.C_island_width_sq * flux_conform resp.C_delta_mn = resp.C_delta_mn * flux_conform + if have_ef + resp.C_resonant_area_weighted_field_asymptotic = resp.C_resonant_area_weighted_field_asymptotic * flux_conform + resp.C_resonant_current_asymptotic = resp.C_resonant_current_asymptotic * flux_conform + resp.C_island_width_sq_asymptotic = resp.C_island_width_sq_asymptotic * flux_conform + resp.C_delta_mn_asymptotic = resp.C_delta_mn_asymptotic * flux_conform + end have_inner_bpen && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * flux_conform) return resp @@ -424,7 +455,7 @@ end Apply the coupling matrices of `state.response` to the forcing on `state`: the applied resonant vectors (Fortran `Phi_res`, `w_isl`, `K_isl`, `Delta`), the forcing's solution weights, and the island -half-widths and Chirikov overlap. +half-widths and Chirikov overlap, each also in its `_asymptotic` form when the response carries those matrices. """ function apply_coupling!(state::PerturbedEquilibriumState; verbose::Bool=false) resp = state.response @@ -447,6 +478,14 @@ function apply_coupling!(state::PerturbedEquilibriumState; verbose::Bool=false) # Island diagnostics from the applied resonant vectors state.island_half_width, state.chirikov_parameter = island_diagnostics(state.island_width_sq, resp.rational_psi, resp.rational_surface_idx) + if !isempty(C.delta_mn_asymptotic) + state.resonant_area_weighted_field_asymptotic = C.resonant_area_weighted_field_asymptotic * forcing_flux + state.resonant_current_asymptotic = C.resonant_current_asymptotic * forcing_flux + state.island_width_sq_asymptotic = C.island_width_sq_asymptotic * forcing_flux + state.delta_mn_asymptotic = C.delta_mn_asymptotic * forcing_flux + state.island_half_width_asymptotic, state.chirikov_parameter_asymptotic = + island_diagnostics(state.island_width_sq_asymptotic, resp.rational_psi, resp.rational_surface_idx) + end if verbose max_island = isempty(state.island_half_width) ? 0.0 : maximum(state.island_half_width) diff --git a/src/PerturbedEquilibrium/Utils.jl b/src/PerturbedEquilibrium/Utils.jl index 607506c3eb..5241167121 100644 --- a/src/PerturbedEquilibrium/Utils.jl +++ b/src/PerturbedEquilibrium/Utils.jl @@ -138,6 +138,22 @@ function save_to_hdf5(file::Union{HDF5.File,HDF5.Group}, state::PerturbedEquilib !isempty(state.island_half_width) && (coupling_group["island_half_width"] = state.island_half_width) !isempty(state.chirikov_parameter) && (coupling_group["chirikov_parameter"] = state.chirikov_parameter) + # The same matrices and applied vectors from the jump of the asymptotic small solution + if !isempty(resp.C_delta_mn_asymptotic) + coupling_group["C_resonant_area_weighted_field_asymptotic"] = resp.C_resonant_area_weighted_field_asymptotic + coupling_group["C_resonant_current_asymptotic"] = resp.C_resonant_current_asymptotic + coupling_group["C_island_width_sq_asymptotic"] = resp.C_island_width_sq_asymptotic + coupling_group["C_Delta_mn_asymptotic"] = resp.C_delta_mn_asymptotic + end + if !isempty(state.delta_mn_asymptotic) + coupling_group["resonant_area_weighted_field_asymptotic"] = state.resonant_area_weighted_field_asymptotic + coupling_group["resonant_current_asymptotic"] = state.resonant_current_asymptotic + coupling_group["island_width_sq_asymptotic"] = state.island_width_sq_asymptotic + coupling_group["Delta_mn_asymptotic"] = state.delta_mn_asymptotic + coupling_group["island_half_width_asymptotic"] = state.island_half_width_asymptotic + coupling_group["chirikov_parameter_asymptotic"] = state.chirikov_parameter_asymptotic + end + # Metadata [n_rational] !isempty(resp.rational_psi) && (coupling_group["rational_psi"] = resp.rational_psi) !isempty(resp.rational_q) && (coupling_group["rational_q"] = resp.rational_q) @@ -310,6 +326,36 @@ const PE_H5_ANNOTATIONS = [ "SingularCoupling/chirikov_parameter" => (; long_name="Chirikov overlap parameter: island half-width / half-distance to the neighbouring rational surface", dims=("surface",), attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/C_resonant_area_weighted_field_asymptotic" => + (; long_name="coupling matrix: applied b̃ → resonant area-weighted field, from the jump of the asymptotic small solution", dims=("surface", "mode"), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/C_resonant_current_asymptotic" => + (; long_name="coupling matrix: applied b̃ → pitch-resonant current, from the jump of the asymptotic small solution", units="A/T", dims=("surface", "mode"), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/C_island_width_sq_asymptotic" => + (; long_name="coupling matrix: applied b̃ → squared island half-width, from the jump of the asymptotic small solution", units="1/T", dims=("surface", "mode"), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/C_Delta_mn_asymptotic" => + (; long_name="coupling matrix: applied b̃ → Δ_mn of the asymptotic small solution, −2πi·χ₁·n·q′·(C_R − C_L) over 2π·χ₁", units="1/T", dims=("surface", "mode"), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/resonant_area_weighted_field_asymptotic" => + (; long_name="resonant area-weighted field per rational surface, from the jump of the asymptotic small solution", units="T", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/resonant_current_asymptotic" => + (; long_name="pitch-resonant current per rational surface, from the jump of the asymptotic small solution", units="A", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/island_width_sq_asymptotic" => + (; long_name="squared island half-width per rational surface (in ψ_N²), from the jump of the asymptotic small solution", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/Delta_mn_asymptotic" => + (; long_name="forcing-driven Δ_mn of the asymptotic small solution per rational surface, over 2π·χ₁", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/island_half_width_asymptotic" => + (; long_name="island half-width per rational surface (in ψ_N), from the jump of the asymptotic small solution", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), + "SingularCoupling/chirikov_parameter_asymptotic" => + (; long_name="Chirikov overlap parameter from the asymptotic island half-widths", dims=("surface",), + attach=(1 => "SingularCoupling/rational_psi", 1 => "SingularCoupling/rational_q")), "SingularCoupling/rational_psi" => (; long_name="normalized poloidal flux ψ_N of each rational surface", scale="psi_rational"), "SingularCoupling/rational_q" => (; long_name="safety factor q = m/n at each rational surface", dims=("surface",), scale="q_rational", attach=(1 => "SingularCoupling/rational_psi",)), diff --git a/test/runtests_dominant_coupling.jl b/test/runtests_dominant_coupling.jl index 9a4b0fad18..af9333dc9f 100644 --- a/test/runtests_dominant_coupling.jl +++ b/test/runtests_dominant_coupling.jl @@ -145,6 +145,67 @@ include("h5_metadata_check.jl") @test read(g["forcing_overlap"]) ≈ pe.dominant_forcing_overlap @test isempty(_collect_metadata_violations(h5)) end + + # A Forward result carries no Δ_EF, so the asymptotic set is left empty. + @test isempty(resp.C_delta_mn_asymptotic) && isempty(pe.delta_mn_asymptotic) && isempty(pe.island_half_width_asymptotic) + @test_throws ArgumentError PE.ResonantCoupling(resp; matrix=:resonant_area_weighted_field_asymptotic) + @test_throws ArgumentError PE.ResonantCoupling(h5path; matrix=:resonant_area_weighted_field_asymptotic) + @test_throws ArgumentError PE.ResonantCoupling(resp; matrix=:resonant_current) + end + end + + @testset "asymptotic Δ_mn metrics beside the finite-width ones" begin + template = joinpath(@__DIR__, "test_data", "regression_tj_ideal_example") + function riccati_run(dir, p0) + for name in readdir(template) + cp(joinpath(template, name), joinpath(dir, name)) + end + cp(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"), joinpath(dir, "forcing.dat")) + inputs = TOML.parsefile(joinpath(dir, "gpec.toml")) + inputs["ForceFreeStates"]["integrator"] = "Riccati" + inputs["Riccati"] = pop!(inputs, "Forward") + inputs["TJAnalytic"]["p0"] = p0 + inputs["ForcingTerms"] = Dict{String,Any}("forcing_data_file" => "forcing.dat", "forcing_data_format" => "ascii") + inputs["PerturbedEquilibrium"] = Dict{String,Any}("compute_singular_coupling" => true) + open(io -> TOML.print(io, inputs), joinpath(dir, "gpec.toml"), "w") + return GPEC.main([dir]) + end + + # Without pressure D_I = −1/4 and the jump does not depend on the width it is taken across. + mktempdir() do dir + run = riccati_run(dir, 0.0) + resp, pe = run.resp, run.pe + for name in (:C_delta_mn, :C_resonant_current, :C_resonant_area_weighted_field, :C_island_width_sq) + @test getfield(resp, Symbol(name, :_asymptotic)) ≈ getfield(resp, name) rtol = 5e-3 + end + for name in (:delta_mn, :resonant_current, :resonant_area_weighted_field, :island_width_sq, :island_half_width, :chirikov_parameter) + @test getfield(pe, Symbol(name, :_asymptotic)) ≈ getfield(pe, name) rtol = 5e-3 + end + + rc = PE.ResonantCoupling(resp; matrix=:resonant_area_weighted_field_asymptotic) + @test rc.C == resp.C_resonant_area_weighted_field_asymptotic + @test PE.ResonantCoupling(joinpath(dir, "gpec.h5"); matrix=:resonant_area_weighted_field_asymptotic).C ≈ rc.C + h5open(joinpath(dir, "gpec.h5"), "r") do h5 + g = h5["PerturbedEquilibrium/SingularCoupling"] + @test read(g["C_Delta_mn_asymptotic"]) ≈ resp.C_delta_mn_asymptotic + @test read(g["Delta_mn"]) ≈ pe.delta_mn + @test read(g["island_half_width_asymptotic"]) ≈ pe.island_half_width_asymptotic + @test isempty(_collect_metadata_violations(h5)) + end + end + + # With pressure the finite-width jump is (1/2 + α)·w^(α − 1/2) times the asymptotic one, α = √−D_I. + mktempdir() do dir + run = riccati_run(dir, 0.1) + resp = run.resp + for row in eachindex(resp.rational_psi) + surf = run.ffs.surfaces[resp.rational_surface_idx[row]] + α = sqrt(-GPEC.LocalStability.mercier_D_I(run.local_stability, surf.psifac)) + w = 5e-4 / abs(resp.rational_n[row] * surf.q1) + ratio = norm(resp.C_delta_mn[row, :]) / norm(resp.C_delta_mn_asymptotic[row, :]) + @test ratio ≈ (0.5 + α) * w^(α - 0.5) rtol = 3e-2 + end + @test norm(resp.C_delta_mn[1, :]) < 0.9 * norm(resp.C_delta_mn_asymptotic[1, :]) end end end From bbd1215675d5e02ec73055f82f69ee235f1ceddb Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 23 Nov 2026 16:35:55 +0100 Subject: [PATCH 14/27] PerturbedEquilibrium - FEATURE! - Accept matched results with only the asymptotic singular-coupling metrics, and require a free-boundary result --- docs/src/api.md | 2 +- docs/src/stability.md | 1 + .../cases/gal_resistive_diiid.toml | 8 +- src/Display.jl | 7 +- src/ForceFreeStates/EulerLagrange.jl | 2 + src/ForceFreeStates/Galerkin/GalerkinSolve.jl | 1 + src/ForceFreeStates/Matching/MatchProblem.jl | 26 ++-- src/ForceFreeStates/Matching/ResonantMatch.jl | 20 +-- src/ForceFreeStates/Output.jl | 1 + src/ForceFreeStates/Result.jl | 14 +- src/ForceFreeStates/Riccati/Driver.jl | 2 + src/ForceFreeStates/Surfaces/Types.jl | 4 + .../PerturbedEquilibrium.jl | 24 ++- .../PerturbedEquilibriumStructs.jl | 4 +- src/PerturbedEquilibrium/SingularCoupling.jl | 144 +++++++++--------- src/Utilities/HDF5Schema.jl | 3 + test/runtests_result_struct.jl | 19 ++- test/runtests_solve_api.jl | 44 ++++-- 18 files changed, 185 insertions(+), 141 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 3a37894470..9423892e7b 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -140,7 +140,7 @@ A `MatchProblem` holds the outer Δ′ a solve published plus per-surface layer ```julia ffs = solve(eq, Galerkin(; error_field_response=true, cut_solution=true); nn=1) matched = solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=0.0), GGJModel()) -bpens = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).bpen for f in 0.0:50.0:500.0] +penetrated_fields = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).penetrated_area_weighted_field for f in 0.0:50.0:500.0] ``` A scalar applies to every surface and a vector gives one value per entry of `ffs.surfaces`, core to edge. diff --git a/docs/src/stability.md b/docs/src/stability.md index e735016e9d..ce22828f2e 100644 --- a/docs/src/stability.md +++ b/docs/src/stability.md @@ -102,6 +102,7 @@ The number of Julia threads is set at startup (`-t N` or `JULIA_NUM_THREADS`); t | `ForceFreeStates/LayerOverlap/` | the resistive-layer overlap scan, when `psilim_from_layer_overlap` is set (table below) | | `SingularSurfaces/rational_psi`, `rational_q`, `rational_m`, `rational_n`, `dqdpsi` | the rational surfaces of the domain, core to edge | | `SingularSurfaces/D_I`, `E`, `F`, `G`, `H`, `K`, `M` | the Mercier index and the Glasser–Greene–Johnson layer coefficients at each surface | +| `SingularSurfaces/alpha` | the Mercier exponent ``\alpha = \sqrt{-D_I}`` the solve's asymptotic series used at each surface; it approaches the value from `D_I` as `delta_mlow` and `delta_mhigh` are raised | | `SingularSurfaces/ca_left`, `ca_right` | the asymptotic (large, small) coefficients on either side of each surface, from ideal crossings | | `SingularSurfaces/Delta_prime_matrix` | the free-boundary Δ′ matrix in the PEST-3 convention, from `"Riccati"` or `"Galerkin"`, with `pest3_A`, `pest3_B`, `pest3_Gamma`; `Delta_prime_raw_freeboundary` is the side-major (left, right) matrix they are folded from. The same set with a `_fixedboundary` suffix is the Δ′ with a conformal wall on the plasma, `Delta_EF` the error-field response, and `edge_response` the edge momentum of each fixed-boundary big-solution column (what matching needs for the matched `W_plasma`) | | `SingularSurfaces/Kinetic/` | the surfaces of a kinetic solve | diff --git a/regression-harness/cases/gal_resistive_diiid.toml b/regression-harness/cases/gal_resistive_diiid.toml index 8b8dceecd7..8fef96f539 100644 --- a/regression-harness/cases/gal_resistive_diiid.toml +++ b/regression-harness/cases/gal_resistive_diiid.toml @@ -103,12 +103,12 @@ label = "||gal match cout||" noise_threshold = 1e-6 order = 42 -# Penetrated resonant field at each layer center (msing × nef) — the headline matching output. -[quantities.gal_match_bpen_norm] -h5path = "SingularSurfaces/Match/bpen" +# Penetrated area-weighted field at each layer center (msing × nef), in T — the headline matching output. +[quantities.gal_match_penetrated_field_norm] +h5path = "SingularSurfaces/Match/penetrated_area_weighted_field" type = "complex_matrix" extract = "norm" -label = "||gal match bpen||" +label = "||gal match penetrated area-weighted field||" noise_threshold = 1e-6 order = 43 diff --git a/src/Display.jl b/src/Display.jl index 26a949ae39..b08730f555 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -219,6 +219,8 @@ function Base.show(io::IO, ::MIME"text/plain", r::ForceFreeStates.ForceFreeState _row(io, "Domain", "ψ ∈ [$(_fmt(r.psilow)), $(_fmt(r.psilim))], q_lim = $(_fmt(r.qlim))" * (r.layer_overlap === nothing ? "" : " (capped by layer overlap)")) surf = isempty(r.surfaces) ? "none" : _list(["$(_surface_label(s)) @ ψ = $(_fmt(s.psifac))" for s in r.surfaces]; max=4) _row(io, "Surfaces", "$(length(r.surfaces)): " * surf) + isempty(r.surfaces) || any(s -> isempty(s.alpha), r.surfaces) || + _row(io, "Mercier α − ½", _list(["$(_surface_label(s)): $(_fmt(real(s.alpha[1]) - 0.5))" for s in r.surfaces]; max=4)) _row(io, "Fixed boundary", _fixed_boundary_note(r)) _row(io, "Free boundary", _free_boundary_note(r)) if r.delta_prime !== nothing @@ -275,7 +277,10 @@ function Base.show(io::IO, ::MIME"text/plain", r::PlasmaResponse) _row(io, "Modes", "n = $(_irange(r.n_modes)), m = $(_irange(r.m_modes)) ($(length(r.m_modes)) total)") _row(io, "Operators", isempty(r.permeability_flux) ? _missing_operators_note(r) : "permeability, inductances $(_shape(r.permeability_flux))") _row(io, "Resonances", isempty(r.rational_psi) ? "none" : _list(_resonances(r))) - _row(io, "Coupling", isempty(r.C_resonant_area_weighted_field) ? _missing_coupling_note(r) : "C $(_shape(r.C_resonant_area_weighted_field))") + coupling = + !isempty(r.C_resonant_area_weighted_field) ? "C $(_shape(r.C_resonant_area_weighted_field))" : + !isempty(r.C_delta_mn_asymptotic) ? "asymptotic only, C $(_shape(r.C_delta_mn_asymptotic))" : _missing_coupling_note(r) + _row(io, "Coupling", coupling) isempty(r.dominant_singular_values) || _row(io, "Dominant σ", _list(_fmt.(r.dominant_singular_values); max=3)) _row(io, "Torque resp.", isempty(r.T_xe) ? "not computed" : "T_xe $(_shape(r.T_xe))") r.unit_edge_basis && _row(io, "Basis", "unit edge displacement") diff --git a/src/ForceFreeStates/EulerLagrange.jl b/src/ForceFreeStates/EulerLagrange.jl index 9391ce4544..e0f20cdafe 100644 --- a/src/ForceFreeStates/EulerLagrange.jl +++ b/src/ForceFreeStates/EulerLagrange.jl @@ -261,6 +261,8 @@ function forward_eulerlagrange_integration(ctrl::ForceFreeStatesControl, equil:: chunks = chunk_el_integration_bounds(odet, ctrl, intr) bases = ctrl.kinetic === nothing ? asymptotic_bases(chunks, ctrl, equil, mats, intr) : nothing + # Each crossed surface publishes the exponent its series used. + bases === nothing || foreach(((ising, basis),) -> intr.sing[ising].alpha = basis.right_series.alpha, pairs(bases)) if verbose @info " ψ = $((@sprintf "%.3f" odet.psifac)), q = $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac)))" diff --git a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl index bc70b23969..508b218736 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinSolve.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinSolve.jl @@ -139,6 +139,7 @@ function galerkin_solve(ctrl::ForceFreeStatesControl, equil, mats::MatrixSplines end al = compute_sing_asymptotics(s, ctrl, equil, mats, intr; sig=-1.0, sing_order=sing_order) push!(asymps, GalSingAsymp(ar, al)) + s.alpha = ar.alpha end # --- allocate workspace --- diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index 1f3b48153b..b9c51d9be4 100644 --- a/src/ForceFreeStates/Matching/MatchProblem.jl +++ b/src/ForceFreeStates/Matching/MatchProblem.jl @@ -7,8 +7,8 @@ Driven inner-layer matching on a finished force-free-states solve `ffs`: each rational surface is matched at the forced eigenvalue γ = 2πi·n·f, with f the plasma rotation frequency there. -`solve(prob, GGJModel())` (or another toroidal layer model, e.g. `CCCModel()`) returns a copy of `ffs` with the matched solution and the penetrated -field `bpen`. `ffs` needs `Delta_EF`, from `Galerkin()` or `Riccati()` with `error_field_response` (Riccati +`solve(prob, GGJModel())` (or another toroidal layer model, e.g. `CCCModel()`) returns a copy of `ffs` with the matched solution and its +`penetrated_area_weighted_field`. `ffs` needs `Delta_EF`, from `Galerkin()` or `Riccati()` with `error_field_response` (Riccati also needs `vac_flag`). # Keywords @@ -90,7 +90,7 @@ closure_capable(::InnerLayer.SLAYERModel) = false """ solve(prob::MatchProblem, model) -> ForceFreeStatesResult -Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched`, `bpen`, the +Match `prob.ffs` to the inner layer of `model`. The result has `closure = :matched`, `penetrated_area_weighted_field`, the [`MatchResult`](@ref) in `result.match`, the matched ξ, the matched edge response `wp` (see [`ForceFreeStatesResult`](@ref)) and, when the solve had `vac_flag`, the free-boundary energies of that response. """ @@ -155,10 +155,14 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel cout, cin, residual = _match_system(dp.raw_fixedboundary, dp.ef, deltar) - # Penetrated field at each layer center (match.f intotsol_b); cin rows per surface are (d₊, d₋). - bpen = zeros(ComplexF64, msing, nef) - for i in 1:msing, j in 1:nef - bpen[i, j] = pen[i, 1] * cin[2i-1, j] + pen[i, 2] * cin[2i, j] + # Penetrated 𝒥b^ψ at each layer center (match.f intotsol_b) over the surface area, in T; cin rows per surface are (d₊, d₋). + mthsurf = length(equil.rzphi_ys) - 1 + penetrated_area_weighted_field = zeros(ComplexF64, msing, nef) + for i in 1:msing + area = Equilibrium.flux_surface_area(equil, sings[i].psifac, mthsurf) + for j in 1:nef + penetrated_area_weighted_field[i, j] = (pen[i, 1] * cin[2i-1, j] + pen[i, 2] * cin[2i, j]) / area + end end # Matched inner ξ_ψ and b^ψ per EF column: odd parity × cin[2i], even × cin[2i-1] (match.f intotsol). @@ -171,7 +175,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel inner_b = Matrix{ComplexF64}[] end - reconnected_flux = Matrix{ComplexF64}(dp.ef .+ transpose(dp.raw_fixedboundary) * cout) + small_coefficients = Matrix{ComplexF64}(dp.ef .+ transpose(dp.raw_fixedboundary) * cout) # Matched outer ξ per EF column: EF column + Σ cout·plasma columns. if basis === nothing @@ -202,7 +206,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel sols_cut = basis.xi_cut if isempty(sols_cut) @warn "MatchProblem: the solve retained no cut solution (set cut_solution=true on Galerkin), " * - "so the composite inner-region profiles are skipped; bpen and the matched outer ξ are unaffected" maxlog = 1 + "so the composite inner-region profiles are skipped; the penetrated field and the matched outer ξ are unaffected" maxlog = 1 empty!(inner_psi) empty!(inner_xi) empty!(inner_b) @@ -249,7 +253,7 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel end end - return MatchResult(cout, cin, deltar, forced_eigenvalue, residual, bpen, reconnected_flux, + return MatchResult(cout, cin, deltar, forced_eigenvalue, residual, penetrated_area_weighted_field, small_coefficients, xi, xi_deriv, inner_psi, inner_xi, inner_b, inner_params, model, prob) end @@ -265,7 +269,7 @@ function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult) wp = ffs.wp + dp.edge_response * match.cout ./ ffs.equil.psio^2 ffs.free_boundary === nothing || (free_boundary = free_run(wp, ffs.control, ffs.equil, ffs.mats, ffs)) end - return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, wp=wp, free_boundary=free_boundary) + return _with(ffs; closure=:matched, penetrated_area_weighted_field=match.penetrated_area_weighted_field, match=match, solution=solution, wp=wp, free_boundary=free_boundary) end # A copy of the immutable `x` with the named fields replaced. diff --git a/src/ForceFreeStates/Matching/ResonantMatch.jl b/src/ForceFreeStates/Matching/ResonantMatch.jl index c5e76448ea..4d76e05879 100644 --- a/src/ForceFreeStates/Matching/ResonantMatch.jl +++ b/src/ForceFreeStates/Matching/ResonantMatch.jl @@ -14,8 +14,8 @@ fields are empty when the solve kept no Galerkin basis. - `deltar`: `(msing, 2)` inner-layer Δ per surface, columns (Δ₊, Δ₋) = (interchange, tearing). - `forced_eigenvalue`: forced eigenvalue γ = 2πi·n·f per surface. - `residual`: relative residual of the linear solve. - - `bpen`: `(msing, nef)` penetrated resonant field at each layer center. - - `reconnected_flux`: `(2msing, nef)` `Δ_EF + Δ_outᵀ·cout`. + - `penetrated_area_weighted_field`: `(msing, nef)` penetrated 𝒥b^ψ at each layer center over the surface area, in T. + - `small_coefficients`: `(2msing, nef)` outer small-solution coefficient left and right of each surface, `Δ_EF + Δ_outᵀ·cout`. - `xi`, `xi_deriv`: `(mpert, ngrid, nef)` matched outer ξ and ξ′, one column per EF column. - `inner_psi`, `inner_xi`, `inner_b`: per surface, the inner ψ grid and the composite ξ_ψ and b^ψ on it; empty unless the inner model returns real-ψ profiles (`GGJModel(; solver=:galerkin)` or `GGJModel(; real_profiles=true)`). @@ -29,8 +29,8 @@ struct MatchResult{P} deltar::Matrix{ComplexF64} forced_eigenvalue::Vector{ComplexF64} residual::Float64 - bpen::Matrix{ComplexF64} - reconnected_flux::Matrix{ComplexF64} + penetrated_area_weighted_field::Matrix{ComplexF64} + small_coefficients::Matrix{ComplexF64} xi::Array{ComplexF64,3} xi_deriv::Array{ComplexF64,3} inner_psi::Vector{Vector{Float64}} @@ -80,8 +80,8 @@ function save_to_hdf5(out_h5::Union{HDF5.File,HDF5.Group}, m::MatchResult) out_h5["$g/cout"] = m.cout out_h5["$g/cin"] = m.cin out_h5["$g/Delta_r"] = m.deltar - out_h5["$g/bpen"] = m.bpen - out_h5["$g/reconnected_flux"] = m.reconnected_flux + out_h5["$g/penetrated_area_weighted_field"] = m.penetrated_area_weighted_field + out_h5["$g/small_coefficients"] = m.small_coefficients out_h5["$g/forced_eigenvalue"] = m.forced_eigenvalue # Per-surface inner-layer ξ_ψ(ψ) (match.f intotsol); ragged grids → one dataset pair per surface. for i in eachindex(m.inner_psi) @@ -113,10 +113,10 @@ const MATCH_H5_ANNOTATIONS = [ (; long_name="inner-region matching coefficients per surface parity, per unit EF column", dims=("surface_parity", "ef")), "SingularSurfaces/Match/Delta_r" => (; long_name="inner-layer Δ per surface and parity, (Δ₊ interchange, Δ₋ tearing)", dims=("surface", "parity")), - "SingularSurfaces/Match/bpen" => - (; long_name="penetrated resonant field b^ψ at each layer center, per unit EF column", dims=("surface", "ef")), - "SingularSurfaces/Match/reconnected_flux" => - (; long_name="reconnected flux Δ_EF + Δ_outᵀ·cout per surface parity, per unit EF column", dims=("surface_parity", "ef")), + "SingularSurfaces/Match/penetrated_area_weighted_field" => + (; long_name="penetrated area-weighted field 𝒥b^ψ/A at each layer center, per unit EF column", units="T", dims=("surface", "ef")), + "SingularSurfaces/Match/small_coefficients" => + (; long_name="matched small-solution coefficient Δ_EF + Δ_outᵀ·cout per surface side, per unit EF column", dims=("surface_parity", "ef")), "SingularSurfaces/Match/forced_eigenvalue" => (; long_name="forced eigenvalue γ = 2πi·n·f at each surface", units="rad/s", _MATCH_SURF...), "SingularSurfaces/Match/residual" => (; long_name="relative residual of the matching linear solve") ] diff --git a/src/ForceFreeStates/Output.jl b/src/ForceFreeStates/Output.jl index 347374fd6a..2770f428ee 100644 --- a/src/ForceFreeStates/Output.jl +++ b/src/ForceFreeStates/Output.jl @@ -81,6 +81,7 @@ function save_to_hdf5( end out_h5["SingularSurfaces/D_I"] = (ls !== nothing && !isempty(result.surfaces)) ? [LocalStability.mercier_D_I(ls, sing.psifac) for sing in result.surfaces] : Float64[] + out_h5["SingularSurfaces/alpha"] = all(sing -> !isempty(sing.alpha), result.surfaces) ? [sing.alpha[1] for sing in result.surfaces] : ComplexF64[] # Resistive-layer overlap scan, present when psilim_from_layer_overlap capped the domain. if result.layer_overlap !== nothing diff --git a/src/ForceFreeStates/Result.jl b/src/ForceFreeStates/Result.jl index d6c886a693..60bc2a7874 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -40,9 +40,9 @@ Optional fields are `Union{Nothing,T}` and follow a presence-equals-capability r consumer that needs one gates on [`require`](@ref) (or [`require_solution`](@ref) for the ξ profiles) and warns-and-skips rather than erroring, so a result from an integrator that cannot supply a given product still flows through the pipeline. PerturbedEquilibrium refuses -`:matched` results, whose singular coupling is not defined yet, and Galerkin results without `free_boundary`. +Galerkin results without `free_boundary`, and builds only the asymptotic singular-coupling metrics for `:matched` results. -Every final result records how its basis crosses the rational surfaces, so bpen and closure are always present. +Every final result records how its basis crosses the rational surfaces, so `penetrated_area_weighted_field` and `closure` are always present. A Forward or Riccati solve applies the ideal jump condition at the rationals; a Galerkin solve is ideal-closed by its EF columns (`error_field_response`), and is unclosed without them. @@ -61,8 +61,8 @@ is ideal-closed by its EF columns (`error_field_response`), and is unclosed with - `closure::Symbol` - How the basis crosses the rationals: `:ideal` (the ideal jump condition was imposed), `:regular` (kinetic terms regularize the force balance equations so no closure is needed) or `:matched` (an inner-layer solution was matched in). A `:matched` result carries the matched edge response as `wp`. - - `bpen::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated resonant field from the - inner layer, per surface (rows follow `surfaces`) and driving mode; all zeros under `:ideal` and `:regular` closure. + - `penetrated_area_weighted_field::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated 𝒥b^ψ at each + layer center over the surface area, in T, per surface (rows follow `surfaces`) and driving mode; all zeros under `:ideal` and `:regular` closure. - `match::Union{Nothing,MatchResult}` - The [`MatchResult`](@ref) of a `MatchProblem` solve; `nothing` otherwise. - `solution::Union{Nothing,SolutionProfiles}` - THE solve's ξ solution; `nothing` when the formalism produced none (Galerkin without `error_field_response`). @@ -112,7 +112,7 @@ struct ForceFreeStatesResult{E<:Equilibrium.PlasmaEquilibrium,F<:MatrixSplines,P # Closure of the basis at the rationals, always present. closure::Symbol - bpen::Matrix{ComplexF64} + penetrated_area_weighted_field::Matrix{ComplexF64} match::Union{Nothing,MatchResult} # Per-formalism products; presence is the capability signal. @@ -230,7 +230,7 @@ function build_result( scan_cond=intr.kinsing_scan_cond, scan_threshold=intr.kinsing_scan_threshold) closure = ctrl.kinetic === nothing ? :ideal : :regular - bpen = zeros(ComplexF64, intr.msing, intr.numpert_total) + penetrated_area_weighted_field = zeros(ComplexF64, intr.msing, intr.numpert_total) # Fixed-boundary plasma energy matrix at the edge; free of any vacuum dependence, so a # vac_flag=false run still publishes its energy product. Aliases free_run's when it ran. @@ -249,7 +249,7 @@ function build_result( intr.mlow, intr.mhigh, intr.mpert, intr.nlow, intr.nhigh, intr.npert, intr.numpert_total, intr.psilow, intr.psilim, intr.qlim, intr.q1lim, intr.wall_settings, metric, mats, intr.sing, kinetic, - closure, bpen, nothing, + closure, penetrated_area_weighted_field, nothing, solution, odet, wp, free_energies, delta_prime, basis, gal_data, nothing ) end diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index 57b892408a..a4b6538396 100644 --- a/src/ForceFreeStates/Riccati/Driver.jl +++ b/src/ForceFreeStates/Riccati/Driver.jl @@ -16,6 +16,8 @@ function riccati_eulerlagrange_integration( odet = _initialize_parallel_odet(ctrl, equil, mats, intr) chunks = balance_integration_chunks(chunk_el_integration_bounds(odet, ctrl, intr; bidirectional=true), ctrl, intr) bases = asymptotic_bases(chunks, ctrl, equil, mats, intr) + # Each crossed surface publishes the exponent its series used. + foreach(((ising, basis),) -> intr.sing[ising].alpha = basis.right_series.alpha, pairs(bases)) if intr.verbose @info " ψ = $((@sprintf "%.3f" odet.psifac)), q = $((@sprintf "%.3f" equil.profiles.q_spline(odet.psifac)))" @info " Riccati FM: $(length(chunks)) chunks over $(Threads.nthreads()) thread$(Threads.nthreads() == 1 ? "" : "s")" diff --git a/src/ForceFreeStates/Surfaces/Types.jl b/src/ForceFreeStates/Surfaces/Types.jl index 333a93ca6c..3777b09b99 100644 --- a/src/ForceFreeStates/Surfaces/Types.jl +++ b/src/ForceFreeStates/Surfaces/Types.jl @@ -13,6 +13,9 @@ A mutable struct holding data related to the singular surfaces in the equilibriu - `n::Vector{Int}` - Toroidal mode number(s) - `q::Float64` - Safety factor (= m/n) - `q1::Float64` - Derivative of safety factor with respect to ψ + - `alpha::Vector{ComplexF64}` - Mercier exponent α = √(−D_I) of each resonant harmonic, as the solve's asymptotic series + found it from the retained poloidal harmonics; it approaches the Mercier index of the equilibrium as the solve converges + in m. Empty where no ideal asymptotic series was built. - `delta_prime::Vector{ComplexF64}` - **Debug stub, not physically valid.** Per-surface ca-based Δ' estimate; use `ForceFreeStatesResult.delta_prime` (STRIDE global BVP, Glasser & Kolemen 2018, Phys. Plasmas 25, 082502) for tearing stability. """ @@ -23,6 +26,7 @@ A mutable struct holding data related to the singular surfaces in the equilibriu n::Vector{Int} = Int[] q::Float64 = 0.0 q1::Float64 = 0.0 + alpha::Vector{ComplexF64} = ComplexF64[] delta_prime::Vector{ComplexF64} = ComplexF64[] restype::Any = nothing # ResistGeometry from ResistEval.jl (populated by resist_eval_all!); typed `Any` to avoid a cross-file type reference end diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index dc7d771a40..3274b1e688 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -50,11 +50,10 @@ their dominant modes (Park, Phys. Plasmas 16, 056115 (2009)), and with `compute_ ψ-resolved torque response `T_xe` of a single-`n` forward kinetic solve. Apply it to an external field with `perturbed_equilibrium(resp, rmp)` as many times as needed. -Products the producing integrator could not supply (free-boundary energies, a ξ solution) leave the -corresponding operators empty: the step warns and is skipped. A Galerkin result carries a free-boundary -δW only with `error_field_response` and `vac_flag`, so building a response from one without it is an error. So is a -`:matched` result, whose singular coupling is not defined yet, and a solve with a wall: the surface -inductance is free-space, and the response needs Λ from the same no-wall vacuum. +A result without a ξ solution leaves the operators empty: the step warns and is skipped. A result without +the free-boundary δW is an error (it needs `vac_flag`, and for Galerkin also `error_field_response`), and so is +a solve with a wall: the surface inductance is free-space, and the response needs Λ from the same no-wall vacuum. +A `:matched` result gets only the `_asymptotic` singular-coupling metrics and the penetrated field. """ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling::Bool=true, compute_torque_response::Bool=false, verbose::Bool=false)::PlasmaResponse @@ -63,14 +62,11 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: "plasma_response needs a force-free-states solve without a wall: its surface inductance L is free-space, " * "so Λ from a wall run would mix two vacuum models. Solve with wall=nothing (no [Wall] section)." ) - # The singular coupling evaluates ideal-closure resonant metrics off each surface, where a matched solution's - # big solution is singular. - ffs.closure === :matched && - error("plasma_response does not support a matched result yet: its singular-coupling metrics assume the ideal closure; " * - "use the unmatched solve") - ffs.free_boundary === nothing && ffs.integrator === :galerkin && - error("plasma_response needs the free-boundary δW, which this Galerkin result does not carry: solve with " * - "Galerkin(; error_field_response=true) and vac_flag=true") + ffs.free_boundary === nothing && + error( + "plasma_response needs the free-boundary δW, which this $(ffs.integrator) result does not carry: solve with " * + "vac_flag=true (and Galerkin(; error_field_response=true) for a Galerkin solve)" + ) m_modes, n_modes = mode_arrays(ffs) # A run has at most one ξ solution, already closed at the rationals and carrying populated @@ -79,7 +75,7 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: resp = PlasmaResponse(; ffs, m_modes, n_modes, compute_singular_coupling, compute_torque_response, unit_edge_basis=solution !== nothing && solution.basis === :unit_edge) - if ForceFreeStates.require(ffs, :free_boundary, "plasma response calculation") && ForceFreeStates.require_solution(ffs, "plasma response calculation") + if ForceFreeStates.require_solution(ffs, "plasma response calculation") build_response_operators!(resp; verbose) if compute_singular_coupling build_coupling_operators!(resp; verbose) diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index 73d640e5d5..d2acab8c16 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -77,13 +77,15 @@ applied root-area-weighted field b̃_x to the resonant response at that surface. - `C_island_width_sq` - (w/2)² coupling (singcoup row 3) - `C_penetrated_area_weighted_field` - Penetrated area-weighted field coupling (singcoup row 4) - `C_delta_mn` - Δ_mn coupling, the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4 over 2π·χ₁ (singcoup row 5) + The four finite-width matrices above are empty for a `:matched` result. - `coupling_flux::NamedTuple` - The same matrices acting on the physical flux Φ_x (keys without the `C_` prefix), used for the applied resonant vectors; empty when the coupling was not built. - `C_resonant_area_weighted_field_asymptotic`, `C_resonant_current_asymptotic`, `C_island_width_sq_asymptotic`, `C_delta_mn_asymptotic` - The same four built from the jump of the asymptotic small solution, −2πi·χ₁·n·q′·(C_R − C_L), in place of the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. The two agree where D_I = −1/4; elsewhere the finite-width matrices are (1/2 + √−D_I)·w^(√−D_I − 1/2) times these, w being that half-width in ψ_N. - Empty unless the result is single-`n` and carries `Delta_EF`. + Empty unless the result is single-`n` and carries `Delta_EF`; a `:matched` result takes C_L, C_R from its matched + small coefficients `match.small_coefficients`. - `C_coeffs::Matrix{ComplexF64}` - Edge-to-solution coefficients `u_bnd⁻¹·edge_mn` of each unit forcing mode. Metadata [n_rational] — identifies each (surface, n) row: diff --git a/src/PerturbedEquilibrium/SingularCoupling.jl b/src/PerturbedEquilibrium/SingularCoupling.jl index bb67609cc1..d2b33d99ac 100644 --- a/src/PerturbedEquilibrium/SingularCoupling.jl +++ b/src/PerturbedEquilibrium/SingularCoupling.jl @@ -222,7 +222,8 @@ stored acting on b̃_x, with flux-space copies in `resp.coupling_flux` for apply Δ_mn, the current, the field and (w/2)² are built from the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. A single-`n` result with `Delta_EF` also gets them from the jump of the asymptotic small solution, −2πi·χ₁·n·q′·(C_R − C_L), -in the `_asymptotic` matrices; those are empty otherwise. +in the `_asymptotic` matrices; those are empty otherwise. A `:matched` result takes C_L, C_R from its matched small +coefficients and gets only the `_asymptotic` and penetrated-field matrices: its big solution is singular at each surface. ## Normalization @@ -280,26 +281,31 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) verbose && @info "Found $n_rational resonant (surface, n) pairs" - resp.C_resonant_area_weighted_field = zeros(ComplexF64, n_rational, numpert_total) - resp.C_resonant_current = zeros(ComplexF64, n_rational, numpert_total) - resp.C_island_width_sq = zeros(ComplexF64, n_rational, numpert_total) - have_inner_bpen = !isempty(ffs.bpen) - if have_inner_bpen + # A matched solution carries the big solution, singular at each surface, so it gets no finite-width rows. + matched = ffs.closure === :matched + finite_size = matched ? (0, 0) : (n_rational, numpert_total) + resp.C_resonant_area_weighted_field = zeros(ComplexF64, finite_size) + resp.C_resonant_current = zeros(ComplexF64, finite_size) + resp.C_island_width_sq = zeros(ComplexF64, finite_size) + have_penetrated = !isempty(ffs.penetrated_area_weighted_field) + if have_penetrated resp.C_penetrated_area_weighted_field = zeros(ComplexF64, n_rational, numpert_total) else resp.C_penetrated_area_weighted_field = zeros(ComplexF64, 0, 0) @warn "No inner-layer B_pen supplied; penetrated field not computed." maxlog = 1 end - resp.C_delta_mn = zeros(ComplexF64, n_rational, numpert_total) + resp.C_delta_mn = zeros(ComplexF64, finite_size) resp.rational_psi = zeros(Float64, n_rational) resp.rational_q = zeros(Float64, n_rational) resp.rational_m_res = zeros(Int, n_rational) resp.rational_n = zeros(Int, n_rational) resp.rational_surface_idx = zeros(Int, n_rational) resp.rational_area = zeros(Float64, n_rational) - # The asymptotic rows need Δ_EF, each surface's left and right small-solution coefficients per unit edge displacement. + # The asymptotic rows need each surface's left and right small-solution coefficients per unit edge displacement: + # Δ_EF for an ideal closure, Δ_EF + Δ_outᵀ·c_out once matched. dp = ffs.delta_prime - have_ef = ffs.npert == 1 && dp !== nothing && size(dp.ef) == (2msing, numpert_total) + small = matched ? ffs.match.small_coefficients : dp === nothing ? nothing : dp.ef + have_ef = ffs.npert == 1 && small !== nothing && size(small) == (2msing, numpert_total) asymptotic_size = have_ef ? (n_rational, numpert_total) : (0, 0) resp.C_resonant_area_weighted_field_asymptotic = zeros(ComplexF64, asymptotic_size) resp.C_resonant_current_asymptotic = zeros(ComplexF64, asymptotic_size) @@ -347,46 +353,9 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) # shear = n·q′/q (Fortran gpout_resp); abs(nn) only sets the sign of C_island_width_sq, not the width. shear = abs(nn) * sing_surf.q1 / sing_surf.q - # Evaluate ∂b^ψ/∂ψ either side of the surface; spot 5e-4 matches the Fortran singfac_min default. - spot_psi = 5e-4 / (abs(nn) * abs(sing_surf.q1)) - lpsi = sing_surf.psifac - spot_psi - rpsi = sing_surf.psifac + spot_psi - - # Ξ, Ξ′ at lpsi/rpsi as in Fortran gpeq_sol: matched → its stored Ξ′, ideal → EL relation, kinetic → stored Ξ′. - if resp.unit_edge_basis - u_l, ud_l = _matched_solution_at(lpsi, resnum, solution, nstep) - u_r, ud_r = _matched_solution_at(rpsi, resnum, solution, nstep) - elseif use_el - u_l, ud_l = _el_solution_at(lpsi, resnum, solution, mats, equil, ffs, nstep) - u_r, ud_r = _el_solution_at(rpsi, resnum, solution, mats, equil, ffs, nstep) - else - u_l, ud_l = _solution_at(lpsi, sing_surf.psifac, resnum, m_res, nn, solution, equil, nstep) - u_r, ud_r = _solution_at(rpsi, sing_surf.psifac, resnum, m_res, nn, solution, equil, nstep) - end - - q_l = equil.profiles.q_spline(lpsi) - q1_l = equil.profiles.q_deriv(lpsi) - q_r = equil.profiles.q_spline(rpsi) - q1_r = equil.profiles.q_deriv(rpsi) - singfac_l = m_res - nn * q_l - singfac_r = m_res - nn * q_r - - jump_vec = Vector{ComplexF64}(undef, numpert_total) - for k in 1:numpert_total - ck = @view C_coeffs[:, k] - xsp_l = transpose(u_l) * ck - xsp1_l = transpose(ud_l) * ck - xsp_r = transpose(u_r) * ck - xsp1_r = transpose(ud_r) * ck - bwp1_l = 2π * im * chi1 * (singfac_l * xsp1_l - nn * q1_l * xsp_l) - bwp1_r = 2π * im * chi1 * (singfac_r * xsp1_r - nn * q1_r * xsp_r) - jump_vec[k] = bwp1_r - bwp1_l - end - - # Inner-layer penetrated field bpen[s, :] contracts with C_coeffs like the outer solution; /area makes it area-weighted. - if have_inner_bpen && s <= size(ffs.bpen, 1) - pen_row = (transpose(C_coeffs) * @view(ffs.bpen[s, :])) ./ area - resp.C_penetrated_area_weighted_field[row, :] = pen_row + # The inner layer's penetrated area-weighted field contracts with C_coeffs like the outer solution. + if have_penetrated && s <= size(ffs.penetrated_area_weighted_field, 1) + resp.C_penetrated_area_weighted_field[row, :] = transpose(C_coeffs) * @view(ffs.penetrated_area_weighted_field[s, :]) end # Δ_mn is the ∂b^ψ/∂ψ jump, stored over 2π·χ₁; j_c carries the surface Jacobian weighting of the current; @@ -398,14 +367,46 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) island_width_sq = abs(shear) > 1e-10 ? (4.0 / (twopi * shear * sing_surf.q * chi1)) .* singflx : zero(singflx) return (; delta_mn=jump ./ (twopi * chi1), resonant_current, resonant_area_weighted_field=singflx ./ area, island_width_sq) end - rows = coupling_rows(jump_vec) - resp.C_delta_mn[row, :] = rows.delta_mn - resp.C_resonant_current[row, :] = rows.resonant_current - resp.C_resonant_area_weighted_field[row, :] = rows.resonant_area_weighted_field - resp.C_island_width_sq[row, :] = rows.island_width_sq + if !matched + # Evaluate ∂b^ψ/∂ψ either side of the surface; spot 5e-4 matches the Fortran singfac_min default. + spot_psi = 5e-4 / (abs(nn) * abs(sing_surf.q1)) + lpsi = sing_surf.psifac - spot_psi + rpsi = sing_surf.psifac + spot_psi + + # Ξ, Ξ′ at lpsi/rpsi as in Fortran gpeq_sol: unit-edge basis → its stored Ξ′, ideal → EL relation, kinetic → stored Ξ′. + if resp.unit_edge_basis + u_l, ud_l = _matched_solution_at(lpsi, resnum, solution, nstep) + u_r, ud_r = _matched_solution_at(rpsi, resnum, solution, nstep) + elseif use_el + u_l, ud_l = _el_solution_at(lpsi, resnum, solution, mats, equil, ffs, nstep) + u_r, ud_r = _el_solution_at(rpsi, resnum, solution, mats, equil, ffs, nstep) + else + u_l, ud_l = _solution_at(lpsi, sing_surf.psifac, resnum, m_res, nn, solution, equil, nstep) + u_r, ud_r = _solution_at(rpsi, sing_surf.psifac, resnum, m_res, nn, solution, equil, nstep) + end + + q1_l = equil.profiles.q_deriv(lpsi) + q1_r = equil.profiles.q_deriv(rpsi) + singfac_l = m_res - nn * equil.profiles.q_spline(lpsi) + singfac_r = m_res - nn * equil.profiles.q_spline(rpsi) + + jump_vec = Vector{ComplexF64}(undef, numpert_total) + for k in 1:numpert_total + ck = @view C_coeffs[:, k] + bwp1_l = 2π * im * chi1 * (singfac_l * (transpose(ud_l) * ck) - nn * q1_l * (transpose(u_l) * ck)) + bwp1_r = 2π * im * chi1 * (singfac_r * (transpose(ud_r) * ck) - nn * q1_r * (transpose(u_r) * ck)) + jump_vec[k] = bwp1_r - bwp1_l + end + + rows = coupling_rows(jump_vec) + resp.C_delta_mn[row, :] = rows.delta_mn + resp.C_resonant_current[row, :] = rows.resonant_current + resp.C_resonant_area_weighted_field[row, :] = rows.resonant_area_weighted_field + resp.C_island_width_sq[row, :] = rows.island_width_sq + end if have_ef - # Asymptotic jump −2πi·χ₁·n·q′·(C_R − C_L): the right and left rows of Δ_EF on the edge displacement of each forcing mode. - rows = coupling_rows((-2π * im * chi1 * nn * sing_surf.q1) .* (transpose(edge_mn) * (dp.ef[2s, :] .- dp.ef[2s-1, :]))) + # Asymptotic jump −2πi·χ₁·n·q′·(C_R − C_L): the right and left small-solution rows on the edge displacement of each forcing mode. + rows = coupling_rows((-2π * im * chi1 * nn * sing_surf.q1) .* (transpose(edge_mn) * (small[2s, :] .- small[2s-1, :]))) resp.C_delta_mn_asymptotic[row, :] = rows.delta_mn resp.C_resonant_current_asymptotic[row, :] = rows.resonant_current resp.C_resonant_area_weighted_field_asymptotic[row, :] = rows.resonant_area_weighted_field @@ -419,8 +420,8 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resp.rational_n[row] = nn resp.rational_surface_idx[row] = s - if verbose - dp_diag = real(resp.C_delta_mn[row, resnum]) + if verbose && (have_ef || !matched) + dp_diag = real((matched ? resp.C_delta_mn_asymptotic : resp.C_delta_mn)[row, resnum]) @info "Row $row: q=$(@sprintf("%.3f", sing_surf.q)), ψ=$(@sprintf("%.3f", sing_surf.psifac)), m=$m_res, n=$nn, Δ_mn(diag)=$(@sprintf("%.3e", dp_diag))" end end @@ -435,17 +436,19 @@ function build_coupling_operators!(resp::PlasmaResponse; verbose::Bool=false) resonant_area_weighted_field_asymptotic=resp.C_resonant_area_weighted_field_asymptotic, resonant_current_asymptotic=resp.C_resonant_current_asymptotic, island_width_sq_asymptotic=resp.C_island_width_sq_asymptotic, delta_mn_asymptotic=resp.C_delta_mn_asymptotic) flux_conform = resp.rootarea_to_area_weight .* resp.surface_area - resp.C_resonant_area_weighted_field = resp.C_resonant_area_weighted_field * flux_conform - resp.C_resonant_current = resp.C_resonant_current * flux_conform - resp.C_island_width_sq = resp.C_island_width_sq * flux_conform - resp.C_delta_mn = resp.C_delta_mn * flux_conform + if !matched + resp.C_resonant_area_weighted_field = resp.C_resonant_area_weighted_field * flux_conform + resp.C_resonant_current = resp.C_resonant_current * flux_conform + resp.C_island_width_sq = resp.C_island_width_sq * flux_conform + resp.C_delta_mn = resp.C_delta_mn * flux_conform + end if have_ef resp.C_resonant_area_weighted_field_asymptotic = resp.C_resonant_area_weighted_field_asymptotic * flux_conform resp.C_resonant_current_asymptotic = resp.C_resonant_current_asymptotic * flux_conform resp.C_island_width_sq_asymptotic = resp.C_island_width_sq_asymptotic * flux_conform resp.C_delta_mn_asymptotic = resp.C_delta_mn_asymptotic * flux_conform end - have_inner_bpen && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * flux_conform) + have_penetrated && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * flux_conform) return resp end @@ -469,15 +472,16 @@ function apply_coupling!(state::PerturbedEquilibriumState; verbose::Bool=false) isnothing(j) || (forcing_flux[j] = mode.amplitude) end - state.resonant_area_weighted_field = C.resonant_area_weighted_field * forcing_flux - state.resonant_current = C.resonant_current * forcing_flux - state.island_width_sq = C.island_width_sq * forcing_flux - state.delta_mn = C.delta_mn * forcing_flux + # A matched response has no finite-width matrices. + if !isempty(C.delta_mn) + state.resonant_area_weighted_field = C.resonant_area_weighted_field * forcing_flux + state.resonant_current = C.resonant_current * forcing_flux + state.island_width_sq = C.island_width_sq * forcing_flux + state.delta_mn = C.delta_mn * forcing_flux + state.island_half_width, state.chirikov_parameter = island_diagnostics(state.island_width_sq, resp.rational_psi, resp.rational_surface_idx) + end isempty(C.penetrated_area_weighted_field) || (state.penetrated_area_weighted_field = C.penetrated_area_weighted_field * forcing_flux) state.forcing_solution_weights = resp.C_coeffs * forcing_flux - - # Island diagnostics from the applied resonant vectors - state.island_half_width, state.chirikov_parameter = island_diagnostics(state.island_width_sq, resp.rational_psi, resp.rational_surface_idx) if !isempty(C.delta_mn_asymptotic) state.resonant_area_weighted_field_asymptotic = C.resonant_area_weighted_field_asymptotic * forcing_flux state.resonant_current_asymptotic = C.resonant_current_asymptotic * forcing_flux diff --git a/src/Utilities/HDF5Schema.jl b/src/Utilities/HDF5Schema.jl index 1e29d87908..1ab1d13ae7 100644 --- a/src/Utilities/HDF5Schema.jl +++ b/src/Utilities/HDF5Schema.jl @@ -239,6 +239,9 @@ const MAIN_H5_ANNOTATIONS = [ "SingularSurfaces/rational_n" => (; long_name="resonant toroidal mode numbers per surface (0-padded)", dims=("surface", "mode")), "SingularSurfaces/D_I" => (; long_name="Mercier D_I evaluated at each rational surface", dims=("surface",), attach=(1 => "SingularSurfaces/rational_psi", 1 => "SingularSurfaces/rational_q")), + "SingularSurfaces/alpha" => + (; long_name="Mercier exponent α = √(−D_I) the solve's asymptotic series used at each rational surface (ν = α − 1/2); converges to SingularSurfaces/D_I with the poloidal harmonics retained", + dims=("surface",), attach=(1 => "SingularSurfaces/rational_psi", 1 => "SingularSurfaces/rational_q")), "SingularSurfaces/ca_left" => (; long_name="asymptotic large/small-solution coefficient matrices just left of each surface (zero-extent when not computed — ideal crossings only)", dims=("mode", "solution", "large_small", "surface")), diff --git a/test/runtests_result_struct.jl b/test/runtests_result_struct.jl index 81ee2960cd..afc63fd7e1 100644 --- a/test/runtests_result_struct.jl +++ b/test/runtests_result_struct.jl @@ -71,8 +71,8 @@ include("display_check.jl") # Ideal closure: no inner layer was matched in. @test ffs.closure === :ideal - @test size(ffs.bpen) == (length(ffs.surfaces), ffs.numpert_total) - @test iszero(ffs.bpen) + @test size(ffs.penetrated_area_weighted_field) == (length(ffs.surfaces), ffs.numpert_total) + @test iszero(ffs.penetrated_area_weighted_field) # Forward integration produces no STRIDE propagators, hence no Δ′ matrix. @test ffs.delta_prime === nothing @@ -105,9 +105,12 @@ include("display_check.jl") @test ffs.integrator === :riccati @test ffs.solution !== nothing && ffs.solution.basis === :el_axis @test ffs.solution.step == length(ffs.solution.psi_store) == size(ffs.solution.du_store, 3) + # Each surface carries the Mercier exponent its crossing used; Forward builds the same series. + @test all(s -> length(s.alpha) == length(s.m), ffs.surfaces) + @test first.(getfield.(ffs.surfaces, :alpha)) ≈ first.(getfield.(forward_result[].surfaces, :alpha)) @test ffs.diagnostics !== nothing @test ffs.closure === :ideal - @test iszero(ffs.bpen) + @test iszero(ffs.penetrated_area_weighted_field) @test ffs.delta_prime !== nothing dp = ffs.delta_prime @@ -231,12 +234,12 @@ include("display_check.jl") # Without a match the EF columns are the ideal closure, with a Hermitian δW. if ideal @test ffs.closure === :ideal - @test iszero(ffs.bpen) + @test iszero(ffs.penetrated_area_weighted_field) @test norm(ffs.wp - ffs.wp') <= 1e-8 * norm(ffs.wp) else @test ffs.closure === :matched - @test ffs.bpen == ffs.match.bpen - @test !iszero(ffs.bpen) + @test ffs.penetrated_area_weighted_field == ffs.match.penetrated_area_weighted_field + @test !iszero(ffs.penetrated_area_weighted_field) end # The closed profiles land in the shared Solutions layout: same names and @@ -263,8 +266,8 @@ include("display_check.jl") if !ideal # Match/ is self-describing: rows follow SingularSurfaces/rational_psi, and it names the model that ran. mg = f["SingularSurfaces/Match"] - @test size(read(mg["bpen"]), 1) == length(read(f["SingularSurfaces/rational_psi"])) - @test read(mg["reconnected_flux"]) == ffs.match.reconnected_flux + @test size(read(mg["penetrated_area_weighted_field"]), 1) == length(read(f["SingularSurfaces/rational_psi"])) + @test read(mg["small_coefficients"]) == ffs.match.small_coefficients @test attrs(mg)["inner_model"] == GeneralizedPerturbedEquilibrium.InnerLayer.model_name(ffs.match.model) @test isempty(_collect_metadata_violations(mg)) end diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index cd9ca38207..0c9f0d62c2 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -102,7 +102,7 @@ include("display_check.jl") ideal = solve(equil, forward; nn=1, wall=wall, ffs_kwargs...) @test scaled.mats.kinetic !== nothing && ideal.mats.kinetic === nothing - @test scaled.closure === :regular && ideal.closure === :ideal && iszero(scaled.bpen) + @test scaled.closure === :regular && ideal.closure === :ideal && iszero(scaled.penetrated_area_weighted_field) @test !isapprox(scaled.free_boundary.et[1], ideal.free_boundary.et[1]; rtol=1e-6) @test factored.free_boundary.et[1] ≈ scaled.free_boundary.et[1] rtol = 1e-10 @test factored.kinetic.kmsing == scaled.kinetic.kmsing @@ -398,7 +398,7 @@ include("display_check.jl") n = length(gal.surfaces) slow = solve(MatchProblem(gal; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel()) fast = solve(MatchProblem(gal; eta=fill(1e-7, n), rho=fill(1e-7, n), rotation=fill(10.0, n)), GGJModel()) - @test slow.bpen != fast.bpen + @test slow.penetrated_area_weighted_field != fast.penetrated_area_weighted_field # The result records which model it was matched with. @test slow.match.model === GGJModel() @test first_diff(gal, gal_snap) === nothing @@ -432,7 +432,7 @@ include("display_check.jl") @test given.eta == fill(1e-7, n) && given.rho == prob.rho && given.rotation == fill(3.0, n) # The derived inputs solve the same as those values given explicitly. explicit = MatchProblem(kgal; eta=prob.eta, rho=prob.rho, rotation=prob.rotation) - @test solve(prob, GGJModel()).bpen == solve(explicit, GGJModel()).bpen + @test solve(prob, GGJModel()).penetrated_area_weighted_field == solve(explicit, GGJModel()).penetrated_area_weighted_field # Data without an E×B rotation need an explicit rotation. attach_kinetic_profiles!(kgal.equil, KineticProfileData(; psi, n_e=flat(5e19), n_i=flat(5e19), T_e=flat(1e3), T_i=flat(1e3))) @test_throws "give rotation" MatchProblem(kgal) @@ -445,9 +445,9 @@ include("display_check.jl") layer = (eta=1e-7, rho=1e-7, rotation=1.0) ggj = solve(MatchProblem(ric; layer...), GGJModel()) # Q* = 0, M⊥/M = 1 is the GGJ layer, through CCC's own Wasow basis and splitting solve. - @test solve(MatchProblem(ric; layer...), CCCModel(; Qstar=0.0)).bpen ≈ ggj.bpen rtol = 1e-6 + @test solve(MatchProblem(ric; layer...), CCCModel(; Qstar=0.0)).penetrated_area_weighted_field ≈ ggj.penetrated_area_weighted_field rtol = 1e-6 drift = solve(MatchProblem(ric; layer...), CCCModel(; Qstar=0.05, mperp=1.2)) - @test drift.closure === :matched && all(isfinite, drift.bpen) && drift.bpen != ggj.bpen + @test drift.closure === :matched && all(isfinite, drift.penetrated_area_weighted_field) && drift.penetrated_area_weighted_field != ggj.penetrated_area_weighted_field @test drift.match.model === CCCModel(; Qstar=0.05, mperp=1.2) && all(p -> p.Qstar == 0.05 && p.mperp == 1.2, drift.match.inner_params) # Without kinetic data CCC needs Q* given. @test_throws "give Qstar, or load kinetic profiles" solve(MatchProblem(ric; layer...), CCCModel()) @@ -509,7 +509,7 @@ include("display_check.jl") ray = solve(prob, GGJModel(; real_profiles=true)).match galm = solve(prob, GGJModel(; solver=:galerkin)).match # Δ and the penetrated field come from the rotated solve whether or not profiles are requested. - @test ray.deltar == center.deltar && ray.bpen == center.bpen + @test ray.deltar == center.deltar && ray.penetrated_area_weighted_field == center.penetrated_area_weighted_field @test isempty(center.inner_psi) && isempty(center.inner_xi) && isempty(center.inner_b) @test !isempty(ray.inner_xi) && !isempty(galm.inner_xi) # At ψ_s the composite ξ is the even (Δ₊) column and b the odd (Δ₋) one, so a parity swap in the @@ -530,7 +530,7 @@ include("display_check.jl") @test ric.free_boundary !== nothing && !isempty(ric.delta_prime.ef) matched = solve(MatchProblem(ric; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel()) @test matched.closure === :matched - @test matched.match !== nothing && matched.bpen == matched.match.bpen + @test matched.match !== nothing && matched.penetrated_area_weighted_field == matched.match.penetrated_area_weighted_field # The matched ξ is built from the Riccati solve's own outer solutions, on its stored grid. @test ric.basis !== nothing && size(ric.basis.xi, 3) == 2 * length(ric.surfaces) + ric.numpert_total @test matched.solution.basis === :unit_edge && matched.solution.psi_store == ric.basis.psi @@ -542,8 +542,21 @@ include("display_check.jl") @test matched.wp ≈ ric.wp + ric.delta_prime.edge_response * matched.match.cout / ψ₀² rtol = 1e-12 @test norm(matched.wp - matched.wp') > 1e-8 * norm(matched.wp) @test matched.free_boundary.wt0 ≈ matched.wp + ric.free_boundary.wv rtol = 1e-12 - # The singular coupling of a matched solution is not defined yet. - @test_throws "matched" plasma_response(matched) + # The matched small coefficients are the inner layers' response Δ₊d₊ ∓ Δ₋d₋ (Wang et al. 2020 Eqs. 11c–d). + m = matched.match + for i in eachindex(ric.surfaces) + dplus, dminus = m.cin[2i-1, :], m.cin[2i, :] + @test m.small_coefficients[2i-1, :] ≈ m.deltar[i, 1] .* dplus .- m.deltar[i, 2] .* dminus rtol = 1e-8 + @test m.small_coefficients[2i, :] ≈ m.deltar[i, 1] .* dplus .+ m.deltar[i, 2] .* dminus rtol = 1e-8 + end + # A matched response carries only the asymptotic metrics, built from those coefficients, and drives a forcing. + resp = plasma_response(matched) + @test isempty(resp.C_delta_mn) && isempty(resp.C_resonant_area_weighted_field) + @test size(resp.C_delta_mn_asymptotic) == (length(resp.rational_psi), matched.numpert_total) + @test resp.C_delta_mn_asymptotic != plasma_response(ric).C_delta_mn_asymptotic + pe = perturbed_equilibrium(resp, RMPField(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"))) + @test isempty(pe.delta_mn) && length(pe.delta_mn_asymptotic) == length(resp.rational_psi) + @test all(isfinite, pe.island_half_width_asymptotic) # A matched result is a new solution, not an outer solve to match again. @test_throws ErrorException MatchProblem(matched; eta=1e-7, rho=1e-7, rotation=1.0) end @@ -578,8 +591,7 @@ include("display_check.jl") @test matched.wp ≈ gal.wp + F[:, 1:(2length(gal.surfaces))] * matched.match.cout / ψ₀² rtol = 1e-12 # Its free-boundary energies use the matched response with the solve's own vacuum. @test matched.free_boundary.wt0 ≈ matched.wp + gal.free_boundary.wv rtol = 1e-12 - # The singular coupling of a matched solution is not defined yet. - @test_throws "matched" plasma_response(matched) + @test isempty(plasma_response(matched).C_delta_mn) # The EF columns do not change either Δ′: both equal those of a solve without them. plain = solve(equil, Galerkin(; nx=32, error_field_response=false); nn=1, ffs_kwargs...) @test gal.delta_prime.raw_freeboundary == plain.delta_prime.raw_freeboundary @@ -609,6 +621,10 @@ include("display_check.jl") novac = solve(equil, Galerkin(; nx=32, error_field_response=true); nn=1, merge(ffs_kwargs, Dict{Symbol,Any}(:vac_flag => false))...) @test novac.wp !== nothing && novac.free_boundary === nothing @test_throws "vac_flag=true" plasma_response(novac) + # The same holds for every integrator. + fwd_novac = solve(equil, forward; nn=1, merge(ffs_kwargs, Dict{Symbol,Any}(:vac_flag => false))...) + @test fwd_novac.free_boundary === nothing + @test_throws "vac_flag=true" plasma_response(fwd_novac) end end @@ -704,7 +720,7 @@ include("display_check.jl") @test reference.closure === api.closure === :matched @test h5open(f -> haskey(f, "Info/Runtimes/match"), joinpath(dir, "gpec.h5")) - @test api.bpen ≈ reference.bpen rtol = 1e-12 + @test api.penetrated_area_weighted_field ≈ reference.penetrated_area_weighted_field rtol = 1e-12 @test api.match.xi ≈ reference.match.xi rtol = 1e-12 # The composite inner profiles need the cut solution, which Galerkin keeps only on request. @test isempty(reference.match.inner_xi) && isempty(api.match.inner_xi) @@ -719,7 +735,7 @@ include("display_check.jl") extra_sections=match_sections(length(ric.surfaces), "ray"))]).ffs @test reference.closure === :matched - @test api.bpen ≈ reference.bpen rtol = 1e-12 + @test api.penetrated_area_weighted_field ≈ reference.penetrated_area_weighted_field rtol = 1e-12 @test api.match.cout ≈ reference.match.cout rtol = 1e-12 @test !isempty(api.match.xi) @test api.match.xi ≈ reference.match.xi rtol = 1e-12 @@ -736,7 +752,7 @@ include("display_check.jl") reference = GPEC.main([_stage_deck(dir; ffs_overrides=Dict{String,Any}("integrator" => "Riccati"), extra_sections=sections)]).ffs @test reference.closure === :matched && reference.match.model isa CCCModel{:ray} && reference.match.model.Qstar == fill(0.05, n) - @test api.bpen ≈ reference.bpen rtol = 1e-12 + @test api.penetrated_area_weighted_field ≈ reference.penetrated_area_weighted_field rtol = 1e-12 @test api.match.cout ≈ reference.match.cout rtol = 1e-12 end From 19662a40ec381d2309888623675ac3abb4d98b9b Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Tue, 24 Nov 2026 00:07:09 +0100 Subject: [PATCH 15/27] Repo - BUGFIX - Pass error_field_response, not the removed rpec_flag, to the Galerkin precompile workload --- src/Precompile.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Precompile.jl b/src/Precompile.jl index 0e41e3fb4d..7f6bbe9ea3 100644 --- a/src/Precompile.jl +++ b/src/Precompile.jl @@ -66,7 +66,7 @@ import Logging stability["ForceFreeStates"]["integrator"] = formalism foreach(name -> delete!(stability, name), ("Riccati", "Forward", "Galerkin")) stability[formalism] = - formalism == "Galerkin" ? Dict{String,Any}("nx" => 32, "rpec_flag" => true) : + formalism == "Galerkin" ? Dict{String,Any}("nx" => 32, "error_field_response" => true) : Dict{String,Any}("eulerlagrange_tolerance" => 1e-7) run_workload(stability) end From 7f6cc849e0e00121c2500612ddfd1b486d141440 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 25 Nov 2026 14:14:06 +0100 Subject: [PATCH 16/27] Examples - FEATURE - Drive the Riccati and matched Galerkin DIII-D examples with the C-coil and track their resonant metrics --- docs/src/workflow.md | 4 +- examples/DIIID-like_SLAYER_example/gpec.toml | 2 +- .../DIIID-like_error_field_example/gpec.toml | 2 +- .../gpec.toml | 26 +++++-- examples/DIIID-like_ideal_example/gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 23 ++++-- .../DIIID-like_truncation_example/gpec.toml | 2 +- examples/LAR_beta_scan/gpec.toml | 2 +- examples/LAR_epsilon_scan/gpec.toml | 2 +- examples/LAR_ideal_match_test/gpec.toml | 2 +- examples/LAR_resistive_match_test/gpec.toml | 2 +- examples/Solovev_ideal_example/gpec.toml | 2 +- examples/Solovev_ideal_example_3D/gpec.toml | 2 +- .../Solovev_ideal_example_multi_n/gpec.toml | 2 +- examples/TJ_ideal_example/gpec.toml | 2 +- examples/TJ_kinetic_NTV_example/gpec.toml | 2 +- .../TJ_kinetic_calculated_example/gpec.toml | 2 +- .../TJ_kinetic_multiion_example/gpec.toml | 2 +- examples/a10_kinetic_example/gpec.toml | 2 +- .../cases/diiid_n1_riccati.toml | 75 +++++++++++++++++-- .../cases/gal_resistive_diiid.toml | 50 +++++++++++++ .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../gpec.toml | 2 +- .../regression_tj_ideal_example/gpec.toml | 2 +- .../gpec.toml | 2 +- 28 files changed, 183 insertions(+), 41 deletions(-) diff --git a/docs/src/workflow.md b/docs/src/workflow.md index fdba0d4648..2519cb5c26 100644 --- a/docs/src/workflow.md +++ b/docs/src/workflow.md @@ -182,8 +182,8 @@ From Julia, the same pipeline is `GeneralizedPerturbedEquilibrium.main(["example | `DIIID-like_ideal_example` | DIII-D-like H-mode, n = 1: free-boundary ideal stability, local stability, C-coil-driven perturbed equilibrium and NTV torque; the default benchmark case | | `DIIID-like_ideal_multi_n_example` | the same plasma with n = 1 and 2 solved together and driven by mixed-n coil currents | | `DIIID-like_ideal_example_IMAS` | the same equilibrium read from an `IMASdd.dd`, run from `run_imas_example.jl` | -| `DIIID-like_riccati_deltaprime_example` | the Δ′ matrix on the `"Riccati"` integrator, no forcing | -| `DIIID-like_gal_resistive_example` | the `"Galerkin"` outer-region Δ′ solve, no forcing | +| `DIIID-like_riccati_deltaprime_example` | the Δ′ matrix on the `"Riccati"` integrator, and its plasma response to the C-coil with the `_asymptotic` resonant metrics | +| `DIIID-like_gal_resistive_example` | the `"Galerkin"` outer-region Δ′ solve matched to a resistive layer, and the matched plasma response to the C-coil | | `DIIID-like_SLAYER_example` | tearing growth rates and critical resonant fields with the `SLAYER` layer model | | `DIIID-like_truncation_example` | the resistive-layer overlap cap on the edge of the integration domain | | `DIIID-like_error_field_example` | error-field sensitivities, Monte Carlo tolerances and locking risk for the DIII-D poloidal-field coils | diff --git a/examples/DIIID-like_SLAYER_example/gpec.toml b/examples/DIIID-like_SLAYER_example/gpec.toml index 3d74674494..c8085f58cc 100644 --- a/examples/DIIID-like_SLAYER_example/gpec.toml +++ b/examples/DIIID-like_SLAYER_example/gpec.toml @@ -49,7 +49,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = true # TRUE for diverted geqdsks — q → ∞ at separatrix, so rational_offset_fraction truncation avoids the δW kink instability at negligible domain cost rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n diff --git a/examples/DIIID-like_error_field_example/gpec.toml b/examples/DIIID-like_error_field_example/gpec.toml index f8315025b1..3089f801f8 100644 --- a/examples/DIIID-like_error_field_example/gpec.toml +++ b/examples/DIIID-like_error_field_example/gpec.toml @@ -60,7 +60,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = true # Truncate at (last_rational_q + rational_offset_fraction)/n — TRUE for diverted equilibria (q → ∞ at separatrix) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/DIIID-like_gal_resistive_example/gpec.toml b/examples/DIIID-like_gal_resistive_example/gpec.toml index 9b95dca102..ea441ca260 100644 --- a/examples/DIIID-like_gal_resistive_example/gpec.toml +++ b/examples/DIIID-like_gal_resistive_example/gpec.toml @@ -1,8 +1,9 @@ -# DIII-D-like H-mode resistive-MHD example: outer-region singular Galerkin Δ′ solve. -# n=1 tearing stability on the bundled geqdsk: the gal solver computes the Δ′ -# matching matrix (PEST-3 convention) plus error-field (EF) columns (Delta_EF). -# The core_edge_packed radial grid is densest at the axis and edge; psihigh = 0.993 -# stays clear of the separatrix. No forcing and no PerturbedEquilibrium stage. +# DIII-D-like H-mode resistive-MHD example: outer-region singular Galerkin Δ′ solve, matched to a resistive inner layer. +# n=1 on the bundled geqdsk: the gal solver computes the Δ′ matching matrix (PEST-3 convention) plus +# error-field (EF) columns (Delta_EF); [Match] closes each rational surface with the inner layer, and the +# perturbed equilibrium of that matched result under the DIII-D C-coil reports the penetrated field and the +# _asymptotic resonant metrics. The core_edge_packed radial grid is densest at the axis and edge; psihigh = 0.993 +# stays clear of the separatrix. [Run] verbose = true # Log each stage's progress @@ -47,7 +48,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Keep psilim at psihigh (do not truncate at last_rational_q + rational_offset_fraction) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n (only used when truncate_at_rational_offset = true) @@ -76,3 +77,16 @@ eta = [8e-8, 8e-8, 8e-8, 8e-8] # Per-surface resisti rho = [3.3e-7, 3.3e-7, 3.3e-7, 3.3e-7] # Per-surface mass density ρ [kg/m³] (core→edge) rotation = [1.0, 1.0, 1.0, 1.0] # Per-surface rotation frequency f [Hz] (core→edge); forced eigenvalue γ_s = 2πi·n·f gamma = 1.6666666666666667 # Ratio of specific heats Γ for the resistive-layer coefficients (5/3) + +[ForcingTerms] +forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat +mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation +nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) + +[[ForcingTerms.coil_set]] +name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) +currents = [1000.0, 500.0, -500.0, -1000.0, -500.0, 500.0] # n=1 cosine phasing, 1 kA peak [A] + +[PerturbedEquilibrium] +compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/examples/DIIID-like_ideal_example/gpec.toml b/examples/DIIID-like_ideal_example/gpec.toml index 2b020622ca..1c9f17ed44 100644 --- a/examples/DIIID-like_ideal_example/gpec.toml +++ b/examples/DIIID-like_ideal_example/gpec.toml @@ -56,7 +56,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = true # Truncate at (last_rational_q + rational_offset_fraction)/n — TRUE for diverted equilibria (q → ∞ at separatrix) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/DIIID-like_ideal_multi_n_example/gpec.toml b/examples/DIIID-like_ideal_multi_n_example/gpec.toml index 54aae84513..71f8da0b84 100644 --- a/examples/DIIID-like_ideal_multi_n_example/gpec.toml +++ b/examples/DIIID-like_ideal_multi_n_example/gpec.toml @@ -49,7 +49,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for multi-n — rational_offset_fraction truncation is ambiguous when n varies; qhigh sets the edge instead rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml index fca015a0c5..062459afed 100644 --- a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml +++ b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml @@ -1,8 +1,8 @@ -# DIII-D-like H-mode equilibrium — n=1 Δ'-matrix case on the Riccati integrator. +# DIII-D-like H-mode equilibrium — n=1 Δ'-matrix case on the Riccati integrator, with the plasma response to the C-coil. # Reuses the equilibrium of the sibling DIIID-like_ideal_example (geqdsk referenced by -# relative path; not duplicated), and is the canonical SingularSurfaces/Delta_prime_matrix -# fixture: the Riccati chunked propagator BVP is the only integrator that produces it. -# No forcing or perturbed equilibrium, so no dense ξ profiles are needed. +# relative path; not duplicated). The Riccati chunked propagator BVP gives the singular-surface +# Δ′ matrix and Delta_EF; [PerturbedEquilibrium] then reports the resonant coupling both from the +# finite-width jump and, through Delta_EF, from the asymptotic small solution (the _asymptotic outputs). [Run] verbose = true # Log each stage's progress @@ -48,7 +48,7 @@ mtheta_vacuum = 512 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = true # Truncate at (last_rational_q + rational_offset_fraction)/n — TRUE for diverted equilibria (q → ∞ at separatrix) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) @@ -56,3 +56,16 @@ rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rati [Riccati] eulerlagrange_tolerance = 1e-10 # Relative tolerance for ODE integration of Euler-Lagrange equations save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored + +[ForcingTerms] +forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat +mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation +nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) + +[[ForcingTerms.coil_set]] +name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) +currents = [1000.0, 500.0, -500.0, -1000.0, -500.0, 500.0] # n=1 cosine phasing, 1 kA peak [A] + +[PerturbedEquilibrium] +compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/examples/DIIID-like_truncation_example/gpec.toml b/examples/DIIID-like_truncation_example/gpec.toml index ec1d684c7c..b0102e0b1b 100644 --- a/examples/DIIID-like_truncation_example/gpec.toml +++ b/examples/DIIID-like_truncation_example/gpec.toml @@ -37,7 +37,7 @@ delta_mhigh = 8 # Expands upper bound of Fourier harmonics singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = true # Truncate at (last_rational_q + rational_offset_fraction)/n — TRUE for diverted equilibria (q → ∞ at separatrix) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) psilim_from_layer_overlap = true # Cap psilim where adjacent resistive layers overlap (the scan is recorded only when capping) diff --git a/examples/LAR_beta_scan/gpec.toml b/examples/LAR_beta_scan/gpec.toml index 6d491b40a0..de32ed4b81 100644 --- a/examples/LAR_beta_scan/gpec.toml +++ b/examples/LAR_beta_scan/gpec.toml @@ -62,7 +62,7 @@ mtheta_vacuum = 960 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Order of the singular-surface (Frobenius) series expansion -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for limited/analytical equilibria — rationals sparse, rational_offset_fraction would chop too much edge rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/LAR_epsilon_scan/gpec.toml b/examples/LAR_epsilon_scan/gpec.toml index 6a116042ae..16b691375a 100644 --- a/examples/LAR_epsilon_scan/gpec.toml +++ b/examples/LAR_epsilon_scan/gpec.toml @@ -63,7 +63,7 @@ mtheta_vacuum = 960 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Order of the singular-surface (Frobenius) series expansion -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for limited/analytical equilibria — rationals sparse, rational_offset_fraction would chop too much edge rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/LAR_ideal_match_test/gpec.toml b/examples/LAR_ideal_match_test/gpec.toml index a94256389e..434c7c1713 100644 --- a/examples/LAR_ideal_match_test/gpec.toml +++ b/examples/LAR_ideal_match_test/gpec.toml @@ -58,7 +58,7 @@ mtheta_vacuum = 960 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Power-series order for the singular-surface asymptotics -integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Keep psilim at psihigh (do not truncate at last_rational_q + rational_offset_fraction) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n (only used when truncate_at_rational_offset = true) diff --git a/examples/LAR_resistive_match_test/gpec.toml b/examples/LAR_resistive_match_test/gpec.toml index 190fb93e01..5e5f0ff64d 100644 --- a/examples/LAR_resistive_match_test/gpec.toml +++ b/examples/LAR_resistive_match_test/gpec.toml @@ -60,7 +60,7 @@ mtheta_vacuum = 960 # Number of points used in splines over poloidal singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series frobenius_order = 6 # Power-series order for the singular-surface asymptotics -integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Galerkin" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Keep psilim at psihigh (do not truncate at last_rational_q + rational_offset_fraction) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction) / n (only used when truncate_at_rational_offset = true) diff --git a/examples/Solovev_ideal_example/gpec.toml b/examples/Solovev_ideal_example/gpec.toml index b4ce76caa7..fa7f22c5b7 100644 --- a/examples/Solovev_ideal_example/gpec.toml +++ b/examples/Solovev_ideal_example/gpec.toml @@ -60,7 +60,7 @@ mtheta_vacuum = 960 # Number of points used in splines over poloidal a singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for limited/analytical equilibria — rationals sparse, rational_offset_fraction would chop too much edge rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/Solovev_ideal_example_3D/gpec.toml b/examples/Solovev_ideal_example_3D/gpec.toml index 79d63b4269..e24fd00d1e 100644 --- a/examples/Solovev_ideal_example_3D/gpec.toml +++ b/examples/Solovev_ideal_example_3D/gpec.toml @@ -44,7 +44,7 @@ nzeta_vacuum = 96 # Number of points used in splines over toroidal a singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for limited/analytical equilibria — rationals sparse, rational_offset_fraction would chop too much edge rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/Solovev_ideal_example_multi_n/gpec.toml b/examples/Solovev_ideal_example_multi_n/gpec.toml index c49a8132ac..755136ed3b 100644 --- a/examples/Solovev_ideal_example_multi_n/gpec.toml +++ b/examples/Solovev_ideal_example_multi_n/gpec.toml @@ -51,7 +51,7 @@ singfac_min = 5e-4 # Distance |m - nq| from each rational surface at # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details). # The multi-n Δ' matrix has open issues and is skipped with a warning; the energies stay valid. -integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Riccati" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for multi-n — rational_offset_fraction truncation is ambiguous when n varies (sing_lim! skips anyway) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/examples/TJ_ideal_example/gpec.toml b/examples/TJ_ideal_example/gpec.toml index 0ba417cdb1..2a6cdcf52f 100644 --- a/examples/TJ_ideal_example/gpec.toml +++ b/examples/TJ_ideal_example/gpec.toml @@ -44,7 +44,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmoni delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator diff --git a/examples/TJ_kinetic_NTV_example/gpec.toml b/examples/TJ_kinetic_NTV_example/gpec.toml index a5ed48d3e4..09215540aa 100644 --- a/examples/TJ_kinetic_NTV_example/gpec.toml +++ b/examples/TJ_kinetic_NTV_example/gpec.toml @@ -33,7 +33,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmoni delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator diff --git a/examples/TJ_kinetic_calculated_example/gpec.toml b/examples/TJ_kinetic_calculated_example/gpec.toml index 518e102b73..6e4cae56e6 100644 --- a/examples/TJ_kinetic_calculated_example/gpec.toml +++ b/examples/TJ_kinetic_calculated_example/gpec.toml @@ -46,7 +46,7 @@ delta_mhigh = 8 # Expands upper bound of Fourier harmoni mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator diff --git a/examples/TJ_kinetic_multiion_example/gpec.toml b/examples/TJ_kinetic_multiion_example/gpec.toml index f37e0b511b..db9c1bdd5a 100644 --- a/examples/TJ_kinetic_multiion_example/gpec.toml +++ b/examples/TJ_kinetic_multiion_example/gpec.toml @@ -45,7 +45,7 @@ delta_mlow = 8 # Expands lower bound of Fourier harmoni delta_mhigh = 8 # Expands upper bound of Fourier harmonics mtheta_vacuum = 960 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 5e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator diff --git a/examples/a10_kinetic_example/gpec.toml b/examples/a10_kinetic_example/gpec.toml index a990d5a642..b1e783eede 100644 --- a/examples/a10_kinetic_example/gpec.toml +++ b/examples/a10_kinetic_example/gpec.toml @@ -56,7 +56,7 @@ delta_mhigh = 6 # Expands upper bound of Fourier harmonics mtheta_vacuum = 512 # Number of points used in splines over poloidal angle at the plasma-vacuum interface kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator diff --git a/regression-harness/cases/diiid_n1_riccati.toml b/regression-harness/cases/diiid_n1_riccati.toml index 115ed6c23c..b9d9a28efb 100644 --- a/regression-harness/cases/diiid_n1_riccati.toml +++ b/regression-harness/cases/diiid_n1_riccati.toml @@ -1,8 +1,7 @@ -# Regression case: DIII-D-like n=1 Δ' matrix from the Riccati chunked propagator BVP. -# The Riccati integrator is the only one that produces SingularSurfaces/Delta_prime_matrix, so -# this case is the canonical Δ' track (its sibling diiid_n1 runs the forward integrator and -# carries the ξ/perturbed-equilibrium quantities instead). Also tracks the free-boundary -# energies and singular-surface locations the BVP depends on, so a Δ' move can be attributed. +# Regression case: DIII-D-like n=1 Δ' matrix from the Riccati chunked propagator BVP, and the Riccati +# plasma response to the C-coil. The canonical Δ' track (its sibling diiid_n1 runs the forward integrator), +# with the resonant coupling from both the finite-width jump and the asymptotic small solution. Also tracks the +# free-boundary energies and singular-surface locations the BVP depends on, so a Δ' move can be attributed. # Each [quantities.*] block names an HDF5 path in the run output, how to extract it, and the # noise floor below which a difference is treated as zero. [case] @@ -162,6 +161,72 @@ label = "beta_n" noise_threshold = 1e-12 order = 62 +# Plasma response to the C-coil: the resonant coupling from the finite-width ∂b^ψ/∂ψ jump and, through Delta_EF, +# from the asymptotic small solution (_asymptotic); the solver's own exponent α at each surface. +[quantities.alpha] +h5path = "SingularSurfaces/alpha" +type = "complex_vector" +extract = "all_complex" +label = "solver exponent alpha per surface" +noise_threshold = 1e-10 +order = 70 + +[quantities.permeability_diag] +h5path = "PerturbedEquilibrium/ResponseMatrices/permeability" +type = "complex_matrix" +extract = "diagonal_complex" +label = "permeability diagonal" +noise_threshold = 1e-8 +order = 71 + +[quantities.delta_mn_all] +h5path = "PerturbedEquilibrium/SingularCoupling/Delta_mn" +type = "complex_vector" +extract = "all_complex" +label = "forcing-driven Delta_mn per row" +noise_threshold = 1e-8 +order = 72 + +[quantities.delta_mn_asymptotic_all] +h5path = "PerturbedEquilibrium/SingularCoupling/Delta_mn_asymptotic" +type = "complex_vector" +extract = "all_complex" +label = "forcing-driven asymptotic Delta_mn per row" +noise_threshold = 1e-8 +order = 73 + +[quantities.resonant_field_all] +h5path = "PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field" +type = "complex_vector" +extract = "all_complex" +label = "resonant field per row" +noise_threshold = 1e-8 +order = 74 + +[quantities.resonant_field_asymptotic_all] +h5path = "PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field_asymptotic" +type = "complex_vector" +extract = "all_complex" +label = "asymptotic resonant field per row" +noise_threshold = 1e-8 +order = 75 + +[quantities.island_half_width_asymptotic] +h5path = "PerturbedEquilibrium/SingularCoupling/island_half_width_asymptotic" +type = "real_vector" +extract = "all_real" +label = "asymptotic island half-width per row" +noise_threshold = 1e-8 +order = 76 + +[quantities.c_delta_mn_asymptotic_norm] +h5path = "PerturbedEquilibrium/SingularCoupling/C_Delta_mn_asymptotic" +type = "complex_matrix" +extract = "norm" +label = "||C_Delta_mn_asymptotic||" +noise_threshold = 1e-8 +order = 77 + # Runtime [quantities.runtime] h5path = "" diff --git a/regression-harness/cases/gal_resistive_diiid.toml b/regression-harness/cases/gal_resistive_diiid.toml index 8fef96f539..afe693ca0a 100644 --- a/regression-harness/cases/gal_resistive_diiid.toml +++ b/regression-harness/cases/gal_resistive_diiid.toml @@ -121,6 +121,56 @@ label = "gal match residual" noise_threshold = 1e-10 order = 44 +# Perturbed equilibrium of the matched result under the C-coil: the penetrated field and the asymptotic resonant metrics +# (a matched result has no finite-width metrics). +[quantities.gal_pe_penetrated_field_all] +h5path = "PerturbedEquilibrium/SingularCoupling/penetrated_area_weighted_field" +type = "complex_vector" +extract = "all_complex" +label = "matched penetrated field per row" +noise_threshold = 1e-8 +order = 45 + +[quantities.gal_pe_c_penetrated_norm] +h5path = "PerturbedEquilibrium/SingularCoupling/C_penetrated_area_weighted_field" +type = "complex_matrix" +extract = "norm" +label = "||matched C_penetrated_area_weighted_field||" +noise_threshold = 1e-8 +order = 46 + +[quantities.gal_pe_delta_mn_asymptotic_all] +h5path = "PerturbedEquilibrium/SingularCoupling/Delta_mn_asymptotic" +type = "complex_vector" +extract = "all_complex" +label = "matched asymptotic Delta_mn per row" +noise_threshold = 1e-8 +order = 47 + +[quantities.gal_pe_resonant_field_asymptotic_all] +h5path = "PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field_asymptotic" +type = "complex_vector" +extract = "all_complex" +label = "matched asymptotic resonant field per row" +noise_threshold = 1e-8 +order = 48 + +[quantities.gal_pe_island_half_width_asymptotic] +h5path = "PerturbedEquilibrium/SingularCoupling/island_half_width_asymptotic" +type = "real_vector" +extract = "all_real" +label = "matched asymptotic island half-width per row" +noise_threshold = 1e-8 +order = 49 + +[quantities.gal_pe_permeability_diag] +h5path = "PerturbedEquilibrium/ResponseMatrices/permeability" +type = "complex_matrix" +extract = "diagonal_complex" +label = "matched permeability diagonal" +noise_threshold = 1e-8 +order = 50 + [quantities.runtime] h5path = "" type = "runtime" diff --git a/test/test_data/regression_solovev_ideal_example/gpec.toml b/test/test_data/regression_solovev_ideal_example/gpec.toml index 72493fecdb..7833418911 100644 --- a/test/test_data/regression_solovev_ideal_example/gpec.toml +++ b/test/test_data/regression_solovev_ideal_example/gpec.toml @@ -45,7 +45,7 @@ mtheta_vacuum = 64 # Number of points used in splines over polo singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for limited/analytical equilibria — rationals sparse, rational_offset_fraction would chop too much edge rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml b/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml index 4caa2594fc..22f20886b2 100644 --- a/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml +++ b/test/test_data/regression_solovev_ideal_example_multi_n/gpec.toml @@ -45,7 +45,7 @@ mtheta_vacuum = 64 # Number of points used in splines over polo singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Integrator selection and domain truncation (see ForceFreeStatesControl docstring for details) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # FALSE for multi-n — rational_offset_fraction truncation is ambiguous when n varies (sing_lim! skips anyway) rational_offset_fraction = 0.2 # Truncate integration at (last_rational_q + rational_offset_fraction)/n (used when truncate_at_rational_offset = true) diff --git a/test/test_data/regression_solovev_kinetic_calculated/gpec.toml b/test/test_data/regression_solovev_kinetic_calculated/gpec.toml index 53a79dc809..96c6b0bf16 100644 --- a/test/test_data/regression_solovev_kinetic_calculated/gpec.toml +++ b/test/test_data/regression_solovev_kinetic_calculated/gpec.toml @@ -45,7 +45,7 @@ delta_mhigh = 0 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator diff --git a/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml b/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml index 6d915442fe..64701222a6 100644 --- a/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml +++ b/test/test_data/regression_solovev_kinetic_nuzero/gpec.toml @@ -45,7 +45,7 @@ delta_mhigh = 0 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at plasma-vacuum interface. kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) singfac_min = 1e-4 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series # Numerical settings of the forward integrator diff --git a/test/test_data/regression_tj_ideal_example/gpec.toml b/test/test_data/regression_tj_ideal_example/gpec.toml index 162eac8018..f8fa35560d 100644 --- a/test/test_data/regression_tj_ideal_example/gpec.toml +++ b/test/test_data/regression_tj_ideal_example/gpec.toml @@ -31,7 +31,7 @@ delta_mlow = 4 # Expands lower bound of Fourier harmoni delta_mhigh = 4 # Expands upper bound of Fourier harmonics mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator diff --git a/test/test_data/regression_tj_kinetic_calculated/gpec.toml b/test/test_data/regression_tj_kinetic_calculated/gpec.toml index 7dae5f9a84..3bc88d565c 100644 --- a/test/test_data/regression_tj_kinetic_calculated/gpec.toml +++ b/test/test_data/regression_tj_kinetic_calculated/gpec.toml @@ -33,7 +33,7 @@ delta_mhigh = 4 # Expands upper bound of Fourier harmoni mtheta_vacuum = 64 # Number of points used in splines over poloidal angle at the plasma-vacuum interface singfac_min = 1e-6 # Distance |m - nq| from each rational surface at which the integration crosses it through its asymptotic series kinetic = "KineticForces" # Kinetic source: the drift-kinetic matrices of the [KineticForces] model (omit for an ideal run) -integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for [PerturbedEquilibrium]/kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) +integrator = "Forward" # Integration formalism, whose numerical settings are its own section: "Forward" (dense ξ, needed for kinetic), "Riccati" (chunked propagator BVP, unlocks the singular-surface Δ′ matrix), or "Galerkin" (outer-region singular Galerkin Δ′) truncate_at_rational_offset = false # Truncate integration at (last_rational_q + rational_offset_fraction)/n; false for analytic equilibria # Numerical settings of the forward integrator From 0c02af73f623a1f658fb76f2ba84ebd083778a9f Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Thu, 26 Nov 2026 11:19:12 +0100 Subject: [PATCH 17/27] Analysis - FEATURE - Let the coupling plots choose their matrix and coupling set, and draw penetrated over effective islands --- ext/GPECMakieExt/perturbedequilibrium.jl | 69 ++++-- src/Analysis/PerturbedEquilibrium.jl | 223 +++++++++++------- src/Analysis/Registry.jl | 13 +- .../PerturbedEquilibriumStructs.jl | 3 +- test/runtests_analysis_plots.jl | 31 +++ test/runtests_dominant_coupling.jl | 12 +- 6 files changed, 233 insertions(+), 118 deletions(-) diff --git a/ext/GPECMakieExt/perturbedequilibrium.jl b/ext/GPECMakieExt/perturbedequilibrium.jl index 32f65e63ab..ebb12d9a8d 100644 --- a/ext/GPECMakieExt/perturbedequilibrium.jl +++ b/ext/GPECMakieExt/perturbedequilibrium.jl @@ -14,7 +14,8 @@ end # Each coupling row: values, label, y scale and reference line (nothing for none). function _coupling_row(d, key) - key === :field && return (_magnitude_row(abs.(d.field), rich("|b̄", subscript("res"), "|"), "T")..., nothing) + key === :field && return (_magnitude_row(abs.(d.penetrated === nothing ? d.field : vcat(d.field, d.penetrated)), rich("|b̄", subscript("res"), "|"), "T")..., + nothing) key === :current && return (_magnitude_row(abs.(d.current), rich("|I", subscript("res"), "|"), "A")..., nothing) key === :island_hw && return (d.island_hw, rich("w/2 (", PSIN, ")"), identity, nothing) key === :chirikov && return (d.chirikov, "island overlap\nChirikov", identity, 1.0) @@ -30,16 +31,17 @@ const _ROW_TITLES = Dict( ) function _coupling_title(d, keys) - :chirikov in keys || return _ROW_TITLES[only(keys) === :field && d.penetrated !== nothing ? :field_pen : only(keys)] + :chirikov in keys || return rich(_ROW_TITLES[only(keys) === :field && d.penetrated !== nothing ? :field_pen : only(keys)], d.asymptotic ? " (asymptotic)" : "") + head = d.asymptotic ? "Asymptotic coupling" : "Resonant coupling" k = count(>=(1), d.chirikov) - return k == 0 ? "Resonant coupling: Chirikov parameter < 1 on every surface" : "Resonant coupling: islands overlap on $k of $(length(d.chirikov)) surfaces" + return k == 0 ? "$head: Chirikov parameter < 1 on every surface" : "$head: islands overlap on $k of $(length(d.chirikov)) surfaces" end # The field row with the penetrated field: b̄_res and b̄_pen as paired stems on one shared scale. function _field_pair!(ax, d, x) v, ylabel, yscale = _magnitude_row(vcat(abs.(d.field), abs.(d.penetrated)), rich("|b̄|"), "T") k = length(x) - ax.ylabel, ax.yscale = ylabel, yscale + ax.ylabel = ylabel positive = filter(>(0), v) base = yscale === log10 ? minimum(positive) / 3 : 0.0 yscale === identity && ylims!(ax, 0, 1.12 * maximum(positive)) @@ -228,13 +230,13 @@ function PE._plot_singular_mode_rz(curves) at = "φ = " * _num(rad2deg(first(curves).phi)) * "°" fig = _figure((330n + 150, 560)) for (j, c) in enumerate(curves) - title = n == 1 ? rich("Dominant mode $(c.mode) at $at, σ = ", _num(c.sigma)) : rich("mode $(c.mode), σ = ", _num(c.sigma)) + title = n == 1 ? rich("Dominant mode $(c.mode) of C_$(c.matrix) at $at, σ = ", _num(c.sigma)) : rich("mode $(c.mode), σ = ", _num(c.sigma)) ax = Axis(fig[1, j]; title, aspect=DataAspect(), xlabel="R (m)", ylabel="Z (m)", ylabelvisible=j == 1, yticklabelsvisible=j == 1) lines!(ax, c.R, c.Z; color=c.b, colormap=DIVERGING, colorrange=(-1, 1), linewidth=16) lines!(ax, c.R, c.Z; color=:black, linewidth=1) end Colorbar(fig[1, n+1]; colormap=DIVERGING, limits=(-1, 1), label=rich("b", subscript("n"), " at $at (arb.)")) - n > 1 && Label(fig[0, 1:n], "Dominant resonant-coupling modes on the control surface"; font=:bold, fontsize=16) + n > 1 && Label(fig[0, 1:n], "Dominant modes of C_$(first(curves).matrix) on the control surface"; font=:bold, fontsize=16) fig end end @@ -247,14 +249,14 @@ function PE._plot_coupling_matrix(d) ns, rank = size(A, 1), length(d.sigma) fig = _figure((1150, 820)) hax = Axis(fig[1, 1]; ylabel="rational surface q = m/n", yticks=(1:ns, d.labels), xticklabelsvisible=false, - title=rich("Resonant coupling C: |b̄", subscript("res"), "| per unit b̃", subscript("m"))) + title=rich("Coupling C_$(d.matrix) per unit b̃", subscript("m"))) hm = heatmap!(hax, d.m, 1:ns, permutedims(A); colormap=:viridis, colorscale=log10, colorrange=(1e-4top, top), lowclip=Makie.to_colormap(:viridis)[1]) scatter!(hax, d.m_res, 1:ns; marker=:rect, color=:transparent, strokecolor=:white, strokewidth=1.5, markersize=16) for s in setdiff(1:ns, d.retained) poly!(hax, Rect(d.m[1] - 0.5, s - 0.5, length(d.m), 1); color=(:white, 0.55)) end - Colorbar(fig[1, 3], hm; label="|C| (T per unit b̃)") + Colorbar(fig[1, 3], hm; label="|C| (per unit b̃)") uax = Axis(fig[1, 2]; xlabel="|U| (unit norm)", yticks=(1:ns, d.labels), yticklabelsvisible=false, title="left singular vectors", limits=((0, 1.05), nothing)) @@ -269,7 +271,7 @@ function PE._plot_coupling_matrix(d) linkxaxes!(hax, vax) axislegend(vax; position=:rt, framevisible=false) - sax = Axis(fig[2, 2]; xlabel="mode k", ylabel=rich("σ", subscript("k"), " (T per unit b̃)"), title="singular values", xticks=1:rank, + sax = Axis(fig[2, 2]; xlabel="mode k", ylabel=rich("σ", subscript("k"), " (per unit b̃)"), title="singular values", xticks=1:rank, limits=(nothing, (0, 1.12 * maximum(d.sigma)))) stem!(sax, 1:rank, d.sigma; color=[WONG[mod1(k, 7)] for k in 1:rank], stemcolor=(:gray, 0.6), markersize=12) @@ -316,20 +318,32 @@ function PE._plot_perturbed_equilibrium_summary(coupling, edge, xi, rz) end end -function PE._plot_islands(d, name) +function PE._plot_islands(d, name; effective=nothing) return themed() do chains = d.chains - isempty(chains) && throw(ArgumentError("no island has a nonzero half-width")) - colors = Makie.resample_cmap(:viridis, length(chains) + 2) + under = effective === nothing ? NamedTuple[] : effective.chains + isempty(chains) && isempty(under) && throw(ArgumentError("no island has a nonzero half-width")) + labels = unique([c.label for c in vcat(under, chains)]) + palette = Makie.resample_cmap(:viridis, length(labels) + 2) + color(c) = palette[findfirst(==(c.label), labels)+1] fig = _figure((1250, 640)) # (θ, ψ_N): the chains in flux coordinates, the outboard midplane central. - bottom = max(0.0, minimum(c.psis - 1.5c.w for c in chains) - 0.03) + bottom = max(0.0, minimum(c.psis - 1.5c.w for c in vcat(under, chains)) - 0.03) a = Axis(fig[1, 1]; xlabel="poloidal angle θ (deg)", ylabel=PSIN, xticks=-180:90:180, limits=((-180, 180), (bottom, 1.02)), title="$name at φ = $(_num(rad2deg(d.phi)))°") - for (k, c) in enumerate(chains) + for c in under shift = circshift(1:length(c.theta), length(c.theta) ÷ 2) - band!(a, sort(c.theta), c.lo[shift], c.hi[shift]; color=(colors[k+1], 0.6)) - hlines!(a, c.psis; color=(colors[k+1], 0.9), linewidth=0.8, linestyle=:dash) + θ = sort(c.theta) + band!(a, θ, c.lo[shift], c.hi[shift]; color=(color(c), 0.12)) + lines!(a, θ, c.lo[shift]; color=color(c), linewidth=1.2, linestyle=:dash) + lines!(a, θ, c.hi[shift]; color=color(c), linewidth=1.2, linestyle=:dash) + end + for c in chains + shift = circshift(1:length(c.theta), length(c.theta) ÷ 2) + band!(a, sort(c.theta), c.lo[shift], c.hi[shift]; color=(color(c), effective === nothing ? 0.6 : 0.75)) + end + for c in (isempty(under) ? chains : under) + hlines!(a, c.psis; color=(color(c), 0.9), linewidth=0.8, linestyle=:dot) text!(a, -178, c.psis; text=c.label, align=(:left, :center), fontsize=11) end # (R, Z): the same chains on the poloidal plane. @@ -337,12 +351,27 @@ function PE._plot_islands(d, name) for s in d.surfaces[1:(end-1)] lines!(b, s...; color=(:black, 0.15), linewidth=0.8) end - for (k, c) in enumerate(chains) - poly!(b, Point2f.(c.polygon); color=(colors[k+1], 0.7), strokewidth=0) + for c in under + pts = Point2f.(c.polygon) + poly!(b, pts; color=(color(c), 0.12), strokewidth=0) + lines!(b, vcat(pts, pts[1:1]); color=color(c), linewidth=1.0, linestyle=:dash) + end + for c in chains + poly!(b, Point2f.(c.polygon); color=(color(c), 0.7), strokewidth=0) end lines!(b, d.surfaces[end]...; color=:black, linewidth=1.5) - Legend(fig[1, 3], [PolyElement(; color=(colors[k+1], 0.7)) for k in eachindex(chains)], ["$(c.label): $(_num(c.w))" for c in chains], - rich("w/2 (", PSIN, ")"); framevisible=false) + if effective === nothing + Legend(fig[1, 3], [PolyElement(; color=(color(c), 0.7)) for c in chains], ["$(c.label): $(_num(c.w))" for c in chains], + rich("w/2 (", PSIN, ")"); framevisible=false) + else + w_pen = Dict(c.label => c.w for c in chains) + w_eff = Dict(c.label => c.w for c in under) + Legend(fig[1, 3], + [[PolyElement(; color=(palette[k+1], 0.75)) for k in eachindex(labels)], + [PolyElement(; color=(:gray, 0.12), strokecolor=:gray, strokewidth=1.2, linestyle=:dash), PolyElement(; color=(:gray, 0.75))]], + [["$l: $(_num(get(w_eff, l, 0.0))) → $(_num(get(w_pen, l, 0.0)))" for l in labels], ["effective", "penetrated"]], + [rich("w/2 (", PSIN, "): effective → penetrated"), "islands"]; framevisible=false) + end colsize!(fig.layout, 1, Relative(0.5)) fig end diff --git a/src/Analysis/PerturbedEquilibrium.jl b/src/Analysis/PerturbedEquilibrium.jl index 770150bd5b..eee4ea3671 100644 --- a/src/Analysis/PerturbedEquilibrium.jl +++ b/src/Analysis/PerturbedEquilibrium.jl @@ -10,7 +10,7 @@ module PerturbedEquilibrium using HDF5 using ..Analysis: register!, _require, _can, capabilities, REASONS, _draw -import ...PerturbedEquilibrium: PerturbedEquilibriumState, PlasmaResponse +import ...PerturbedEquilibrium: PerturbedEquilibriumState, PlasmaResponse, dominant_coupling import ..CoilForcing: plot_control_surface, _control_surface_data, _equil_helicity const Source = Union{AbstractString,PerturbedEquilibriumState} @@ -21,21 +21,35 @@ const _RESPONSE = "PerturbedEquilibrium/Response/" # The penetrated field when the run carries a nonzero one (matched runs), otherwise `nothing`. _penetrated(v) = isempty(v) || all(iszero, v) ? nothing : v -function _coupling_data(s::PerturbedEquilibriumState) +# The asymptotic set by default when the source carries no finite-width one (a matched result). +_default_asymptotic(s::PerturbedEquilibriumState) = isempty(s.resonant_area_weighted_field) +_default_asymptotic(h5path::AbstractString) = h5open(fid -> !haskey(fid, _COUPLING * "resonant_area_weighted_field"), h5path, "r") + +_set_name(asymptotic::Bool) = asymptotic ? "asymptotic" : "finite-width" + +# The applied resonant rows of one coupling set: from the finite-width ∂b^ψ/∂ψ jump, or with `asymptotic` from the asymptotic small solution. +function _coupling_data(s::PerturbedEquilibriumState, asymptotic::Bool) r = s.response - return (; field=s.resonant_area_weighted_field, penetrated=_penetrated(s.penetrated_area_weighted_field), current=s.resonant_current, island_hw=s.island_half_width, - chirikov=s.chirikov_parameter, - delta_mn=s.delta_mn, psi=r.rational_psi, q=r.rational_q, m=r.rational_m_res, n=r.rational_n) + sfx = asymptotic ? "_asymptotic" : "" + pick(name) = getfield(s, Symbol(name, sfx)) + isempty(pick(:resonant_area_weighted_field)) && throw(ArgumentError("this result carries no $(_set_name(asymptotic)) resonant coupling")) + return (; asymptotic, field=pick(:resonant_area_weighted_field), penetrated=_penetrated(s.penetrated_area_weighted_field), current=pick(:resonant_current), + island_hw=pick(:island_half_width), chirikov=pick(:chirikov_parameter), delta_mn=pick(:delta_mn), psi=r.rational_psi, q=r.rational_q, + m=r.rational_m_res, n=r.rational_n) end -function _coupling_data(h5path::AbstractString) +function _coupling_data(h5path::AbstractString, asymptotic::Bool) h5open(h5path, "r") do fid + sfx = asymptotic ? "_asymptotic" : "" + haskey(fid, _COUPLING * "resonant_area_weighted_field" * sfx) || throw(ArgumentError("$h5path carries no $(_set_name(asymptotic)) resonant coupling")) rd(name) = read(fid[_COUPLING*name]) pen = haskey(fid, _COUPLING * "penetrated_area_weighted_field") ? _penetrated(rd("penetrated_area_weighted_field")) : nothing - (; field=rd("resonant_area_weighted_field"), penetrated=pen, current=rd("resonant_current"), island_hw=rd("island_half_width"), chirikov=rd("chirikov_parameter"), - delta_mn=rd("Delta_mn"), psi=rd("rational_psi"), q=rd("rational_q"), m=rd("rational_m"), n=rd("rational_n")) + (; asymptotic, field=rd("resonant_area_weighted_field" * sfx), penetrated=pen, current=rd("resonant_current" * sfx), + island_hw=rd("island_half_width" * sfx), chirikov=rd("chirikov_parameter" * sfx), delta_mn=rd("Delta_mn" * sfx), psi=rd("rational_psi"), + q=rd("rational_q"), m=rd("rational_m"), n=rd("rational_n")) end end +_coupling_data(src, asymptotic::Nothing=nothing) = _coupling_data(src, _default_asymptotic(src)) const _COMPONENTS = Dict( :xi_psi => (dataset="xi_psi", field=:psi, modes=:xi_modes, needs=:response_xi), @@ -80,7 +94,7 @@ function _plot_perturbed_equilibrium_summary end const _COUPLING_ROWS = (:field, :current, :island_hw, :chirikov, :delta_mn) """ - plot_resonant_area_weighted_field(src; save_path=nothing) + plot_resonant_area_weighted_field(src; asymptotic=nothing, save_path=nothing) Plot the resonant coupling at each rational surface in rows sharing a q = m/n axis: the resonant area-weighted field |b̄_res|, the resonant current |I_res|, the island half-width w/2, the effective island-overlap Chirikov parameter @@ -93,19 +107,21 @@ overlapping islands. ### Keyword arguments + - `asymptotic`: Draw the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `save_path`: If given, save the figure to this path (default: `nothing`) ### Returns A Makie `Figure`. """ -function plot_resonant_area_weighted_field(src::Source; save_path=nothing) +function plot_resonant_area_weighted_field(src::Source; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) _require(plot_resonant_area_weighted_field, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), _COUPLING_ROWS; save_path) + return _draw(_plot_resonant_coupling, _coupling_data(src, asymptotic), _COUPLING_ROWS; save_path) end """ - plot_resonant_area_weighted_field_amplitude(src; save_path=nothing) + plot_resonant_area_weighted_field_amplitude(src; asymptotic=nothing, save_path=nothing) Plot the resonant area-weighted field |b̄_res| = |Φ_res|/A at each rational surface [Pharr 2026], in tesla, beside the penetrated field |b̄_pen| when the run carries one. @@ -116,19 +132,21 @@ penetrated field |b̄_pen| when the run carries one. ### Keyword arguments + - `asymptotic`: Draw the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `save_path`: If given, save the figure to this path (default: `nothing`) ### Returns A Makie `Figure`. """ -function plot_resonant_area_weighted_field_amplitude(src::Source; save_path=nothing) +function plot_resonant_area_weighted_field_amplitude(src::Source; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) _require(plot_resonant_area_weighted_field_amplitude, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), (:field,); save_path) + return _draw(_plot_resonant_coupling, _coupling_data(src, asymptotic), (:field,); save_path) end """ - plot_island_widths(src; save_path=nothing) + plot_island_widths(src; asymptotic=nothing, save_path=nothing) Plot the island half-width w/2 at each rational surface, in ψ_N. @@ -138,19 +156,21 @@ Plot the island half-width w/2 at each rational surface, in ψ_N. ### Keyword arguments + - `asymptotic`: Draw the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `save_path`: If given, save the figure to this path (default: `nothing`) ### Returns A Makie `Figure`. """ -function plot_island_widths(src::Source; save_path=nothing) +function plot_island_widths(src::Source; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) _require(plot_island_widths, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), (:island_hw,); save_path) + return _draw(_plot_resonant_coupling, _coupling_data(src, asymptotic), (:island_hw,); save_path) end """ - plot_chirikov_parameter(src; save_path=nothing) + plot_chirikov_parameter(src; asymptotic=nothing, save_path=nothing) Plot the effective island-overlap Chirikov parameter at each rational surface, with the overlap threshold 1 marked. @@ -160,19 +180,21 @@ Plot the effective island-overlap Chirikov parameter at each rational surface, w ### Keyword arguments + - `asymptotic`: Draw the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `save_path`: If given, save the figure to this path (default: `nothing`) ### Returns A Makie `Figure`. """ -function plot_chirikov_parameter(src::Source; save_path=nothing) +function plot_chirikov_parameter(src::Source; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) _require(plot_chirikov_parameter, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), (:chirikov,); save_path) + return _draw(_plot_resonant_coupling, _coupling_data(src, asymptotic), (:chirikov,); save_path) end """ - plot_driven_delta_mn(src; save_path=nothing) + plot_driven_delta_mn(src; asymptotic=nothing, save_path=nothing) Plot the forcing-driven Re Δ_mn at each rational surface, the jump of ∂b^ψ/∂ψ across it that the applied forcing drives; for the equilibrium's Δ′ matrix of a Riccati or Galerkin solve, see `ForceFreeStates.plot_delta_prime`. @@ -183,15 +205,17 @@ drives; for the equilibrium's Δ′ matrix of a Riccati or Galerkin solve, see ` ### Keyword arguments + - `asymptotic`: Draw the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `save_path`: If given, save the figure to this path (default: `nothing`) ### Returns A Makie `Figure`. """ -function plot_driven_delta_mn(src::Source; save_path=nothing) +function plot_driven_delta_mn(src::Source; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) _require(plot_driven_delta_mn, src) - return _draw(_plot_resonant_coupling, _coupling_data(src), (:delta_mn,); save_path) + return _draw(_plot_resonant_coupling, _coupling_data(src, asymptotic), (:delta_mn,); save_path) end const _STYLES = (:log_heatmap, :linear_heatmap, :lines) @@ -244,7 +268,7 @@ A Makie `Figure`. Throws an `ArgumentError` when no panel can be drawn. function plot_perturbed_equilibrium_summary(src::Source; save_path=nothing) _require(plot_perturbed_equilibrium_summary, src) caps = capabilities(src) - coupling = _can(plot_resonant_area_weighted_field_amplitude, caps) ? _coupling_data(src) : nothing + coupling = _can(plot_resonant_area_weighted_field_amplitude, caps) ? _coupling_data(src, nothing) : nothing edge = :response_b in caps ? _response_data(src, :b_psi) : nothing xi = _can(plot_mode_spectrogram, caps) ? _response_data(src, :xi_psi) : nothing rz = src isa PerturbedEquilibriumState && _can(plot_perturbed_field_rz, caps) ? _poloidal_data(src, :b_n) : nothing @@ -301,9 +325,9 @@ function _boundary_displacement(pe::PerturbedEquilibriumState; phi=0.0, ntheta=7 return (; R=first.(pts), Z=last.(pts), xi) end -# Island chains at toroidal angle φ between ψ_s ∓ (w/2)|cos(ξ/2)|, ξ = 2π m θ + n (ν − φ) + α with α the phase of the -# surface's resonant field, in (θ, ψ_N) and as (R, Z) polygons; ψ is clipped to the last flux surface. -function _island_chains(pe::PerturbedEquilibriumState, halfwidth; phi=0.0, ntheta=1440) +# Island chains at toroidal angle φ between ψ_s ∓ (w/2)|cos(ξ/2)|, ξ = 2π m θ + n (ν − φ) + α with α the phase of `field` +# on that surface, in (θ, ψ_N) and as (R, Z) polygons; ψ is clipped to the last flux surface. +function _island_chains(pe::PerturbedEquilibriumState, halfwidth, field; phi=0.0, ntheta=1440) resp = pe.response equil = resp.ffs.equil psimax = pe.psi_grid[end] @@ -313,7 +337,7 @@ function _island_chains(pe::PerturbedEquilibriumState, halfwidth; phi=0.0, nthet for row in eachindex(resp.rational_psi) psis, m, n, w = resp.rational_psi[row], resp.rational_m_res[row], resp.rational_n[row], halfwidth[row] w > 0 || continue - α = angle(pe.resonant_area_weighted_field[row]) + α = angle(field[row]) half = [w * abs(cos((2π * m * θ + n * (equil.rzphi_nu((psis, θ); hint) - phi) + α) / 2)) for θ in θs] lo, hi = clamp.(psis .- half, 0.0, psimax), clamp.(psis .+ half, 0.0, psimax) outer = [_rz(equil, p, θ, hint) for (p, θ) in zip(hi, θs)] @@ -359,10 +383,10 @@ function plot_perturbed_field_rz(pe::PerturbedEquilibriumState; component=:b_n, end """ - plot_effective_islands(pe; phi=0.0, save_path=nothing) + plot_effective_islands(pe; asymptotic=nothing, phi=0.0, save_path=nothing) Plot the island chains the effective resonant flux would open, in (θ, ψ_N) and on the poloidal plane at toroidal angle -φ, with each chain's half-width w/2 (in ψ_N) listed. +φ, with each chain's half-width w/2 (in ψ_N) listed. The chains take the phase of the stored effective field. ### Arguments @@ -370,6 +394,8 @@ Plot the island chains the effective resonant flux would open, in (θ, ψ_N) and ### Keyword arguments + - `asymptotic`: Use the coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the finite-width + jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `phi`: Toroidal angle in radians (default: `0.0`) - `save_path`: If given, save the figure to this path (default: `nothing`) @@ -377,16 +403,19 @@ Plot the island chains the effective resonant flux would open, in (θ, ψ_N) and A Makie `Figure`. """ -function plot_effective_islands(pe::PerturbedEquilibriumState; phi=0.0, save_path=nothing) +function plot_effective_islands(pe::PerturbedEquilibriumState; asymptotic::Union{Nothing,Bool}=nothing, phi=0.0, save_path=nothing) _require(plot_effective_islands, pe) - return _draw(_plot_islands, _island_chains(pe, pe.island_half_width; phi), "Effective islands"; save_path) + d = _coupling_data(pe, asymptotic) + title = d.asymptotic ? "Effective islands (asymptotic)" : "Effective islands" + return _draw(_plot_islands, _island_chains(pe, d.island_hw, d.field; phi), title; save_path) end """ - plot_islands(pe; phi=0.0, save_path=nothing) + plot_islands(pe; asymptotic=nothing, phi=0.0, save_path=nothing) -Plot the island chains of the penetrated field in (θ, ψ_N) and on the poloidal plane at toroidal angle φ. The -half-width scales from the effective one as w² ∝ |b̄|: w_pen = w_eff √(|b̄_pen| / |b̄_res|). +Plot the island chains of the penetrated field over those the effective resonant flux would open, in (θ, ψ_N) and on the +poloidal plane at toroidal angle φ. The penetrated half-width scales from the effective one as w² ∝ |b̄|: +w_pen = w_eff √(|b̄_pen| / |b̄_res|). Each chain takes the phase of its own field. ### Arguments @@ -394,6 +423,8 @@ half-width scales from the effective one as w² ∝ |b̄|: w_pen = w_eff √(|b ### Keyword arguments + - `asymptotic`: Use the effective coupling from the asymptotic small solution (the `_asymptotic` outputs) instead of the + finite-width jump (default: the asymptotic set when the result carries only that one, as a matched result does) - `phi`: Toroidal angle in radians (default: `0.0`) - `save_path`: If given, save the figure to this path (default: `nothing`) @@ -401,18 +432,33 @@ half-width scales from the effective one as w² ∝ |b̄|: w_pen = w_eff √(|b A Makie `Figure`. """ -function plot_islands(pe::PerturbedEquilibriumState; phi=0.0, save_path=nothing) +function plot_islands(pe::PerturbedEquilibriumState; asymptotic::Union{Nothing,Bool}=nothing, phi=0.0, save_path=nothing) _require(plot_islands, pe) - ratio = abs.(pe.penetrated_area_weighted_field) ./ max.(abs.(pe.resonant_area_weighted_field), floatmin()) - return _draw(_plot_islands, _island_chains(pe, pe.island_half_width .* sqrt.(ratio); phi), "Penetrated islands"; save_path) + d = _coupling_data(pe, asymptotic) + pen = pe.penetrated_area_weighted_field + w_pen = d.island_hw .* sqrt.(abs.(pen) ./ max.(abs.(d.field), floatmin())) + effective = _island_chains(pe, d.island_hw, d.field; phi) + return _draw(_plot_islands, _island_chains(pe, w_pen, pen; phi), "Penetrated and effective islands"; effective, save_path) +end + +# The coupling matrices a response can carry, by their name without the `C_` prefix. +const _MATRICES = (:resonant_area_weighted_field, :resonant_current, :island_width_sq, :delta_mn, :penetrated_area_weighted_field, + :resonant_area_weighted_field_asymptotic, :resonant_current_asymptotic, :island_width_sq_asymptotic, :delta_mn_asymptotic) + +# The named coupling matrix of `resp` and its SVD over the core window, as the stored dominant mode is taken. +function _coupling_svd(resp::PlasmaResponse, matrix, fn) + name = something(matrix, isempty(resp.C_resonant_area_weighted_field) ? :resonant_area_weighted_field_asymptotic : :resonant_area_weighted_field) + name in _MATRICES || throw(ArgumentError("$(nameof(fn)): matrix must be one of $(_MATRICES), got :$name")) + C = getfield(resp, Symbol(:C_, name)) + (isempty(C) || all(iszero, C)) && throw(ArgumentError("$(nameof(fn)): the plasma response carries no C_$name")) + return (; name, C, dom=dominant_coupling(C, resp.rational_psi)) end """ - plot_dominant_mode_surface(src; mode=1, n=nothing, save_path=nothing) + plot_dominant_mode_surface(src; matrix=nothing, mode=1, n=nothing, save_path=nothing) -Plot dominant resonant-coupling mode `mode`, the right singular vector of the resonant coupling matrix, as the normal -field it represents on the control surface: toroidal angle φ against poloidal angle θ, in arbitrary units (the vector -has unit norm). +Plot dominant mode `mode` of a coupling matrix, its right singular vector, as the normal field it represents on the +control surface: toroidal angle φ against poloidal angle θ, in arbitrary units (the vector has unit norm). ### Arguments @@ -420,6 +466,10 @@ has unit norm). ### Keyword arguments + - `matrix`: The coupling matrix, a `C_` field of the response without the prefix: `:resonant_area_weighted_field`, + `:resonant_current`, `:island_width_sq`, `:delta_mn`, their `_asymptotic` forms, or `:penetrated_area_weighted_field` + (default: `:resonant_area_weighted_field`, or `:resonant_area_weighted_field_asymptotic` for a response that carries only + the asymptotic set, as a matched one does) - `mode`: Which dominant mode, 1 the strongest (default: `1`) - `n`: Toroidal mode number drawn (default: the first) - `save_path`: If given, save the figure to this path (default: `nothing`) @@ -428,40 +478,42 @@ has unit norm). A Makie `Figure`. """ -function plot_dominant_mode_surface(src::Union{PlasmaResponse,PerturbedEquilibriumState}; mode::Int=1, n=nothing, save_path=nothing) +function plot_dominant_mode_surface(src::Union{PlasmaResponse,PerturbedEquilibriumState}; matrix::Union{Nothing,Symbol}=nothing, mode::Int=1, n=nothing, + save_path=nothing) _require(plot_dominant_mode_surface, src) resp = src isa PlasmaResponse ? src : src.response - 1 <= mode <= length(resp.dominant_singular_values) || - throw(ArgumentError("plot_dominant_mode_surface: mode must be 1 to $(length(resp.dominant_singular_values))")) - σ = resp.dominant_singular_values[mode] - return plot_control_surface(resp, resp.dominant_right_singular_vectors[:, mode]; n, arb=true, label="dominant mode $mode (σ = $(round(σ; sigdigits=3)))", - save_path) + c = _coupling_svd(resp, matrix, plot_dominant_mode_surface) + nk = length(c.dom.singular_values) + 1 <= mode <= nk || throw(ArgumentError("plot_dominant_mode_surface: mode must be 1 to $nk")) + σ = c.dom.singular_values[mode] + return plot_control_surface(resp, c.dom.right_singular_vectors[:, mode]; n, arb=true, + label="dominant mode $mode of C_$(c.name) (σ = $(round(σ; sigdigits=3)))", save_path) end # Each dominant mode's b_n at toroidal angle `phi` around the control-surface cross-section, normalized to its peak there, # with the boundary in (R, Z). The map's φ = 0 column of the spectrum rotated by e^{i n h φ} is the field at φ. -function _singular_mode_rz_data(resp::PlasmaResponse, modes, phi; mtheta=512) +function _singular_mode_rz_data(resp::PlasmaResponse, c, modes, phi; mtheta=512) equil = resp.ffs.equil hint = (Ref(1), Ref(1)) turn = cis(first(resp.n_modes) * _equil_helicity(equil) * phi) return map(modes) do k - v = resp.dominant_right_singular_vectors[:, k] + v = c.dom.right_singular_vectors[:, k] d = _control_surface_data(resp, v .* turn; nphi=1, mtheta) b = d.field[:, 1] ./ maximum(abs, d.field[:, 1]) pts = [_rz(equil, equil.rzphi_xs[end], mod(θ / 360, 1), hint) for θ in d.theta] R, Z = first.(pts), last.(pts) - (; mode=k, sigma=resp.dominant_singular_values[k], phi, R=[R; R[1]], Z=[Z; Z[1]], b=[b; b[1]]) + (; mode=k, matrix=c.name, sigma=c.dom.singular_values[k], phi, R=[R; R[1]], Z=[Z; Z[1]], b=[b; b[1]]) end end function _plot_singular_mode_rz end """ - plot_singular_mode_rz(src; modes=nothing, phi=0.0, save_path=nothing) + plot_singular_mode_rz(src; matrix=nothing, modes=nothing, phi=0.0, save_path=nothing) -Plot dominant resonant-coupling modes on the control-surface cross-section: the boundary in (R, Z) as a band coloured -by each mode's normal field b_n at toroidal angle φ, normalized to its peak, one panel per mode. The modes are the -stored decomposition's, over the rational surfaces with ψ_N ≤ 0.9. +Plot the dominant modes of a coupling matrix on the control-surface cross-section: the boundary in (R, Z) as a band +coloured by each mode's normal field b_n at toroidal angle φ, normalized to its peak, one panel per mode. The modes come +from the matrix's SVD over the rational surfaces with ψ_N ≤ 0.9. ### Arguments @@ -469,6 +521,10 @@ stored decomposition's, over the rational surfaces with ψ_N ≤ 0.9. ### Keyword arguments + - `matrix`: The coupling matrix, a `C_` field of the response without the prefix: `:resonant_area_weighted_field`, + `:resonant_current`, `:island_width_sq`, `:delta_mn`, their `_asymptotic` forms, or `:penetrated_area_weighted_field` + (default: `:resonant_area_weighted_field`, or `:resonant_area_weighted_field_asymptotic` for a response that carries only + the asymptotic set, as a matched one does) - `modes`: Which dominant modes, 1 the strongest (default: the first three that exist) - `phi`: Toroidal angle in radians (default: `0.0`) - `save_path`: If given, save the figure to this path (default: `nothing`) @@ -477,38 +533,40 @@ stored decomposition's, over the rational surfaces with ψ_N ≤ 0.9. A Makie `Figure`. """ -function plot_singular_mode_rz(src::Union{PlasmaResponse,PerturbedEquilibriumState}; modes=nothing, phi=0.0, save_path=nothing) +function plot_singular_mode_rz(src::Union{PlasmaResponse,PerturbedEquilibriumState}; matrix::Union{Nothing,Symbol}=nothing, modes=nothing, phi=0.0, + save_path=nothing) _require(plot_singular_mode_rz, src) resp = src isa PlasmaResponse ? src : src.response - nk = length(resp.dominant_singular_values) + c = _coupling_svd(resp, matrix, plot_singular_mode_rz) + nk = length(c.dom.singular_values) ks = something(modes, 1:min(3, nk)) all(k -> 1 <= k <= nk, ks) || throw(ArgumentError("plot_singular_mode_rz: modes must lie in 1 to $nk")) - return _draw(_plot_singular_mode_rz, _singular_mode_rz_data(resp, collect(ks), phi); save_path) + return _draw(_plot_singular_mode_rz, _singular_mode_rz_data(resp, c, collect(ks), phi); save_path) end -# The resonant coupling matrix of toroidal mode number `n` and its SVD C = U Σ Vᴴ: rows are rational surfaces, columns -# poloidal harmonics; U has rows only for the surfaces inside the SVD's core window, at `retained` in the row order. -function _coupling_matrix_data(resp::PlasmaResponse, n) +# Coupling matrix `c` of toroidal mode number `n` and its SVD C = U Σ Vᴴ: rows are rational surfaces, columns poloidal +# harmonics; U has rows only for the surfaces inside the SVD's core window, at `retained` in the row order. +function _coupling_matrix_data(resp::PlasmaResponse, c, n) n = something(n, first(resp.n_modes)) n in resp.n_modes || throw(ArgumentError("plot_coupling_matrix: n = $n is not one of the response's toroidal mode numbers $(unique(resp.n_modes))")) cols = findall(==(n), resp.n_modes) rows = findall(==(n), resp.rational_n) - inwindow = [i for (i, r) in enumerate(resp.dominant_rational_index) if r in rows] - return (; m=resp.m_modes[cols], labels=["$(resp.rational_m_res[r])/$n" for r in rows], m_res=resp.rational_m_res[rows], - C=resp.C_resonant_area_weighted_field[rows, cols], sigma=resp.dominant_singular_values, - U=resp.dominant_left_singular_vectors[inwindow, :], retained=[findfirst(==(resp.dominant_rational_index[i]), rows) for i in inwindow], - V=resp.dominant_right_singular_vectors[cols, :]) + dom = c.dom + inwindow = [i for (i, r) in enumerate(dom.rational_index) if r in rows] + return (; matrix=c.name, m=resp.m_modes[cols], labels=["$(resp.rational_m_res[r])/$n" for r in rows], m_res=resp.rational_m_res[rows], + C=c.C[rows, cols], sigma=dom.singular_values, U=dom.left_singular_vectors[inwindow, :], + retained=[findfirst(==(dom.rational_index[i]), rows) for i in inwindow], V=dom.right_singular_vectors[cols, :]) end function _plot_coupling_matrix end """ - plot_coupling_matrix(src; n=nothing, save_path=nothing) + plot_coupling_matrix(src; matrix=nothing, n=nothing, save_path=nothing) -Plot the resonant coupling matrix C, the resonant area-weighted field b̄_res at each rational surface per unit applied -harmonic b̃_m, with its singular value decomposition C = U Σ Vᴴ: |C| against surface and m, the left singular vectors -|U| on the same surface axis, the right singular vectors |V| on the same m axis (V₁ is the dominant mode), and the -singular values σ. Surfaces outside the decomposition's core window are shaded. +Plot a coupling matrix C, the response at each rational surface per unit applied harmonic b̃_m (by default the resonant +area-weighted field b̄_res), with its singular value decomposition C = U Σ Vᴴ: |C| against surface and m, the left +singular vectors |U| on the same surface axis, the right singular vectors |V| on the same m axis (V₁ is the dominant +mode), and the singular values σ. Surfaces outside the decomposition's core window are shaded. ### Arguments @@ -516,6 +574,10 @@ singular values σ. Surfaces outside the decomposition's core window are shaded. ### Keyword arguments + - `matrix`: The coupling matrix, a `C_` field of the response without the prefix: `:resonant_area_weighted_field`, + `:resonant_current`, `:island_width_sq`, `:delta_mn`, their `_asymptotic` forms, or `:penetrated_area_weighted_field` + (default: `:resonant_area_weighted_field`, or `:resonant_area_weighted_field_asymptotic` for a response that carries only + the asymptotic set, as a matched one does) - `n`: Toroidal mode number drawn (default: the first) - `save_path`: If given, save the figure to this path (default: `nothing`) @@ -523,9 +585,10 @@ singular values σ. Surfaces outside the decomposition's core window are shaded. A Makie `Figure`. """ -function plot_coupling_matrix(src::Union{PlasmaResponse,PerturbedEquilibriumState}; n=nothing, save_path=nothing) +function plot_coupling_matrix(src::Union{PlasmaResponse,PerturbedEquilibriumState}; matrix::Union{Nothing,Symbol}=nothing, n=nothing, save_path=nothing) _require(plot_coupling_matrix, src) - return _draw(_plot_coupling_matrix, _coupling_matrix_data(src isa PlasmaResponse ? src : src.response, n); save_path) + resp = src isa PlasmaResponse ? src : src.response + return _draw(_plot_coupling_matrix, _coupling_matrix_data(resp, _coupling_svd(resp, matrix, plot_coupling_matrix), n); save_path) end const _PE_SOURCES = (PerturbedEquilibriumState, AbstractString) @@ -537,14 +600,14 @@ register!(plot_island_widths, _PE_SOURCES, (:singular_coupling,), "island half-w register!(plot_chirikov_parameter, _PE_SOURCES, (:singular_coupling,), "effective island-overlap Chirikov parameter per rational surface") register!(plot_driven_delta_mn, _PE_SOURCES, (:singular_coupling,), "forcing-driven Δ_mn per rational surface") register!(plot_mode_spectrogram, _PE_SOURCES, (:response_xi,), "response harmonics against ψ_N (component = :xi_psi, :b_psi, :Jb_theta, :Jb_zeta)") -register!(plot_dominant_mode_surface, (PlasmaResponse, PerturbedEquilibriumState), (:dominant_mode,), - "a dominant resonant-coupling mode as b_n on the control surface") -register!(plot_singular_mode_rz, (PlasmaResponse, PerturbedEquilibriumState), (:dominant_mode,), - "dominant resonant-coupling modes as b_n on the control-surface cross-section") -register!(plot_coupling_matrix, (PlasmaResponse, PerturbedEquilibriumState), (:coupling_matrices, :dominant_mode), - "resonant coupling matrix |C| with its singular values and left and right singular vectors") +register!(plot_dominant_mode_surface, (PlasmaResponse, PerturbedEquilibriumState), (:coupling_matrices,), + "a dominant mode of a coupling matrix as b_n on the control surface (matrix = which C_)") +register!(plot_singular_mode_rz, (PlasmaResponse, PerturbedEquilibriumState), (:coupling_matrices,), + "dominant modes of a coupling matrix as b_n on the control-surface cross-section (matrix = which C_)") +register!(plot_coupling_matrix, (PlasmaResponse, PerturbedEquilibriumState), (:coupling_matrices,), + "a coupling matrix |C| with its singular values and left and right singular vectors (matrix = which C_)") register!(plot_perturbed_field_rz, (PerturbedEquilibriumState,), (:response_n,), "b_n or ξ_n on the poloidal plane (deform = true for the displaced boundary)") register!(plot_effective_islands, (PerturbedEquilibriumState,), (:singular_coupling,), "island chains from the effective resonant flux") -register!(plot_islands, (PerturbedEquilibriumState,), (:penetrated_field,), "island chains from the penetrated field") +register!(plot_islands, (PerturbedEquilibriumState,), (:singular_coupling, :penetrated_field), "island chains from the penetrated field over the effective ones") end # module PerturbedEquilibrium diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index d7075b4b52..9d5b413a11 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -53,10 +53,10 @@ const REASONS = Dict{Symbol,String}( :kinetic_scan => "needs the kinetic singular-surface scan: run with a kinetic source and singfac_min > 0", :ballooning_scan => "needs the ballooning scan: add a [LocalStability] section", :singular_coupling => "needs the singular coupling: run PerturbedEquilibrium with compute_singular_coupling = true", - :response_xi => "needs the reconstructed displacement ξ: run PerturbedEquilibrium on a Forward free-boundary result", - :response_n => "needs the stored normal field and displacement: run PerturbedEquilibrium on a Forward free-boundary result", + :response_xi => "needs the reconstructed displacement ξ: run PerturbedEquilibrium on a free-boundary result", + :response_n => "needs the stored normal field and displacement: run PerturbedEquilibrium on a free-boundary result", :penetrated_field => "needs a penetrated field: ideal runs have none; it comes from a matched (resistive) run", - :response_b => "needs the reconstructed perturbed field b: run PerturbedEquilibrium on a Forward free-boundary result", + :response_b => "needs the reconstructed perturbed field b: run PerturbedEquilibrium on a free-boundary result", :coil_sets => "needs coil forcing: give ForcingTerms coil sets (forcing_data_format = \"coil\")", :forcing_modes => "needs forcing modes: give ForcingTerms a forcing", :ef_sensitivities => "needs the coil sensitivities: add an [ErrorFields] section", @@ -102,7 +102,7 @@ capabilities(r::FT.RMPField) = function capabilities(r::PlasmaResponse) caps = Set{Symbol}() - isempty(r.C_resonant_area_weighted_field) || push!(caps, :coupling_matrices) + isempty(r.C_resonant_area_weighted_field) && isempty(r.C_resonant_area_weighted_field_asymptotic) || push!(caps, :coupling_matrices) isempty(r.dominant_singular_values) || push!(caps, :dominant_mode) return caps end @@ -110,7 +110,7 @@ end # A perturbed equilibrium holds its response's capabilities as well as those of its own drive. function capabilities(s::PerturbedEquilibriumState) caps = capabilities(s.response) - isempty(s.resonant_area_weighted_field) || push!(caps, :singular_coupling) + isempty(s.resonant_area_weighted_field) && isempty(s.resonant_area_weighted_field_asymptotic) || push!(caps, :singular_coupling) s.xi_modes === nothing || push!(caps, :response_xi) s.b_modes === nothing || push!(caps, :response_b) s.b_n_modes === nothing || s.xi_n_modes === nothing || push!(caps, :response_n) @@ -141,7 +141,8 @@ const _H5_CAPABILITIES = ( :delta_ef => "SingularSurfaces/Delta_EF", :kinetic_scan => "SingularSurfaces/Kinetic/scan_psi", :ballooning_scan => "LocalStability/alpha", - :singular_coupling => "PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field", + :singular_coupling => + ("PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field", "PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field_asymptotic"), :response_xi => "PerturbedEquilibrium/Response/xi_psi", :response_b => "PerturbedEquilibrium/Response/b_psi_area_weighted", :ef_sensitivities => EF._H5_GROUP, diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index d2acab8c16..32756ba71a 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -82,8 +82,7 @@ applied root-area-weighted field b̃_x to the resonant response at that surface. `C_` prefix), used for the applied resonant vectors; empty when the coupling was not built. - `C_resonant_area_weighted_field_asymptotic`, `C_resonant_current_asymptotic`, `C_island_width_sq_asymptotic`, `C_delta_mn_asymptotic` - The same four built from the jump of the asymptotic small solution, - −2πi·χ₁·n·q′·(C_R − C_L), in place of the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. The two agree where D_I = −1/4; - elsewhere the finite-width matrices are (1/2 + √−D_I)·w^(√−D_I − 1/2) times these, w being that half-width in ψ_N. + −2πi·χ₁·n·q′·(C_R − C_L), in place of the ∂b^ψ/∂ψ jump across |m − nq| = 5e-4. The two agree where D_I = −1/4. Empty unless the result is single-`n` and carries `Delta_EF`; a `:matched` result takes C_L, C_R from its matched small coefficients `match.small_coefficients`. - `C_coeffs::Matrix{ComplexF64}` - Edge-to-solution coefficients `u_bnd⁻¹·edge_mn` of each unit forcing mode. diff --git a/test/runtests_analysis_plots.jl b/test/runtests_analysis_plots.jl index aca083035f..039fc68d46 100644 --- a/test/runtests_analysis_plots.jl +++ b/test/runtests_analysis_plots.jl @@ -106,6 +106,9 @@ using TOML @test A.capabilities(ret.resp) ⊆ A.capabilities(ret.pe) @test plot_dominant_mode_surface(ret.resp; mode=length(ret.resp.dominant_singular_values)) isa Figure @test_throws "mode must be 1 to" plot_dominant_mode_surface(ret.resp; mode=length(ret.resp.dominant_singular_values) + 1) + # Any coupling matrix the response carries can be decomposed and drawn; other names are refused. + @test A.PerturbedEquilibrium.plot_coupling_matrix(ret.resp; matrix=:resonant_current) isa Figure + @test_throws "matrix must be one of" A.PerturbedEquilibrium.plot_coupling_matrix(ret.resp; matrix=:bogus) @test_throws "coils = true needs" CF.plot_control_surface(ret.resp, ret.resp.dominant_right_singular_vectors[:, 1]; coils=true) # A bare equilibrium marks the q = m/n crossings of n = 1, which include every surface the solve found. bare, solved = A.Equilibrium._surfaces(ret.equil), A.Equilibrium._surfaces(ret.ffs) @@ -142,6 +145,34 @@ using TOML end end + @testset "matched Riccati run draws the asymptotic coupling and both island sets" begin + mktempdir() do dir + ret, h5 = _run_fixture( + dir, + "regression_tj_ideal_example"; + edit=d -> (d["ForceFreeStates"]["integrator"] = "Riccati"; d["Riccati"] = delete!(pop!(d, "Forward"), "renorm_threshold")), + sections=Dict{String,Any}( + "Match" => Dict{String,Any}("eta" => 1e-7, "rho" => 3e-7, "rotation" => 1.0), + "ForcingTerms" => Dict{String,Any}("forcing_data_format" => "coil", "mtheta_coil" => 240, "nzeta_coil" => 32, + "coil_set" => [Dict{String,Any}("name" => "hoop", "source" => "pf_hoop", "radius" => 12.0, "height" => 1.2, + "currents" => [2.0e3], "tiltx" => [3.0])]), + "PerturbedEquilibrium" => Dict{String,Any}("compute_singular_coupling" => true)) + ) + @test ret.ffs.closure === :matched + for x in (ret.resp, ret.pe) + _check_sources(x, h5) + end + caps = A.capabilities(ret.pe) + @test :singular_coupling in caps && :coupling_matrices in caps && :penetrated_field in caps + P = A.PerturbedEquilibrium + # A matched result has only the asymptotic set, the default; asking for the finite-width one names what is missing. + @test_throws "no finite-width resonant coupling" P.plot_resonant_area_weighted_field(ret.pe; asymptotic=false) + @test_throws "no finite-width resonant coupling" P.plot_islands(ret.pe; asymptotic=false) + @test P.plot_coupling_matrix(ret.pe; matrix=:penetrated_area_weighted_field) isa Figure + @test_throws "carries no C_resonant_area_weighted_field" P.plot_coupling_matrix(ret.pe; matrix=:resonant_area_weighted_field) + end + end + @testset "Riccati run offers Δ′ and solution profiles" begin mktempdir() do dir ret, h5 = _run_fixture(dir, "regression_solovev_ideal_example"; diff --git a/test/runtests_dominant_coupling.jl b/test/runtests_dominant_coupling.jl index af9333dc9f..8977dd94c1 100644 --- a/test/runtests_dominant_coupling.jl +++ b/test/runtests_dominant_coupling.jl @@ -194,17 +194,9 @@ include("h5_metadata_check.jl") end end - # With pressure the finite-width jump is (1/2 + α)·w^(α − 1/2) times the asymptotic one, α = √−D_I. + # With pressure the finite-width jump depends on the width and departs from the asymptotic one. mktempdir() do dir - run = riccati_run(dir, 0.1) - resp = run.resp - for row in eachindex(resp.rational_psi) - surf = run.ffs.surfaces[resp.rational_surface_idx[row]] - α = sqrt(-GPEC.LocalStability.mercier_D_I(run.local_stability, surf.psifac)) - w = 5e-4 / abs(resp.rational_n[row] * surf.q1) - ratio = norm(resp.C_delta_mn[row, :]) / norm(resp.C_delta_mn_asymptotic[row, :]) - @test ratio ≈ (0.5 + α) * w^(α - 0.5) rtol = 3e-2 - end + resp = riccati_run(dir, 0.1).resp @test norm(resp.C_delta_mn[1, :]) < 0.9 * norm(resp.C_delta_mn_asymptotic[1, :]) end end From 2bf80d0f42bd9b9552e9e2fa5f269279d6adca9e Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Fri, 13 Nov 2026 16:52:21 +0100 Subject: [PATCH 18/27] ForcingTerms - REFACTOR! - Rename RMPField to ForcingField --- docs/src/api.md | 14 +- docs/src/forcing_terms.md | 2 +- docs/src/perturbed_equilibrium.md | 8 +- src/Analysis/CoilForcing.jl | 22 ++-- src/Analysis/Registry.jl | 6 +- src/Deck.jl | 2 +- src/Display.jl | 16 +-- src/ErrorFields/NTVLimits.jl | 2 +- src/ForcingTerms/ForcingTerms.jl | 124 +++++++++--------- src/GeneralizedPerturbedEquilibrium.jl | 9 +- src/KineticForces/Compute.jl | 2 +- .../PerturbedEquilibrium.jl | 44 +++---- .../PerturbedEquilibriumStructs.jl | 6 +- src/PerturbedEquilibrium/TorqueResponse.jl | 4 +- src/PerturbedEquilibrium/Utils.jl | 2 +- test/runtests_analysis_plots.jl | 6 +- test/runtests_deck_roundtrip.jl | 4 +- test/runtests_solve_api.jl | 74 +++++------ test/runtests_torque_response.jl | 4 +- 19 files changed, 176 insertions(+), 175 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 9423892e7b..efb7c19987 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -10,7 +10,7 @@ eq = PlasmaEquilibrium("input.geqdsk"; jac_type="hamada", kinetic_file="kineti ffs = solve(eq, Forward(); nn=1, delta_mlow=8, delta_mhigh=8, vac_flag=true) # [ForceFreeStates]: Forward, no wall, for the response below ls = solve(LocalStabilityProblem(eq; alpha_boundary_scan=true), Ballooning()) # [LocalStability] resp = plasma_response(ffs; compute_singular_coupling=true) # [PerturbedEquilibrium] -pe = perturbed_equilibrium(resp, RMPField("coils.dat")) # with the [ForcingTerms] drive +pe = perturbed_equilibrium(resp, ForcingField("coils.dat")) # with the [ForcingTerms] drive kf = kinetic_torque(pe, KineticForcesControl()) # [KineticForces] ef = error_fields(resp, pe.coil_sets, ForcingTerms.CoilConfig(ft_ctrl); # [ErrorFields]; ft_ctrl: the [ForcingTerms] control tolerances=ErrorFields.read_tolerance_toml("tolerances.toml")) @@ -29,8 +29,8 @@ foreach(r -> save_to_hdf5("gpec.h5", r), (pe, kf, ef, tear)) | ForceFreeStates | `[ForceFreeStates]` + `[Forward]`, `[Riccati]` or `[Galerkin]` | `solve(ForceBalanceProblem(eq; ...), Forward() \| Riccati() \| Galerkin())` | `ForceFreeStatesResult` | | LocalStability | `[LocalStability]` + `[Ballooning]` | `solve(LocalStabilityProblem(eq; ...), Ballooning(; ...))` | `LocalStabilityResult` | | Match | `[Match]` + `[GGJ]` | `solve(MatchProblem(ffs; ...), GGJModel())` | `ForceFreeStatesResult` with `closure == :matched` | -| Drive | `[ForcingTerms]` | `RMPField(ft_ctrl)` (a `ForcingTermsControl`), `RMPField(file)`, `RMPField(modes)` | `RMPField` | -| PerturbedEquilibrium | `[PerturbedEquilibrium]` | `plasma_response(ffs; ...)`, then `perturbed_equilibrium(resp, rmp; ...)` | `PlasmaResponse`, `PerturbedEquilibriumState` | +| Drive | `[ForcingTerms]` | `ForcingField(ft_ctrl)` (a `ForcingTermsControl`), `ForcingField(file)`, `ForcingField(modes)` | `ForcingField` | +| PerturbedEquilibrium | `[PerturbedEquilibrium]` | `plasma_response(ffs; ...)`, then `perturbed_equilibrium(resp, field; ...)` | `PlasmaResponse`, `PerturbedEquilibriumState` | | KineticForces | `[KineticForces]` | `kinetic_torque(pe, KineticForcesControl(; ...))` | `KineticForcesResult` | | ErrorFields | `[ErrorFields]` | `error_fields(resp, pe.coil_sets, CoilConfig(...); ...)` | `ErrorFieldsResult` | | Tearing | `[Tearing]` + `[SLAYER]` or `[GGJ]` | `solve(TearingProblem(ffs; ...), SLAYERModel() \| GGJModel(); config=TearingConfig(...))` | `TearingResult` | @@ -108,16 +108,16 @@ The `kinetic_file` (and, for HDF5, `kinetic_group`) keyword reads the kinetic pr ## Combining forcing sources -`RMPField`s form a vector space: `+`, `-` and scalar `*` build lazy linear combinations that compute nothing until `perturbed_equilibrium` materializes them, and because the response is linear in the forcing, driving with a combination equals combining the materialized fields; a complex scalar phase-rotates a source. +`ForcingField`s form a vector space: `+`, `-` and scalar `*` build lazy linear combinations that compute nothing until `perturbed_equilibrium` materializes them, and because the response is linear in the forcing, driving with a combination equals combining the materialized fields; a complex scalar phase-rotates a source. ```julia -nominal = RMPField("nominal_efc.dat") -weld_field = RMPField("weld_fields.h5") +nominal = ForcingField("nominal_efc.dat") +weld_field = ForcingField("weld_fields.h5") pe = perturbed_equilibrium(resp, 2.0 * nominal + 0.5 * weld_field) ``` This is the substrate for error-field workflows: build per-unit sources (a coil set per ampere, a displacement field per millimetre), then assemble physical cases by weighting and summing, with one `plasma_response` serving every combination. -`RMPField(modes)` wraps a control-surface spectrum computed elsewhere, in the unit-norm ``\Phi_x`` convention, as a leaf. +`ForcingField(modes)` wraps a control-surface spectrum computed elsewhere, in the unit-norm ``\Phi_x`` convention, as a leaf. The weights are linear-combination coefficients, not physical amplitudes: a coil set with a failed conductor is `nominal - failed_coil`, not `0.9 * nominal`. ## Choosing an integrator diff --git a/docs/src/forcing_terms.md b/docs/src/forcing_terms.md index 8ad9ae5a0f..2cd2ea5915 100644 --- a/docs/src/forcing_terms.md +++ b/docs/src/forcing_terms.md @@ -1,7 +1,7 @@ # Forcing Terms `ForcingTerms` specifies the external magnetic perturbation that drives the perturbed equilibrium: the spectrum of the normal field on the control surface at `psilim`, given either as a file of (m, n) amplitudes or computed by Biot–Savart from coil geometry. -The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs; its result is the `RMPField` that `perturbed_equilibrium` applies to the plasma response. +The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs; its result is the `ForcingField` that `perturbed_equilibrium` applies to the plasma response. ## Normalization diff --git a/docs/src/perturbed_equilibrium.md b/docs/src/perturbed_equilibrium.md index 0d5c2e8e6c..3281d482e4 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -7,7 +7,7 @@ It is the stage that turns a stability calculation into the quantities of error- The force-free states of [Stability](stability.md) give the displacement inside the plasma for any boundary value, and the [Vacuum](vacuum.md) response gives the field outside it. On the control surface at `psilim` the two are joined by requiring continuity of the normal field, which fixes the plasma response to an applied spectrum uniquely ([Park et al. (2007a)](citations.md#PerturbedEquilibrium), [Park et al. (2009)](citations.md#PerturbedEquilibrium)). -`plasma_response(ffs)` builds the operators of that response once, with no reference to a drive; `perturbed_equilibrium(resp, rmp)` applies them to one external field from [Forcing Terms](forcing_terms.md), so a scan over fields reuses one response. +`plasma_response(ffs)` builds the operators of that response once, with no reference to a drive; `perturbed_equilibrium(resp, field)` applies them to one external field from [Forcing Terms](forcing_terms.md), so a scan over fields reuses one response. `compute_perturbed_equilibrium` is the lower-level form of the same call. The resonant part of the response is reported at every rational surface as the singular coupling: the pitch-resonant field and current, the island half-width and the Chirikov overlap parameter. @@ -60,7 +60,7 @@ A kinetic forward solve (`integrator = "Forward"`, `kinetic = "KineticForces"`) With `compute_torque_response = true`, `plasma_response` refers that quadratic form back to the applied root-area-weighted field ``\tilde b`` and stores it at every node as the torque response matrix ``T_{xe}(\psi)``, cumulative in ψ, under `PerturbedEquilibrium/TorqueResponse/`; it is the `T_xe` of the Fortran GPEC, in the basis of the stored response matrices, in N·m/T². ``T_{xe}`` is built on the ``+n`` harmonic alone and is therefore twice the physical value, so the cumulative complex torque of an applied spectrum is ``T(\psi) = \tilde b^\dagger T_{xe}(\psi)\, \tilde b / 2`` (`torque_profile` applies the 1/2), with ``\operatorname{Re} T`` the toroidal torque inside ψ, equal to `Energies/toroidal_torque` at the control surface, and ``\operatorname{Im} T = 2n\,\delta W``. Only the Hermitian part ``(T_{xe} + T_{xe}^\dagger)/2`` contributes to the torque; its eigenvectors are the applied spectra of extremal torque, and the anti-Hermitian part carries the energy. -Each `perturbed_equilibrium(resp, rmp)` call contracts ``T_{xe}`` with its field into a `TorqueResponse`: the applied torque ``T_\mathrm{applied}`` and the source form ``T_\mathrm{source} = M^\dagger T M`` with one column of ``M`` per forcing source, so that driving the sources at scale factors ``s`` gives ``s^\dagger T_\mathrm{source}\, s / 2``. +Each `perturbed_equilibrium(resp, field)` call contracts ``T_{xe}`` with its field into a `TorqueResponse`: the applied torque ``T_\mathrm{applied}`` and the source form ``T_\mathrm{source} = M^\dagger T M`` with one column of ``M`` per forcing source, so that driving the sources at scale factors ``s`` gives ``s^\dagger T_\mathrm{source}\, s / 2``. ## Governing equations @@ -116,11 +116,11 @@ In a script the same two steps are using GeneralizedPerturbedEquilibrium resp = plasma_response(ffs; compute_singular_coupling=true) -pe = perturbed_equilibrium(resp, rmp; regularization_width=0.05) # rmp: an RMPField, see the Scripting API +pe = perturbed_equilibrium(resp, field; regularization_width=0.05) # field: a ForcingField, see the Scripting API save_to_hdf5("gpec.h5", pe) ``` -with the `RMPField` built from coils or a file as on the [Scripting API](api.md) page; computing the response does not write a file. +with the `ForcingField` built from coils or a file as on the [Scripting API](api.md) page; computing the response does not write a file. ## Outputs diff --git a/src/Analysis/CoilForcing.jl b/src/Analysis/CoilForcing.jl index 353a562782..e3a0c5ec08 100644 --- a/src/Analysis/CoilForcing.jl +++ b/src/Analysis/CoilForcing.jl @@ -232,12 +232,12 @@ function plot_coil_geometry_3d(pe::PerturbedEquilibriumState; save_path=nothing) return plot_coil_geometry_3d(pe.coil_sets; equil=pe.response.ffs.equil, save_path) end -# The coil sets of every coil term of `rmp`, each set's currents scaled by its term's weight (by the weight's magnitude +# The coil sets of every coil term of `field`, each set's currents scaled by its term's weight (by the weight's magnitude # when it is complex, which shifts the toroidal phase), with the number of terms that have no geometry. -function _rmp_coil_sets(rmp::FT.RMPField; n=1) +function _field_coil_sets(field::FT.ForcingField; n=1) sets, skipped, complex_weight = FT.CoilSet[], 0, false - for t in FT._rmp_terms(rmp) - if !(t isa FT.RMPSource && t.ctrl.forcing_data_format == "coil") + for t in FT._field_terms(field) + if !(t isa FT.ForcingSource && t.ctrl.forcing_data_format == "coil") skipped += 1 continue end @@ -251,15 +251,15 @@ function _rmp_coil_sets(rmp::FT.RMPField; n=1) end """ - plot_sources(rmp; n=1, color=:current, save_path=nothing) + plot_sources(field; n=1, color=:current, save_path=nothing) -Plot the coils of an `RMPField` in 3D at equal data aspect, with no plasma: every coil term of a sum together, each +Plot the coils of a `ForcingField` in 3D at equal data aspect, with no plasma: every coil term of a sum together, each term's currents scaled by its weight. Mode-table and spectrum terms have no geometry and are counted in the title. Use GLMakie to rotate it. ### Arguments - - `rmp`: An `RMPField` with at least one coil term + - `field`: A `ForcingField` with at least one coil term ### Keyword arguments @@ -271,10 +271,10 @@ GLMakie to rotate it. A Makie `Figure`. """ -function plot_sources(rmp::FT.RMPField; n::Int=1, color::Symbol=:current, save_path=nothing) - _require(plot_sources, rmp) +function plot_sources(field::FT.ForcingField; n::Int=1, color::Symbol=:current, save_path=nothing) + _require(plot_sources, field) color in (:current, :set) || throw(ArgumentError("plot_sources: color must be :current or :set")) - d = _rmp_coil_sets(rmp; n) + d = _field_coil_sets(field; n) notes = String[] d.skipped > 0 && push!(notes, "$(d.skipped) mode-table term$(d.skipped == 1 ? "" : "s") not drawn") d.complex_weight && push!(notes, "complex weights drawn at their magnitude") @@ -463,7 +463,7 @@ register!(plot_bn_contour, (PerturbedEquilibriumState,), (:forcing_modes,), "app register!(plot_coil_geometry_3d, (PerturbedEquilibriumState,), (:coil_sets,), "3D coils and plasma boundary") register!(plot_coil_geometry_rz, (PerturbedEquilibriumState,), (:coil_sets,), "coils over the plasma boundary in (R, Z)") register!(plot_mode_spectrum, (PerturbedEquilibriumState,), (:forcing_modes,), "|Φ_x(m, n)| forcing spectrum") -register!(plot_sources, (FT.RMPField,), (:coil_source,), "the coil sources in 3D, coloured by current or by set") +register!(plot_sources, (FT.ForcingField,), (:coil_source,), "the coil sources in 3D, coloured by current or by set") export plot_coil_geometry_3d, plot_coil_geometry_rz export plot_bn_contour, plot_mode_spectrum, plot_control_surface, plot_sources diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index 9d5b413a11..e582c7c725 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -61,7 +61,7 @@ const REASONS = Dict{Symbol,String}( :forcing_modes => "needs forcing modes: give ForcingTerms a forcing", :ef_sensitivities => "needs the coil sensitivities: add an [ErrorFields] section", :dominant_mode => "needs the dominant resonant-coupling mode: run PerturbedEquilibrium with compute_singular_coupling = true", - :coil_source => "needs a coil source: give RMPField coil sets (a mode table or spectrum has no geometry to draw)", + :coil_source => "needs a coil source: give ForcingField coil sets (a mode table or spectrum has no geometry to draw)", :coupling_matrices => "needs the resonant coupling matrices: run plasma_response with compute_singular_coupling = true", :ef_monte_carlo => "needs the tolerance Monte Carlo: give ErrorFields a tolerance file", :ef_risk => "needs the locking risk: give ErrorFields a tolerance file and a scenario", @@ -97,8 +97,8 @@ end capabilities(r::LocalStabilityResult) = isempty(r.alpha) ? Set{Symbol}() : Set([:ballooning_scan]) -capabilities(r::FT.RMPField) = - any(t -> t isa FT.RMPSource && t.ctrl.forcing_data_format == "coil", FT._rmp_terms(r)) ? Set([:coil_source]) : Set{Symbol}() +capabilities(r::FT.ForcingField) = + any(t -> t isa FT.ForcingSource && t.ctrl.forcing_data_format == "coil", FT._field_terms(r)) ? Set([:coil_source]) : Set{Symbol}() function capabilities(r::PlasmaResponse) caps = Set{Symbol}() diff --git a/src/Deck.jl b/src/Deck.jl index 7ca0363600..4d2d347fd2 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -661,7 +661,7 @@ function deck_sections(pe::PerturbedEquilibrium.PerturbedEquilibriumState) sections = Dict{String,Any}("PerturbedEquilibrium" => table) forcing === nothing && return sections sections["ForcingTerms"] = - forcing isa ForcingTerms.RMPSource && forcing.scale == 1 ? _forcing_table(forcing.ctrl) : + forcing isa ForcingTerms.ForcingSource && forcing.scale == 1 ? _forcing_table(forcing.ctrl) : Dict{String,Any}("forcing_data_format" => "hdf5", "forcing_data_file" => _RECORDED_FORCING) return sections end diff --git a/src/Display.jl b/src/Display.jl index b08730f555..7c0df7ac67 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -11,7 +11,7 @@ using .PerturbedEquilibrium: PerturbedEquilibriumState using .KineticForces: MethodResult, KineticForcesState using .ErrorFields: MonteCarloResult, RiskResult, EFCCoupling using .Tearing: GrowthRateResult -using .ForcingTerms: RMPSource, RMPSpectrum, RMPFieldSum +using .ForcingTerms: ForcingSource, ForcingSpectrum, ForcingFieldSum _fmt(x::Real) = @sprintf("%.4g", x) _fmt(::Nothing) = "—" @@ -292,21 +292,21 @@ end _weight(w) = string(iszero(real(w)) && !iszero(imag(w)) ? _fmt(imag(w)) * "im" : _fmt(w), " × ") -function _rmp_label(f::RMPSource) +function _field_label(f::ForcingSource) c = f.ctrl c.forcing_data_format == "coil" || return string(basename(c.forcing_data_file), " (", c.forcing_data_format, ")") sets = [isempty(get(d, "name", "")) ? get(d, "source", "coil set") : d["name"] for d in c.coil_sets_raw] return string(isempty(c.machine) ? "" : c.machine * " ", "coils ", _list(sets)) end -_rmp_label(f::RMPSpectrum) = string("spectrum of ", _plural(length(f.modes), "mode"), ", n = ", _irange([m.n for m in f.modes])) +_field_label(f::ForcingSpectrum) = string("spectrum of ", _plural(length(f.modes), "mode"), ", n = ", _irange([m.n for m in f.modes])) -Base.show(io::IO, f::Union{RMPSource,RMPSpectrum}) = print(io, "RMPField(", f.scale == 1 ? "" : _weight(f.scale), _rmp_label(f), ")") -Base.show(io::IO, f::RMPFieldSum) = print(io, "RMPField(sum of ", _plural(length(f.terms), "term"), ")") +Base.show(io::IO, f::Union{ForcingSource,ForcingSpectrum}) = print(io, "ForcingField(", f.scale == 1 ? "" : _weight(f.scale), _field_label(f), ")") +Base.show(io::IO, f::ForcingFieldSum) = print(io, "ForcingField(sum of ", _plural(length(f.terms), "term"), ")") -function Base.show(io::IO, ::MIME"text/plain", f::RMPFieldSum) - print(io, "RMPField sum of ", _plural(length(f.terms), "term")) +function Base.show(io::IO, ::MIME"text/plain", f::ForcingFieldSum) + print(io, "ForcingField sum of ", _plural(length(f.terms), "term")) for t in f.terms - print(io, "\n ", _weight(t.scale), _rmp_label(t)) + print(io, "\n ", _weight(t.scale), _field_label(t)) end return nothing end diff --git a/src/ErrorFields/NTVLimits.jl b/src/ErrorFields/NTVLimits.jl index 21d700914d..c3b10d9ebd 100644 --- a/src/ErrorFields/NTVLimits.jl +++ b/src/ErrorFields/NTVLimits.jl @@ -550,7 +550,7 @@ function efc_couplings( "scan ±$(@sprintf("%.3e", span)) rad/s on $(length(grid0)) initial points (max $(scan_max_points))" function response_of(modes::Vector{ForcingMode}) - pe_state = PerturbedEquilibrium.compute_perturbed_equilibrium(resp, ForcingTerms.RMPField(modes); regularization_width, verbose) + pe_state = PerturbedEquilibrium.compute_perturbed_equilibrium(resp, ForcingTerms.ForcingField(modes); regularization_width, verbose) kf_intr = KineticForces.KineticForcesInternal(equil; verbose=verbose) KineticForces.set_perturbation_data!(kf_intr, pe_state, ffs, equil, ffs.metric) return kf_intr diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index c8ee6eab05..bb827c1c43 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -253,7 +253,7 @@ function load_forcing_from_h5_group!(forcing_modes::Vector{ForcingMode}, group): end """ - RMPField + ForcingField Abstract supertype of every external-forcing description the scripting API accepts: a resonant-magnetic-perturbation field, described by where it comes from and how strongly it @@ -261,30 +261,30 @@ drives (a forcing-mode file, a coil set with currents, or a precomputed spectrum Construction checks the description and throws an `ArgumentError` naming the problem: a forcing file must exist and parse as a mode table with a known normalization, and every coil set must resolve to geometry and carry currents. The -modes are materialized against an equilibrium only when the perturbed-equilibrium stage runs, so one `RMPField` can +modes are materialized against an equilibrium only when the perturbed-equilibrium stage runs, so one `ForcingField` can drive several solves. ## Construction - RMPField(path; format=..., scale=1.0, kwargs...) - RMPField(coil_sets; scale=1.0, kwargs...) - RMPField(ctrl::ForcingTermsControl; scale=1.0) - RMPField(modes::Vector{ForcingMode}; scale=1.0) + ForcingField(path; format=..., scale=1.0, kwargs...) + ForcingField(coil_sets; scale=1.0, kwargs...) + ForcingField(ctrl::ForcingTermsControl; scale=1.0) + ForcingField(modes::Vector{ForcingMode}; scale=1.0) The first form points at a forcing-mode file, `format` defaulting to `"hdf5"` for an `.h5` or `.hdf5` extension and `"ascii"` otherwise. The second form takes one coil set or a vector of them, each a NamedTuple or Dict with the `[[ForcingTerms.coil_set]]` keys, and selects the coil format: ```julia -RMPField((name="c", currents=[1e3, 500, -500, -1e3, -500, 500]); machine="d3d") # the DIII-D C-coil, in amperes -RMPField([(name="iu", currents=iu), (name="il", currents=il)]; machine="d3d") -RMPField((source="pf_hoop", radius=12.0, height=1.2, currents=[2e3])) +ForcingField((name="c", currents=[1e3, 500, -500, -1e3, -500, 500]); machine="d3d") # the DIII-D C-coil, in amperes +ForcingField([(name="iu", currents=iu), (name="il", currents=il)]; machine="d3d") +ForcingField((source="pf_hoop", radius=12.0, height=1.2, currents=[2e3])) ``` Remaining `kwargs` are [`ForcingTermsControl`](@ref) fields. These three return a single-source leaf -([`RMPSource`](@ref)). The last form takes a control-surface spectrum computed elsewhere, already in -the unit-norm `Φ_x` convention, and returns a spectrum-literal leaf ([`RMPSpectrum`](@ref)). +([`ForcingSource`](@ref)). The last form takes a control-surface spectrum computed elsewhere, already in +the unit-norm `Φ_x` convention, and returns a spectrum-literal leaf ([`ForcingSpectrum`](@ref)). ## Algebra @@ -293,8 +293,8 @@ perturbation) build lazy linear combinations. The response is linear in the forc is materialized on the control surface and the mode amplitudes are summed. ```julia -nominal = RMPField("nominal_efc.dat") -weld_field = RMPField("weld_fields.h5"; scale=0.5) +nominal = ForcingField("nominal_efc.dat") +weld_field = ForcingField("weld_fields.h5"; scale=0.5) total = 2.0 * nominal + weld_field # lazy: records terms and weights, computes nothing pe = perturbed_equilibrium(plasma_response(ffs), total) # materializes each term, sums, drives PE ``` @@ -305,55 +305,55 @@ in a linear combination, applied uniformly to the materialized spectrum of every A source that is not a scalar multiple of another needs its own description: a coil set with a failed conductor is `nominal - failed_coil`, not `0.9 * nominal`. """ -abstract type RMPField end +abstract type ForcingField end """ - RMPSource + ForcingSource -A single-source [`RMPField`](@ref) leaf: one forcing description plus a complex weight. -Built by the `RMPField` constructors; scalar multiplication rescales the weight. +A single-source [`ForcingField`](@ref) leaf: one forcing description plus a complex weight. +Built by the `ForcingField` constructors; scalar multiplication rescales the weight. ## Fields - `ctrl::ForcingTermsControl` - The forcing source: format, file path or machine, and the raw coil-set blocks. - `scale::ComplexF64` - The source's weight in a linear combination, applied to the materialized control-surface spectrum (complex = phase rotation). Not a physical amplitude. """ -struct RMPSource <: RMPField +struct ForcingSource <: ForcingField ctrl::ForcingTermsControl scale::ComplexF64 end """ - RMPSpectrum + ForcingSpectrum -A spectrum-literal [`RMPField`](@ref) leaf: control-surface forcing modes computed elsewhere, in the +A spectrum-literal [`ForcingField`](@ref) leaf: control-surface forcing modes computed elsewhere, in the unit-norm `Φ_x` convention the response consumes, plus a complex weight. Built by -`RMPField(modes::Vector{ForcingMode})`; scalar multiplication rescales the weight. +`ForcingField(modes::Vector{ForcingMode})`; scalar multiplication rescales the weight. ## Fields - `modes::Vector{ForcingMode}` - The control-surface spectrum, copied at construction. - - `scale::ComplexF64` - The leaf's weight in a linear combination, as for [`RMPSource`](@ref). + - `scale::ComplexF64` - The leaf's weight in a linear combination, as for [`ForcingSource`](@ref). """ -struct RMPSpectrum <: RMPField +struct ForcingSpectrum <: ForcingField modes::Vector{ForcingMode} scale::ComplexF64 end """ - RMPFieldSum + ForcingFieldSum -A lazy linear combination of [`RMPSource`](@ref) and [`RMPSpectrum`](@ref) leaves, built by `+`/`-` on -[`RMPField`](@ref)s. Holds the flattened term list; scalar multiplication distributes onto +A lazy linear combination of [`ForcingSource`](@ref) and [`ForcingSpectrum`](@ref) leaves, built by `+`/`-` on +[`ForcingField`](@ref)s. Holds the flattened term list; scalar multiplication distributes onto the leaves. Materialization evaluates each term against the equilibrium and sums the mode amplitudes — valid because the perturbed-equilibrium response is linear in the forcing. ## Fields - - `terms::Vector{Union{RMPSource,RMPSpectrum}}` - The flattened weighted leaves. + - `terms::Vector{Union{ForcingSource,ForcingSpectrum}}` - The flattened weighted leaves. """ -struct RMPFieldSum <: RMPField - terms::Vector{Union{RMPSource,RMPSpectrum}} +struct ForcingFieldSum <: ForcingField + terms::Vector{Union{ForcingSource,ForcingSpectrum}} end """ @@ -368,32 +368,32 @@ const _NORMALIZATIONS = ("normal_field_T", "sfl_flux_Wb", "unit_flux") # Read a forcing-mode file now, so a missing or malformed file fails when the source is built. function _check_forcing_file(ctrl::ForcingTermsControl) path = ctrl.forcing_data_file - isfile(path) || throw(ArgumentError("RMPField: no forcing file at $path")) + isfile(path) || throw(ArgumentError("ForcingField: no forcing file at $path")) modes = ForcingMode[] tag = try load_forcing_data!(modes, path, ctrl.forcing_data_format) catch err throw( ArgumentError( - "RMPField: $path is not a forcing-mode table (format $(ctrl.forcing_data_format)): $(sprint(showerror, err)). " * + "ForcingField: $path is not a forcing-mode table (format $(ctrl.forcing_data_format)): $(sprint(showerror, err)). " * "A mode table holds rows of n, m, Re, Im (see `load_forcing_data!`); a coil geometry file goes in a coil set, " * - "as in RMPField((name=\"set\", dat_file=path, currents=[...]))." + "as in ForcingField((name=\"set\", dat_file=path, currents=[...]))." ) ) end - isempty(modes) && throw(ArgumentError("RMPField: $path holds no forcing modes")) - tag in _NORMALIZATIONS || throw(ArgumentError("RMPField: $path declares normalization \"$tag\"; use one of $(join(_NORMALIZATIONS, ", "))")) + isempty(modes) && throw(ArgumentError("ForcingField: $path holds no forcing modes")) + tag in _NORMALIZATIONS || throw(ArgumentError("ForcingField: $path declares normalization \"$tag\"; use one of $(join(_NORMALIZATIONS, ", "))")) return nothing end # Resolve every coil set now, so an unknown key, a missing geometry file or a missing current fails when the source is # built; window-pane sets placed by standoff need the plasma surface and are resolved when materialized. function _check_coil_sets(ctrl::ForcingTermsControl) - isempty(ctrl.coil_sets_raw) && throw(ArgumentError("RMPField: a coil source needs at least one coil set")) + isempty(ctrl.coil_sets_raw) && throw(ArgumentError("ForcingField: a coil source needs at least one coil set")) cfg = CoilConfig(ctrl) for sc in cfg.coil_sets label = isempty(sc.name) ? "a coil set" : "coil set \"$(sc.name)\"" - all(iszero, sc.currents) && throw(ArgumentError("RMPField: $label has no currents; give `currents` in amperes, one per conductor")) + all(iszero, sc.currents) && throw(ArgumentError("ForcingField: $label has no currents; give `currents` in amperes, one per conductor")) isnan(sc.standoff) || continue cs = try _build_raw_coil_set(cfg, sc) @@ -401,53 +401,53 @@ function _check_coil_sets(ctrl::ForcingTermsControl) hint = isempty(cfg.machine) && sc.source in ("", "file") && isempty(sc.dat_file) && isempty(sc.h5_file) ? " (a named set is read from _.dat: pass machine=\"d3d\", say, or give a dat_file)" : "" - throw(ArgumentError("RMPField: $label: $(sprint(showerror, err))$hint")) + throw(ArgumentError("ForcingField: $label: $(sprint(showerror, err))$hint")) end length(sc.currents) > cs.ncoil && - throw(ArgumentError("RMPField: $label has $(length(sc.currents)) currents for its $(cs.ncoil) conductors")) + throw(ArgumentError("ForcingField: $label has $(length(sc.currents)) currents for its $(cs.ncoil) conductors")) end return nothing end -function RMPField(ctrl::ForcingTermsControl; scale::Number=1.0) +function ForcingField(ctrl::ForcingTermsControl; scale::Number=1.0) fmt = ctrl.forcing_data_format fmt == "coil" ? _check_coil_sets(ctrl) : fmt in ("ascii", "hdf5") ? _check_forcing_file(ctrl) : - throw(ArgumentError("RMPField: forcing_data_format \"$fmt\" is not \"ascii\", \"hdf5\" or \"coil\"")) - return RMPSource(ctrl, ComplexF64(scale)) + throw(ArgumentError("ForcingField: forcing_data_format \"$fmt\" is not \"ascii\", \"hdf5\" or \"coil\"")) + return ForcingSource(ctrl, ComplexF64(scale)) end -RMPField(path::AbstractString; format::String=_infer_format(path), scale::Number=1.0, kwargs...) = - RMPField(ForcingTermsControl(; forcing_data_file=abspath(path), forcing_data_format=format, kwargs...); scale) +ForcingField(path::AbstractString; format::String=_infer_format(path), scale::Number=1.0, kwargs...) = + ForcingField(ForcingTermsControl(; forcing_data_file=abspath(path), forcing_data_format=format, kwargs...); scale) # A coil set as the [[ForcingTerms.coil_set]] table: a Dict or NamedTuple, keys as strings or symbols. _coil_dict(d::AbstractDict) = Dict{String,Any}(string(k) => v for (k, v) in d) _coil_dict(nt::NamedTuple) = Dict{String,Any}(string(k) => v for (k, v) in pairs(nt)) -_coil_dict(x) = throw(ArgumentError("RMPField: a coil set is a Dict or NamedTuple of [[ForcingTerms.coil_set]] keys, not a $(typeof(x))")) +_coil_dict(x) = throw(ArgumentError("ForcingField: a coil set is a Dict or NamedTuple of [[ForcingTerms.coil_set]] keys, not a $(typeof(x))")) -RMPField(coil_sets::AbstractVector; scale::Number=1.0, kwargs...) = - RMPField(ForcingTermsControl(; forcing_data_format="coil", coil_sets_raw=_coil_dict.(coil_sets), kwargs...); scale) -RMPField(coil_set::Union{AbstractDict,NamedTuple}; kwargs...) = RMPField([coil_set]; kwargs...) +ForcingField(coil_sets::AbstractVector; scale::Number=1.0, kwargs...) = + ForcingField(ForcingTermsControl(; forcing_data_format="coil", coil_sets_raw=_coil_dict.(coil_sets), kwargs...); scale) +ForcingField(coil_set::Union{AbstractDict,NamedTuple}; kwargs...) = ForcingField([coil_set]; kwargs...) -function RMPField(modes::Vector{ForcingMode}; scale::Number=1.0) - isempty(modes) && throw(ArgumentError("RMPField: a spectrum needs at least one forcing mode")) - all(m -> isfinite(m.amplitude), modes) || throw(ArgumentError("RMPField: a spectrum amplitude is not finite")) - return RMPSpectrum([ForcingMode(; n=mode.n, m=mode.m, amplitude=mode.amplitude) for mode in modes], ComplexF64(scale)) +function ForcingField(modes::Vector{ForcingMode}; scale::Number=1.0) + isempty(modes) && throw(ArgumentError("ForcingField: a spectrum needs at least one forcing mode")) + all(m -> isfinite(m.amplitude), modes) || throw(ArgumentError("ForcingField: a spectrum amplitude is not finite")) + return ForcingSpectrum([ForcingMode(; n=mode.n, m=mode.m, amplitude=mode.amplitude) for mode in modes], ComplexF64(scale)) end """ -Flattened weighted-leaf list of any [`RMPField`](@ref). +Flattened weighted-leaf list of any [`ForcingField`](@ref). """ -_rmp_terms(f::Union{RMPSource,RMPSpectrum}) = Union{RMPSource,RMPSpectrum}[f] -_rmp_terms(f::RMPFieldSum) = f.terms +_field_terms(f::Union{ForcingSource,ForcingSpectrum}) = Union{ForcingSource,ForcingSpectrum}[f] +_field_terms(f::ForcingFieldSum) = f.terms -Base.:+(a::RMPField, b::RMPField) = RMPFieldSum(vcat(_rmp_terms(a), _rmp_terms(b))) -Base.:-(a::RMPField) = -1 * a -Base.:-(a::RMPField, b::RMPField) = a + (-1 * b) -Base.:*(c::Number, f::RMPSource) = RMPSource(f.ctrl, ComplexF64(c) * f.scale) -Base.:*(c::Number, f::RMPSpectrum) = RMPSpectrum(f.modes, ComplexF64(c) * f.scale) -Base.:*(c::Number, f::RMPFieldSum) = RMPFieldSum([c * t for t in f.terms]) -Base.:*(f::RMPField, c::Number) = c * f +Base.:+(a::ForcingField, b::ForcingField) = ForcingFieldSum(vcat(_field_terms(a), _field_terms(b))) +Base.:-(a::ForcingField) = -1 * a +Base.:-(a::ForcingField, b::ForcingField) = a + (-1 * b) +Base.:*(c::Number, f::ForcingSource) = ForcingSource(f.ctrl, ComplexF64(c) * f.scale) +Base.:*(c::Number, f::ForcingSpectrum) = ForcingSpectrum(f.modes, ComplexF64(c) * f.scale) +Base.:*(c::Number, f::ForcingFieldSum) = ForcingFieldSum([c * t for t in f.terms]) +Base.:*(f::ForcingField, c::Number) = c * f """ snapshot_forcing_modes(ft_ctrl; verbose=false) -> Union{Nothing,Tuple{Vector{ForcingMode},String}} @@ -465,6 +465,6 @@ function snapshot_forcing_modes(ft_ctrl::ForcingTermsControl; verbose::Bool=fals end -export ForcingTermsControl, ForcingMode, RMPField, load_forcing_data!, save_forcing_to_h5, load_forcing_from_h5_group! +export ForcingTermsControl, ForcingMode, ForcingField, load_forcing_data!, save_forcing_to_h5, load_forcing_from_h5_group! end # module ForcingTerms diff --git a/src/GeneralizedPerturbedEquilibrium.jl b/src/GeneralizedPerturbedEquilibrium.jl index 9cc367e474..62a2709c5a 100755 --- a/src/GeneralizedPerturbedEquilibrium.jl +++ b/src/GeneralizedPerturbedEquilibrium.jl @@ -77,7 +77,7 @@ using .InnerLayer: GGJModel, CCCModel, SLAYERModel using .Tearing: TearingProblem, TearingConfig, TearingResult, CriticalResonantFieldControl using .LocalStability: LocalStabilityProblem, Ballooning, LocalStabilityResult using .Equilibrium: PlasmaEquilibrium, KineticProfileData, IonSpecies, attach_kinetic_profiles! -using .ForcingTerms: RMPField +using .ForcingTerms: ForcingField using .PerturbedEquilibrium: plasma_response, perturbed_equilibrium, PlasmaResponse using .KineticForces: kinetic_torque, KineticForcesControl, KineticForcesResult using .ErrorFields: error_fields, ErrorFieldsResult @@ -199,8 +199,8 @@ function main_from_inputs( if deck.perturbed_equilibrium !== nothing pe = _timed_stage(runtimes, "perturbed_equilibrium", "Perturbed Equilibrium") do # A replay from stored coil geometry skips the source checks: the geometry files they read may be gone. - rmp = preloaded_coil_sets === nothing ? RMPField(deck.forcing) : ForcingTerms.RMPSource(deck.forcing, 1) - perturbed_equilibrium(plasma_response(ffs; verbose, deck.perturbed_equilibrium.response...), rmp; + field = preloaded_coil_sets === nothing ? ForcingField(deck.forcing) : ForcingTerms.ForcingSource(deck.forcing, 1) + perturbed_equilibrium(plasma_response(ffs; verbose, deck.perturbed_equilibrium.response...), field; coil_sets=preloaded_coil_sets, verbose, deck.perturbed_equilibrium.drive...) end resp = pe.response @@ -312,7 +312,8 @@ end export main, write_imas export solve, plasma_response, perturbed_equilibrium, kinetic_torque, error_fields export KineticProfileData, IonSpecies, attach_kinetic_profiles! -export PlasmaEquilibrium, ForceBalanceProblem, Forward, Riccati, Galerkin, TestKineticMatrices, KineticMatrices, kinetic_matrices, ForceFreeStatesResult, RMPField, PlasmaResponse +export PlasmaEquilibrium, + ForceBalanceProblem, Forward, Riccati, Galerkin, TestKineticMatrices, KineticMatrices, kinetic_matrices, ForceFreeStatesResult, ForcingField, PlasmaResponse export MatchProblem, TearingProblem, TearingConfig, TearingResult, GGJModel, CCCModel, SLAYERModel export LocalStabilityProblem, Ballooning, LocalStabilityResult export KineticForcesControl, KineticForcesResult, ErrorFieldsResult diff --git a/src/KineticForces/Compute.jl b/src/KineticForces/Compute.jl index c639d7a049..4cb8abda1c 100644 --- a/src/KineticForces/Compute.jl +++ b/src/KineticForces/Compute.jl @@ -458,7 +458,7 @@ kinetic profiles attached to its equilibrium. A multi-species plasma adds each s Call `save_to_hdf5(target, kf)` to save the result. ```julia -pe = perturbed_equilibrium(plasma_response(ffs), RMPField("forcing.dat")) +pe = perturbed_equilibrium(plasma_response(ffs), ForcingField("forcing.dat")) kf = kinetic_torque(pe, KineticForcesControl()) ``` """ diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 3274b1e688..5c83824f0c 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -48,7 +48,7 @@ control-surface response operators (inductances, permeability, reluctance; Park Plasmas 14, 052110 (2007)) and, with `compute_singular_coupling`, the singular-coupling matrices and their dominant modes (Park, Phys. Plasmas 16, 056115 (2009)), and with `compute_torque_response` the ψ-resolved torque response `T_xe` of a single-`n` forward kinetic solve. Apply it to an external field -with `perturbed_equilibrium(resp, rmp)` as many times as needed. +with `perturbed_equilibrium(resp, field)` as many times as needed. A result without a ξ solution leaves the operators empty: the step warns and is skipped. A result without the free-boundary δW is an error (it needs `vac_flag`, and for Galerkin also `error_field_response`), and so is @@ -87,11 +87,11 @@ function plasma_response(ffs::ForceFreeStatesResult; compute_singular_coupling:: end """ - perturbed_equilibrium(resp, rmp; regularization_width=0.0, verbose=false, coil_sets=nothing) + perturbed_equilibrium(resp, field; regularization_width=0.0, verbose=false, coil_sets=nothing) -> PerturbedEquilibriumState -Drive the plasma response `resp` (from [`plasma_response`](@ref)) with the external field `rmp`, an -[`RMPField`](@ref GeneralizedPerturbedEquilibrium.ForcingTerms.RMPField), and return the perturbed-equilibrium result. One response serves any number of +Drive the plasma response `resp` (from [`plasma_response`](@ref)) with the external field `field`, an +[`ForcingField`](@ref GeneralizedPerturbedEquilibrium.ForcingTerms.ForcingField), and return the perturbed-equilibrium result. One response serves any number of fields, so a scan rebuilds no operator. `regularization_width` smooths the ideal 1/(m−nq) divergence in the profile reconstruction (Fortran @@ -100,19 +100,19 @@ Call `save_to_hdf5(target, pe)` to save the result. `coil_sets` injects already- ```julia resp = plasma_response(ffs) -pe = perturbed_equilibrium(resp, RMPField("forcing.dat")) +pe = perturbed_equilibrium(resp, ForcingField("forcing.dat")) ``` """ function perturbed_equilibrium( resp::PlasmaResponse, - rmp::ForcingTerms.RMPField; + field::ForcingTerms.ForcingField; regularization_width::Real=0.0, verbose::Bool=false, coil_sets::Union{Nothing,Vector{CoilSet}}=nothing ) # Injected coil geometry (gpec.h5 replay with `--coil-source coils`) lets the coil field # be recomputed from stored geometry without the .dat/.h5 files. - pe_state = compute_perturbed_equilibrium(resp, rmp; regularization_width, verbose, + pe_state = compute_perturbed_equilibrium(resp, field; regularization_width, verbose, preloaded_coil_sets=coil_sets === nothing ? CoilSet[] : copy(coil_sets)) return pe_state @@ -123,7 +123,7 @@ end preloaded_coil_sets=CoilSet[])::PerturbedEquilibriumState Drive the operators of `resp` with one external field: materialize `forcing` (a `ForcingTermsControl` -or any [`ForcingTerms.RMPField`](@ref)) on the control surface, then apply the response and the +or any [`ForcingTerms.ForcingField`](@ref)) on the control surface, then apply the response and the singular coupling to it, reconstruct the perturbed profiles, and contract any torque response with the forcing sources. Steps whose operators `resp` does not carry are skipped, leaving only the forcing spectrum. @@ -136,14 +136,14 @@ forcing spectrum. """ function compute_perturbed_equilibrium( resp::PlasmaResponse, - forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.RMPField}; + forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.ForcingField}; regularization_width::Real=0.0, verbose::Bool=true, preloaded_coil_sets::Vector{CoilSet}=CoilSet[] )::PerturbedEquilibriumState ffs = resp.ffs modes, coil_sets = materialize_forcing_modes(ffs, forcing; preloaded_coil_sets, verbose) - state = PerturbedEquilibriumState(; response=resp, forcing=forcing isa ForcingTerms.RMPField ? forcing : ForcingTerms.RMPField(forcing), + state = PerturbedEquilibriumState(; response=resp, forcing=forcing isa ForcingTerms.ForcingField ? forcing : ForcingTerms.ForcingField(forcing), forcing_modes=modes, coil_sets=isempty(coil_sets) ? preloaded_coil_sets : coil_sets, regularization_width=Float64(regularization_width)) @@ -207,42 +207,42 @@ function materialize_forcing_modes( end """ - materialize_forcing_modes(ffs, rmp::ForcingTerms.RMPSource; kwargs...) -> (modes, coil_sets) + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingSource; kwargs...) -> (modes, coil_sets) -Materialize a single-source [`ForcingTerms.RMPField`](@ref) leaf and apply its weight. The +Materialize a single-source [`ForcingTerms.ForcingField`](@ref) leaf and apply its weight. The returned modes are fresh objects, so weighting never reaches back into any caller state. """ -function materialize_forcing_modes(ffs::ForceFreeStatesResult, rmp::ForcingTerms.RMPSource; kwargs...) - modes, coil_sets = materialize_forcing_modes(ffs, rmp.ctrl; kwargs...) - if rmp.scale != 1 - modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=rmp.scale * mode.amplitude) for mode in modes] +function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTerms.ForcingSource; kwargs...) + modes, coil_sets = materialize_forcing_modes(ffs, field.ctrl; kwargs...) + if field.scale != 1 + modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in modes] end return modes, coil_sets end """ - materialize_forcing_modes(ffs, rmp::ForcingTerms.RMPSpectrum; kwargs...) -> (modes, coil_sets) + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingSpectrum; kwargs...) -> (modes, coil_sets) Materialize a spectrum-literal leaf: fresh copies of its unit-norm modes, weighted. Nothing is read or integrated, and no coil geometry is produced. """ -function materialize_forcing_modes(::ForceFreeStatesResult, rmp::ForcingTerms.RMPSpectrum; kwargs...) - return [ForcingMode(; n=mode.n, m=mode.m, amplitude=rmp.scale * mode.amplitude) for mode in rmp.modes], ForcingTerms.CoilSet[] +function materialize_forcing_modes(::ForceFreeStatesResult, field::ForcingTerms.ForcingSpectrum; kwargs...) + return [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in field.modes], ForcingTerms.CoilSet[] end """ - materialize_forcing_modes(ffs, rmp::ForcingTerms.RMPFieldSum; kwargs...) -> (modes, coil_sets) + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingFieldSum; kwargs...) -> (modes, coil_sets) Materialize a lazy linear combination of forcing sources: each weighted leaf is evaluated independently and the mode amplitudes are summed per (n, m), sorted by (n, m). Coil geometry from every coil-format leaf is concatenated in the second return value; `preloaded_coil_sets` is ignored for sums. """ -function materialize_forcing_modes(ffs::ForceFreeStatesResult, rmp::ForcingTerms.RMPFieldSum; +function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTerms.ForcingFieldSum; preloaded_coil_sets::Vector{ForcingTerms.CoilSet}=ForcingTerms.CoilSet[], verbose::Bool=false) amplitudes = Dict{Tuple{Int,Int},ComplexF64}() coil_sets = ForcingTerms.CoilSet[] - for term in rmp.terms + for term in field.terms term_modes, term_coils = materialize_forcing_modes(ffs, term; verbose=verbose) for mode in term_modes key = (mode.n, mode.m) diff --git a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl index 32756ba71a..54bbec7590 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -39,7 +39,7 @@ end The source-independent half of a perturbed equilibrium: the control-surface response and singular-coupling operators of one force-free-states result, built once by [`plasma_response`](@ref) and applied to any number of external fields by -`perturbed_equilibrium(resp, rmp)` (Park et al., Phys. Plasmas 14, 052110 (2007); Park, +`perturbed_equilibrium(resp, field)` (Park et al., Phys. Plasmas 14, 052110 (2007); Park, Phys. Plasmas 16, 056115 (2009)). Operators the result could not supply (no free-boundary energies or no ξ solution) are left empty, and forcing such a response yields only the forcing spectra. @@ -165,7 +165,7 @@ The perturbed equilibrium driven by one external field: the forcing materialized ## Fields - `response::PlasmaResponse` - The operators this field was applied to. - - `forcing` - The [`ForcingTerms.RMPField`](@ref) applied. + - `forcing` - The [`ForcingTerms.ForcingField`](@ref) applied. - `forcing_modes::Vector{ForcingMode}` - The materialized control-surface forcing Φ_x. - `coil_sets::Vector{CoilSet}` - Coil geometry used (coil-format forcing); captured for the gpec.h5 rerun snapshot. - `regularization_width::Float64` - Width the profiles were reconstructed with (Fortran `reg_spot`): 0, no @@ -223,7 +223,7 @@ Torque response (kinetic forward solves with `compute_torque_response`): """ @kwdef mutable struct PerturbedEquilibriumState response::PlasmaResponse - forcing::Union{Nothing,ForcingTerms.RMPField} = nothing + forcing::Union{Nothing,ForcingTerms.ForcingField} = nothing forcing_modes::Vector{ForcingMode} = ForcingMode[] coil_sets::Vector{CoilSet} = CoilSet[] regularization_width::Float64 = 0.0 diff --git a/src/PerturbedEquilibrium/TorqueResponse.jl b/src/PerturbedEquilibrium/TorqueResponse.jl index 09cb18fc76..6eb4478796 100644 --- a/src/PerturbedEquilibrium/TorqueResponse.jl +++ b/src/PerturbedEquilibrium/TorqueResponse.jl @@ -132,13 +132,13 @@ referred to b̃ through `R = S·A`, so `T_source = B̃†·T_xe·B̃` with `B̃ """ function apply_torque_response!( state::PerturbedEquilibriumState, - forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.RMPField}; + forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.ForcingField}; verbose::Bool=false ) resp = state.response ffs = resp.ffs ft_ctrl = forcing isa ForcingTerms.ForcingTermsControl ? forcing : - forcing isa ForcingTerms.RMPSource ? forcing.ctrl : nothing + forcing isa ForcingTerms.ForcingSource ? forcing.ctrl : nothing source_b = zeros(ComplexF64, ffs.numpert_total, 0) source_names = String[] if !isempty(state.coil_sets) && ft_ctrl !== nothing && ft_ctrl.forcing_data_format == "coil" diff --git a/src/PerturbedEquilibrium/Utils.jl b/src/PerturbedEquilibrium/Utils.jl index 5241167121..ed3fa6a65a 100644 --- a/src/PerturbedEquilibrium/Utils.jl +++ b/src/PerturbedEquilibrium/Utils.jl @@ -211,7 +211,7 @@ end function _record_forcing_snapshot!(file, state::PerturbedEquilibriumState) forcing = state.forcing forcing === nothing && return nothing - snapshot = forcing isa ForcingTerms.RMPSource && forcing.scale == 1 ? ForcingTerms.snapshot_forcing_modes(forcing.ctrl) : + snapshot = forcing isa ForcingTerms.ForcingSource && forcing.scale == 1 ? ForcingTerms.snapshot_forcing_modes(forcing.ctrl) : (state.forcing_modes, "unit_flux") snapshot === nothing && return nothing modes, normalization = snapshot diff --git a/test/runtests_analysis_plots.jl b/test/runtests_analysis_plots.jl index 039fc68d46..2b29792809 100644 --- a/test/runtests_analysis_plots.jl +++ b/test/runtests_analysis_plots.jl @@ -114,10 +114,10 @@ using TOML bare, solved = A.Equilibrium._surfaces(ret.equil), A.Equilibrium._surfaces(ret.ffs) @test all(q -> any(≈(q), bare.sing_q), solved.sing_q) && !isempty(bare.sing_q) @test plot_equilibrium_summary(ret.equil; n=2) isa Figure - # An RMPField draws its coil sources in 3D before any plasma; a mode table has no geometry to draw. - hoop = RMPField((name="hoop", source="pf_hoop", radius=12.0, height=1.2, currents=[2.0e3], tiltx=[3.0])) + # A ForcingField draws its coil sources in 3D before any plasma; a mode table has no geometry to draw. + hoop = ForcingField((name="hoop", source="pf_hoop", radius=12.0, height=1.2, currents=[2.0e3], tiltx=[3.0])) @test plot_sources(hoop) isa Figure && plot_sources(2hoop - 0.5im * hoop; color=:set) isa Figure - @test_throws A.REASONS[:coil_source] plot_sources(RMPField([GPEC.ForcingTerms.ForcingMode(; n=1, m=2, amplitude=1e-4)])) + @test_throws A.REASONS[:coil_source] plot_sources(ForcingField([GPEC.ForcingTerms.ForcingMode(; n=1, m=2, amplitude=1e-4)])) # A summary none of whose panels this run supplies is listed as unavailable, and says so when called. @test occursin("✗ plot_error_field_summary", repr(MIME"text/plain"(), available_plots(h5))) @test_throws A.REASONS[:ef_sensitivities] plot_error_field_summary(h5) diff --git a/test/runtests_deck_roundtrip.jl b/test/runtests_deck_roundtrip.jl index d0df7e00a3..92e0d1779e 100644 --- a/test/runtests_deck_roundtrip.jl +++ b/test/runtests_deck_roundtrip.jl @@ -62,7 +62,7 @@ end ffs = solve(ForceBalanceProblem(equil; deck.force_balance.keywords...), deck.force_balance.algorithm) ls = solve(LocalStabilityProblem(ffs.equil; deck.local_stability.problem...), deck.local_stability.algorithm) resp = plasma_response(ffs; deck.perturbed_equilibrium.response...) - pe = perturbed_equilibrium(resp, RMPField(deck.forcing); deck.perturbed_equilibrium.drive...) + pe = perturbed_equilibrium(resp, ForcingField(deck.forcing); deck.perturbed_equilibrium.drive...) script_h5 = joinpath(dir, "script.h5") foreach(r -> save_to_hdf5(script_h5, r), (ffs, ls, pe)) @test deck_same(stages(recorded(script_h5), dir), stages(recorded(deck_h5), dir)) @@ -82,7 +82,7 @@ end @test replay.pe.forcing_b == pe.forcing_b # A weighted field has no [ForcingTerms]: the replay drives the recorded control-surface modes. - doubled = perturbed_equilibrium(resp, 2 * RMPField(deck.forcing); deck.perturbed_equilibrium.drive...) + doubled = perturbed_equilibrium(resp, 2 * ForcingField(deck.forcing); deck.perturbed_equilibrium.drive...) weighted_h5 = joinpath(dir, "weighted.h5") foreach(r -> save_to_hdf5(weighted_h5, r), (ffs, doubled)) @test recorded(weighted_h5)["ForcingTerms"]["forcing_data_file"] == "Input/RawInputs/ForcingTerms" diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index fb4212bf1c..f57f8a0f38 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -238,7 +238,7 @@ include("display_check.jl") ffs = solve(equil, forward; nn=1, wall=wall, ffs_kwargs...) resp = plasma_response(ffs; verbose=false) - pe = perturbed_equilibrium(resp, RMPField(forcing); pe_kw...) + pe = perturbed_equilibrium(resp, ForcingField(forcing); pe_kw...) # The response matrices depend on the equilibrium and the solve, not on the drive. @test resp isa PlasmaResponse && pe.response === resp @@ -247,38 +247,38 @@ include("display_check.jl") @test size(resp.C_delta_mn) == size(reference.response.C_delta_mn) @test !isempty(pe.resonant_area_weighted_field) - # The deck reads and normalizes its forcing file exactly as a fresh RMPField does. + # The deck reads and normalizes its forcing file exactly as a fresh ForcingField does. @test pe.resonant_area_weighted_field ≈ reference.resonant_area_weighted_field rtol = 1e-10 @test pe.forcing_b ≈ reference.forcing_b rtol = 1e-10 # One response serves any number of fields: forcing it again reproduces the result. - again = perturbed_equilibrium(resp, RMPField(forcing); pe_kw...) + again = perturbed_equilibrium(resp, ForcingField(forcing); pe_kw...) @test again.forcing_b == pe.forcing_b @test again.resonant_area_weighted_field == pe.resonant_area_weighted_field # `scale` is a uniform multiplier on the materialized forcing, and the response is # linear in it. - scaled = perturbed_equilibrium(resp, RMPField(forcing; scale=2.0); pe_kw...) + scaled = perturbed_equilibrium(resp, ForcingField(forcing; scale=2.0); pe_kw...) @test scaled.forcing_b ≈ 2 .* pe.forcing_b rtol = 1e-10 @test scaled.resonant_area_weighted_field ≈ 2 .* pe.resonant_area_weighted_field rtol = 1e-10 # Lazy source algebra materializes to the combined field: 3A - A == 2A drives # the same perturbed equilibrium as scale=2 (exercises +, -, * and the merge). - combo = perturbed_equilibrium(resp, 3 * RMPField(forcing) - RMPField(forcing); pe_kw...) + combo = perturbed_equilibrium(resp, 3 * ForcingField(forcing) - ForcingField(forcing); pe_kw...) @test combo.forcing_b ≈ scaled.forcing_b rtol = 1e-10 @test combo.resonant_area_weighted_field ≈ scaled.resonant_area_weighted_field rtol = 1e-10 # A spectrum-literal leaf of the materialized modes drives the same perturbed equilibrium, # takes a weight, and sums with a file leaf. - literal = perturbed_equilibrium(resp, RMPField(pe.forcing_modes); pe_kw...) + literal = perturbed_equilibrium(resp, ForcingField(pe.forcing_modes); pe_kw...) @test literal.forcing_b == pe.forcing_b @test literal.resonant_area_weighted_field == pe.resonant_area_weighted_field - @test perturbed_equilibrium(resp, 2 * RMPField(pe.forcing_modes); pe_kw...).forcing_b ≈ scaled.forcing_b rtol = 1e-10 - @test perturbed_equilibrium(resp, RMPField(pe.forcing_modes) + RMPField(forcing); pe_kw...).forcing_b ≈ scaled.forcing_b rtol = 1e-10 + @test perturbed_equilibrium(resp, 2 * ForcingField(pe.forcing_modes); pe_kw...).forcing_b ≈ scaled.forcing_b rtol = 1e-10 + @test perturbed_equilibrium(resp, ForcingField(pe.forcing_modes) + ForcingField(forcing); pe_kw...).forcing_b ≈ scaled.forcing_b rtol = 1e-10 # No regularization by default; an explicit width changes the regularized profiles, not the control-surface quantities. @test pe.regularization_width == 0.0 - reg = perturbed_equilibrium(resp, RMPField(forcing); regularization_width=0.05, pe_kw...) + reg = perturbed_equilibrium(resp, ForcingField(forcing); regularization_width=0.05, pe_kw...) @test reg.regularization_width == 0.05 @test reg.forcing_b == pe.forcing_b @test !(reg.xi_modes.clebsch_alpha ≈ pe.xi_modes.clebsch_alpha) @@ -294,12 +294,12 @@ include("display_check.jl") f["n"], f["m"], f["amplitude_real"], f["amplitude_imag"] = [1, 1], [2, 3], [1e-4, 5e-5], [0.0, 0.0] end - @testset "RMPField algebra is lazy and flattens" begin - a = RMPField(table) - b = RMPField(table; scale=0.5) - c = RMPField(table_h5) + @testset "ForcingField algebra is lazy and flattens" begin + a = ForcingField(table) + b = ForcingField(table; scale=0.5) + c = ForcingField(table_h5) s = a + b - @test s isa GPEC.ForcingTerms.RMPFieldSum + @test s isa GPEC.ForcingTerms.ForcingFieldSum @test length(s.terms) == 2 @test length((a + b + c).terms) == 3 d = 2.0 * s @@ -309,37 +309,37 @@ include("display_check.jl") @test (a * 3).scale == 3.0 + 0.0im @test (a-b).terms[2].scale == -0.5 + 0.0im @test (-a).scale == -1.0 + 0.0im - @test repr(a) == "RMPField(forcing.dat (ascii))" && repr(3 * a) == "RMPField(3 × forcing.dat (ascii))" + @test repr(a) == "ForcingField(forcing.dat (ascii))" && repr(3 * a) == "ForcingField(3 × forcing.dat (ascii))" @test occursin("-0.5im × forcing.h5 (hdf5)", repr(MIME"text/plain"(), a - 0.5im * c)) end - @testset "RMPField infers its format and carries its scale" begin - @test RMPField(table).ctrl.forcing_data_format == "ascii" - @test RMPField(table_h5).ctrl.forcing_data_format == "hdf5" - @test isabspath(RMPField(table).ctrl.forcing_data_file) - @test RMPField(table; scale=3.0).scale == 3.0 + @testset "ForcingField infers its format and carries its scale" begin + @test ForcingField(table).ctrl.forcing_data_format == "ascii" + @test ForcingField(table_h5).ctrl.forcing_data_format == "hdf5" + @test isabspath(ForcingField(table).ctrl.forcing_data_file) + @test ForcingField(table; scale=3.0).scale == 3.0 # One coil set or several, as NamedTuples or Dicts with the [[ForcingTerms.coil_set]] keys. c_coil = (name="c", currents=[1e3, 500, -500, -1e3, -500, 500]) - coil_field = RMPField(c_coil; machine="d3d") + coil_field = ForcingField(c_coil; machine="d3d") @test coil_field.ctrl.forcing_data_format == "coil" @test coil_field.ctrl.machine == "d3d" @test coil_field.ctrl.coil_sets_raw == [Dict{String,Any}("name" => "c", "currents" => c_coil.currents)] - @test length(RMPField([c_coil, Dict("name" => "iu", "currents" => fill(1e3, 6))]; machine="d3d").ctrl.coil_sets_raw) == 2 - @test repr(coil_field) == "RMPField(d3d coils c)" + @test length(ForcingField([c_coil, Dict("name" => "iu", "currents" => fill(1e3, 6))]; machine="d3d").ctrl.coil_sets_raw) == 2 + @test repr(coil_field) == "ForcingField(d3d coils c)" end - @testset "RMPField checks its source when built" begin - @test_throws "no forcing file" RMPField(joinpath(forcing_dir, "missing.dat")) + @testset "ForcingField checks its source when built" begin + @test_throws "no forcing file" ForcingField(joinpath(forcing_dir, "missing.dat")) geometry = joinpath(pkgdir(GPEC), "src", "ForcingTerms", "coil_geometries", "d3d_c.dat") - @test_throws "is not a forcing-mode table" RMPField(geometry) - @test_throws "is not a forcing-mode table" RMPField(table; format="hdf5") - @test_throws "is not \"ascii\", \"hdf5\" or \"coil\"" RMPField(table; format="csv") - @test_throws "has no currents" RMPField((name="c",); machine="d3d") - @test_throws "currents for its 6 conductors" RMPField((name="c", currents=ones(7)); machine="d3d") - @test_throws "pass machine" RMPField((name="c", currents=ones(6))) - @test_throws "unknown keys" RMPField((name="c", curents=ones(6)); machine="d3d") - @test_throws "a coil set is a Dict or NamedTuple" RMPField([1, 2]) - @test_throws "at least one forcing mode" RMPField(GPEC.ForcingTerms.ForcingMode[]) + @test_throws "is not a forcing-mode table" ForcingField(geometry) + @test_throws "is not a forcing-mode table" ForcingField(table; format="hdf5") + @test_throws "is not \"ascii\", \"hdf5\" or \"coil\"" ForcingField(table; format="csv") + @test_throws "has no currents" ForcingField((name="c",); machine="d3d") + @test_throws "currents for its 6 conductors" ForcingField((name="c", currents=ones(7)); machine="d3d") + @test_throws "pass machine" ForcingField((name="c", currents=ones(6))) + @test_throws "unknown keys" ForcingField((name="c", curents=ones(6)); machine="d3d") + @test_throws "a coil set is a Dict or NamedTuple" ForcingField([1, 2]) + @test_throws "at least one forcing mode" ForcingField(GPEC.ForcingTerms.ForcingMode[]) end @testset "rejected keyword combinations" begin @@ -554,7 +554,7 @@ include("display_check.jl") @test isempty(resp.C_delta_mn) && isempty(resp.C_resonant_area_weighted_field) @test size(resp.C_delta_mn_asymptotic) == (length(resp.rational_psi), matched.numpert_total) @test resp.C_delta_mn_asymptotic != plasma_response(ric).C_delta_mn_asymptotic - pe = perturbed_equilibrium(resp, RMPField(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"))) + pe = perturbed_equilibrium(resp, ForcingField(joinpath(@__DIR__, "..", "examples", "TJ_ideal_example", "forcing.dat"))) @test isempty(pe.delta_mn) && length(pe.delta_mn_asymptotic) == length(resp.rational_psi) @test all(isfinite, pe.island_half_width_asymptotic) # A matched result is a new solution, not an outer solve to match again. @@ -643,10 +643,10 @@ include("display_check.jl") "PerturbedEquilibrium" => Dict{String,Any}(String(k) => v for (k, v) in pairs(pe_kwargs)))) reference = GPEC.main([dir]) resp = plasma_response(reference.ffs; compute_singular_coupling=true, verbose=false) - pe = perturbed_equilibrium(resp, RMPField(joinpath(dir, "forcing.h5")); verbose=false) + pe = perturbed_equilibrium(resp, ForcingField(joinpath(dir, "forcing.h5")); verbose=false) @test pe.response.permeability ≈ reference.pe.response.permeability rtol = 1e-10 - # The deck reads and normalizes its forcing file exactly as a fresh RMPField does. + # The deck reads and normalizes its forcing file exactly as a fresh ForcingField does. @test pe.forcing_b ≈ reference.pe.forcing_b rtol = 1e-10 end end diff --git a/test/runtests_torque_response.jl b/test/runtests_torque_response.jl index 8ceb87036f..a7ee1a1165 100644 --- a/test/runtests_torque_response.jl +++ b/test/runtests_torque_response.jl @@ -157,7 +157,7 @@ compute_torque_response = true # Build the ψ-resolved torque response @testset "regularization on a kinetic result" begin # No regularization by default; an explicit width still reaches the regularized profiles. @test pe.regularization_width == 0.0 - reg = perturbed_equilibrium(resp, _GPE_TR.ForcingTerms.RMPField(ft_ctrl); regularization_width=0.05, + reg = perturbed_equilibrium(resp, _GPE_TR.ForcingTerms.ForcingField(ft_ctrl); regularization_width=0.05, coil_sets=pe.coil_sets, verbose=false) @test reg.regularization_width == 0.05 @test reg.forcing_b ≈ pe.forcing_b rtol = 1e-12 @@ -169,7 +169,7 @@ compute_torque_response = true # Build the ψ-resolved torque response # A response without its operators cannot carry a torque response. @test_throws ArgumentError _PE_TR.build_torque_response!(_PE_TR.PlasmaResponse(; ffs)) # The torque response is opt-in: a response built without it contracts nothing. - plain = perturbed_equilibrium(plasma_response(ffs; compute_singular_coupling=false, verbose=false), _GPE_TR.ForcingTerms.RMPField(ft_ctrl); + plain = perturbed_equilibrium(plasma_response(ffs; compute_singular_coupling=false, verbose=false), _GPE_TR.ForcingTerms.ForcingField(ft_ctrl); coil_sets=pe.coil_sets, verbose=false) @test isempty(plain.response.T_xe) && plain.torque_response === nothing end From eeb5b56811fc1391367fca24e34f7290b1e271de Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Fri, 13 Nov 2026 16:52:34 +0100 Subject: [PATCH 19/27] ForcingTerms - REFACTOR! - Make each ForcingField source its own leaf type --- src/Analysis/CoilForcing.jl | 4 +- src/Analysis/Registry.jl | 3 +- src/Deck.jl | 16 ++- src/Display.jl | 12 +- src/ForcingTerms/CoilGeometry.jl | 7 +- src/ForcingTerms/ForcingTerms.jl | 105 +++++++++++------- src/GeneralizedPerturbedEquilibrium.jl | 2 +- .../PerturbedEquilibrium.jl | 81 ++++++-------- src/PerturbedEquilibrium/TorqueResponse.jl | 18 +-- src/PerturbedEquilibrium/Utils.jl | 4 +- test/runtests_solve_api.jl | 25 +++-- test/runtests_torque_response.jl | 4 +- 12 files changed, 154 insertions(+), 127 deletions(-) diff --git a/src/Analysis/CoilForcing.jl b/src/Analysis/CoilForcing.jl index e3a0c5ec08..11bcbd4934 100644 --- a/src/Analysis/CoilForcing.jl +++ b/src/Analysis/CoilForcing.jl @@ -237,13 +237,13 @@ end function _field_coil_sets(field::FT.ForcingField; n=1) sets, skipped, complex_weight = FT.CoilSet[], 0, false for t in FT._field_terms(field) - if !(t isa FT.ForcingSource && t.ctrl.forcing_data_format == "coil") + if !(t isa FT.ForcingCoils) skipped += 1 continue end complex_weight |= !isreal(t.scale) w = isreal(t.scale) ? real(t.scale) : abs(t.scale) - for cs in FT.load_coil_sets(FT.CoilConfig(t.ctrl), n) + for cs in FT.load_coil_sets(t.config, n) push!(sets, FT.CoilSet(cs.name, cs.ncoil, cs.s, cs.nw, cs.nsec, cs.x, cs.y, cs.z, w .* cs.currents)) end end diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index e582c7c725..6332d2d375 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -97,8 +97,7 @@ end capabilities(r::LocalStabilityResult) = isempty(r.alpha) ? Set{Symbol}() : Set([:ballooning_scan]) -capabilities(r::FT.ForcingField) = - any(t -> t isa FT.ForcingSource && t.ctrl.forcing_data_format == "coil", FT._field_terms(r)) ? Set([:coil_source]) : Set{Symbol}() +capabilities(r::FT.ForcingField) = any(t -> t isa FT.ForcingCoils, FT._field_terms(r)) ? Set([:coil_source]) : Set{Symbol}() function capabilities(r::PlasmaResponse) caps = Set{Symbol}() diff --git a/src/Deck.jl b/src/Deck.jl index 4d2d347fd2..21ffa16f1b 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -618,6 +618,20 @@ function _forcing_table(ctrl::ForcingTerms.ForcingTermsControl) return table end +# [ForcingTerms] of a single forcing source: a file by path, coils by their settings and the non-default keys of each set. +_forcing_table(f::ForcingTerms.ForcingFile) = Dict{String,Any}("forcing_data_file" => f.path, "forcing_data_format" => f.format) + +function _forcing_table(f::ForcingTerms.ForcingCoils) + cfg, default = f.config, ForcingTerms.CoilSetConfig() + table = Dict{String,Any}("forcing_data_format" => "coil", "machine" => cfg.machine, "mtheta_coil" => cfg.mtheta_coil, "nzeta_coil" => cfg.nzeta_coil) + cfg.dat_dir == ForcingTerms.BUNDLED_COIL_DIR || (table["dat_dir"] = cfg.dat_dir) + table["coil_set"] = Any[ + Dict{String,Any}(String(k) => _deck_out(getfield(sc, k)) for k in fieldnames(ForcingTerms.CoilSetConfig) if !isequal(getfield(sc, k), getfield(default, k))) + for sc in cfg.coil_sets + ] + return table +end + # [ErrorFields] with its sub-tables, from the settings an error-field assessment takes. function _error_fields_sections(settings, tolerance_file::AbstractString) table = _deck_table(settings.ctrl) @@ -661,7 +675,7 @@ function deck_sections(pe::PerturbedEquilibrium.PerturbedEquilibriumState) sections = Dict{String,Any}("PerturbedEquilibrium" => table) forcing === nothing && return sections sections["ForcingTerms"] = - forcing isa ForcingTerms.ForcingSource && forcing.scale == 1 ? _forcing_table(forcing.ctrl) : + forcing isa Union{ForcingTerms.ForcingFile,ForcingTerms.ForcingCoils} && forcing.scale == 1 ? _forcing_table(forcing) : Dict{String,Any}("forcing_data_format" => "hdf5", "forcing_data_file" => _RECORDED_FORCING) return sections end diff --git a/src/Display.jl b/src/Display.jl index 7c0df7ac67..e0c3a544f0 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -11,7 +11,7 @@ using .PerturbedEquilibrium: PerturbedEquilibriumState using .KineticForces: MethodResult, KineticForcesState using .ErrorFields: MonteCarloResult, RiskResult, EFCCoupling using .Tearing: GrowthRateResult -using .ForcingTerms: ForcingSource, ForcingSpectrum, ForcingFieldSum +using .ForcingTerms: ForcingFile, ForcingCoils, ForcingSpectrum, ForcingLeaf, ForcingFieldSum _fmt(x::Real) = @sprintf("%.4g", x) _fmt(::Nothing) = "—" @@ -292,15 +292,15 @@ end _weight(w) = string(iszero(real(w)) && !iszero(imag(w)) ? _fmt(imag(w)) * "im" : _fmt(w), " × ") -function _field_label(f::ForcingSource) - c = f.ctrl - c.forcing_data_format == "coil" || return string(basename(c.forcing_data_file), " (", c.forcing_data_format, ")") - sets = [isempty(get(d, "name", "")) ? get(d, "source", "coil set") : d["name"] for d in c.coil_sets_raw] +_field_label(f::ForcingFile) = string(basename(f.path), " (", f.format, ")") +function _field_label(f::ForcingCoils) + c = f.config + sets = [!isempty(sc.name) ? sc.name : !isempty(sc.source) ? sc.source : "coil set" for sc in c.coil_sets] return string(isempty(c.machine) ? "" : c.machine * " ", "coils ", _list(sets)) end _field_label(f::ForcingSpectrum) = string("spectrum of ", _plural(length(f.modes), "mode"), ", n = ", _irange([m.n for m in f.modes])) -Base.show(io::IO, f::Union{ForcingSource,ForcingSpectrum}) = print(io, "ForcingField(", f.scale == 1 ? "" : _weight(f.scale), _field_label(f), ")") +Base.show(io::IO, f::ForcingLeaf) = print(io, "ForcingField(", f.scale == 1 ? "" : _weight(f.scale), _field_label(f), ")") Base.show(io::IO, f::ForcingFieldSum) = print(io, "ForcingField(sum of ", _plural(length(f.terms), "term"), ")") function Base.show(io::IO, ::MIME"text/plain", f::ForcingFieldSum) diff --git a/src/ForcingTerms/CoilGeometry.jl b/src/ForcingTerms/CoilGeometry.jl index e13277bdee..6d27f68a54 100644 --- a/src/ForcingTerms/CoilGeometry.jl +++ b/src/ForcingTerms/CoilGeometry.jl @@ -156,15 +156,16 @@ Base.@kwdef struct CoilConfig coil_sets::Vector{CoilSetConfig} = CoilSetConfig[] end +# The coil geometry files shipped with the package, the default `dat_dir`. +const BUNDLED_COIL_DIR = joinpath(@__DIR__, "coil_geometries") + """ CoilConfig(ft_ctrl::ForcingTermsControl) Construct a `CoilConfig` from a `ForcingTermsControl` populated from TOML. """ function CoilConfig(ft_ctrl::ForcingTermsControl) - dat_dir = isempty(ft_ctrl.dat_dir) ? - joinpath(@__DIR__, "coil_geometries") : - ft_ctrl.dat_dir + dat_dir = isempty(ft_ctrl.dat_dir) ? BUNDLED_COIL_DIR : ft_ctrl.dat_dir coil_sets = CoilSetConfig[_parse_coil_set_config(d) for d in ft_ctrl.coil_sets_raw] diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index bb827c1c43..01da33e910 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -266,8 +266,9 @@ drive several solves. ## Construction - ForcingField(path; format=..., scale=1.0, kwargs...) + ForcingField(path; format=..., scale=1.0) ForcingField(coil_sets; scale=1.0, kwargs...) + ForcingField(cfg::CoilConfig; scale=1.0) ForcingField(ctrl::ForcingTermsControl; scale=1.0) ForcingField(modes::Vector{ForcingMode}; scale=1.0) @@ -281,10 +282,11 @@ ForcingField([(name="iu", currents=iu), (name="il", currents=il)]; machine="d3d" ForcingField((source="pf_hoop", radius=12.0, height=1.2, currents=[2e3])) ``` -Remaining `kwargs` are -[`ForcingTermsControl`](@ref) fields. These three return a single-source leaf -([`ForcingSource`](@ref)). The last form takes a control-surface spectrum computed elsewhere, already in -the unit-norm `Φ_x` convention, and returns a spectrum-literal leaf ([`ForcingSpectrum`](@ref)). +Its remaining `kwargs` are the [`ForcingTermsControl`](@ref) coil settings (`machine`, `dat_dir`, `mtheta_coil`, +`nzeta_coil`). The third form takes the same coil description already parsed, and the fourth a deck's `[ForcingTerms]` +section. The file forms return a [`ForcingFile`](@ref) leaf and the coil forms a [`ForcingCoils`](@ref) leaf. The last form +takes a control-surface spectrum computed elsewhere, already in the unit-norm `Φ_x` convention, and returns a +spectrum-literal leaf ([`ForcingSpectrum`](@ref)). ## Algebra @@ -308,18 +310,36 @@ failed conductor is `nominal - failed_coil`, not `0.9 * nominal`. abstract type ForcingField end """ - ForcingSource + ForcingFile -A single-source [`ForcingField`](@ref) leaf: one forcing description plus a complex weight. -Built by the `ForcingField` constructors; scalar multiplication rescales the weight. +A forcing-mode file [`ForcingField`](@ref) leaf: a table of (n, m) amplitudes plus a complex weight. +Built by `ForcingField(path)`; scalar multiplication rescales the weight. ## Fields - - `ctrl::ForcingTermsControl` - The forcing source: format, file path or machine, and the raw coil-set blocks. + - `path::String` - Absolute path of the forcing-mode table. + - `format::String` - `"ascii"` or `"hdf5"`; see [`load_forcing_data!`](@ref). - `scale::ComplexF64` - The source's weight in a linear combination, applied to the materialized control-surface spectrum (complex = phase rotation). Not a physical amplitude. """ -struct ForcingSource <: ForcingField - ctrl::ForcingTermsControl +struct ForcingFile <: ForcingField + path::String + format::String + scale::ComplexF64 +end + +""" + ForcingCoils + +A coil [`ForcingField`](@ref) leaf: coil sets with their currents, whose Biot-Savart field is sampled on the control +surface, plus a complex weight. Built by `ForcingField(coil_sets)`; scalar multiplication rescales the weight. + +## Fields + + - `config::CoilConfig` - The coil sets and the boundary grid their field is sampled on. + - `scale::ComplexF64` - The source's weight in a linear combination, as for [`ForcingFile`](@ref). +""" +struct ForcingCoils <: ForcingField + config::CoilConfig scale::ComplexF64 end @@ -333,27 +353,30 @@ unit-norm `Φ_x` convention the response consumes, plus a complex weight. Built ## Fields - `modes::Vector{ForcingMode}` - The control-surface spectrum, copied at construction. - - `scale::ComplexF64` - The leaf's weight in a linear combination, as for [`ForcingSource`](@ref). + - `scale::ComplexF64` - The leaf's weight in a linear combination, as for [`ForcingFile`](@ref). """ struct ForcingSpectrum <: ForcingField modes::Vector{ForcingMode} scale::ComplexF64 end +# A single-source ForcingField: one forcing description plus its weight. +const ForcingLeaf = Union{ForcingFile,ForcingCoils,ForcingSpectrum} + """ ForcingFieldSum -A lazy linear combination of [`ForcingSource`](@ref) and [`ForcingSpectrum`](@ref) leaves, built by `+`/`-` on -[`ForcingField`](@ref)s. Holds the flattened term list; scalar multiplication distributes onto +A lazy linear combination of [`ForcingFile`](@ref), [`ForcingCoils`](@ref) and [`ForcingSpectrum`](@ref) leaves, built by `+`/`-` +on [`ForcingField`](@ref)s. Holds the flattened term list; scalar multiplication distributes onto the leaves. Materialization evaluates each term against the equilibrium and sums the mode amplitudes — valid because the perturbed-equilibrium response is linear in the forcing. ## Fields - - `terms::Vector{Union{ForcingSource,ForcingSpectrum}}` - The flattened weighted leaves. + - `terms::Vector{Union{ForcingFile,ForcingCoils,ForcingSpectrum}}` - The flattened weighted leaves. """ struct ForcingFieldSum <: ForcingField - terms::Vector{Union{ForcingSource,ForcingSpectrum}} + terms::Vector{ForcingLeaf} end """ @@ -366,16 +389,15 @@ _infer_format(path::AbstractString) = lowercase(splitext(path)[2]) in (".h5", ". const _NORMALIZATIONS = ("normal_field_T", "sfl_flux_Wb", "unit_flux") # Read a forcing-mode file now, so a missing or malformed file fails when the source is built. -function _check_forcing_file(ctrl::ForcingTermsControl) - path = ctrl.forcing_data_file +function _check_forcing_file(path::AbstractString, format::AbstractString) isfile(path) || throw(ArgumentError("ForcingField: no forcing file at $path")) modes = ForcingMode[] tag = try - load_forcing_data!(modes, path, ctrl.forcing_data_format) + load_forcing_data!(modes, path, format) catch err throw( ArgumentError( - "ForcingField: $path is not a forcing-mode table (format $(ctrl.forcing_data_format)): $(sprint(showerror, err)). " * + "ForcingField: $path is not a forcing-mode table (format $format): $(sprint(showerror, err)). " * "A mode table holds rows of n, m, Re, Im (see `load_forcing_data!`); a coil geometry file goes in a coil set, " * "as in ForcingField((name=\"set\", dat_file=path, currents=[...]))." ) @@ -388,9 +410,8 @@ end # Resolve every coil set now, so an unknown key, a missing geometry file or a missing current fails when the source is # built; window-pane sets placed by standoff need the plasma surface and are resolved when materialized. -function _check_coil_sets(ctrl::ForcingTermsControl) - isempty(ctrl.coil_sets_raw) && throw(ArgumentError("ForcingField: a coil source needs at least one coil set")) - cfg = CoilConfig(ctrl) +function _check_coil_sets(cfg::CoilConfig) + isempty(cfg.coil_sets) && throw(ArgumentError("ForcingField: a coil source needs at least one coil set")) for sc in cfg.coil_sets label = isempty(sc.name) ? "a coil set" : "coil set \"$(sc.name)\"" all(iszero, sc.currents) && throw(ArgumentError("ForcingField: $label has no currents; give `currents` in amperes, one per conductor")) @@ -409,16 +430,21 @@ function _check_coil_sets(ctrl::ForcingTermsControl) return nothing end -function ForcingField(ctrl::ForcingTermsControl; scale::Number=1.0) - fmt = ctrl.forcing_data_format - fmt == "coil" ? _check_coil_sets(ctrl) : - fmt in ("ascii", "hdf5") ? _check_forcing_file(ctrl) : - throw(ArgumentError("ForcingField: forcing_data_format \"$fmt\" is not \"ascii\", \"hdf5\" or \"coil\"")) - return ForcingSource(ctrl, ComplexF64(scale)) +function ForcingField(cfg::CoilConfig; scale::Number=1.0) + _check_coil_sets(cfg) + return ForcingCoils(cfg, ComplexF64(scale)) end -ForcingField(path::AbstractString; format::String=_infer_format(path), scale::Number=1.0, kwargs...) = - ForcingField(ForcingTermsControl(; forcing_data_file=abspath(path), forcing_data_format=format, kwargs...); scale) +function ForcingField(path::AbstractString; format::String=_infer_format(path), scale::Number=1.0) + format in ("ascii", "hdf5") || throw(ArgumentError("ForcingField: forcing_data_format \"$format\" is not \"ascii\", \"hdf5\" or \"coil\"")) + _check_forcing_file(abspath(path), format) + return ForcingFile(abspath(path), format, ComplexF64(scale)) +end + +function ForcingField(ctrl::ForcingTermsControl; scale::Number=1.0) + ctrl.forcing_data_format == "coil" && return ForcingField(CoilConfig(ctrl); scale) + return ForcingField(ctrl.forcing_data_file; format=ctrl.forcing_data_format, scale) +end # A coil set as the [[ForcingTerms.coil_set]] table: a Dict or NamedTuple, keys as strings or symbols. _coil_dict(d::AbstractDict) = Dict{String,Any}(string(k) => v for (k, v) in d) @@ -438,29 +464,28 @@ end """ Flattened weighted-leaf list of any [`ForcingField`](@ref). """ -_field_terms(f::Union{ForcingSource,ForcingSpectrum}) = Union{ForcingSource,ForcingSpectrum}[f] +_field_terms(f::ForcingLeaf) = ForcingLeaf[f] _field_terms(f::ForcingFieldSum) = f.terms Base.:+(a::ForcingField, b::ForcingField) = ForcingFieldSum(vcat(_field_terms(a), _field_terms(b))) Base.:-(a::ForcingField) = -1 * a Base.:-(a::ForcingField, b::ForcingField) = a + (-1 * b) -Base.:*(c::Number, f::ForcingSource) = ForcingSource(f.ctrl, ComplexF64(c) * f.scale) +Base.:*(c::Number, f::ForcingFile) = ForcingFile(f.path, f.format, ComplexF64(c) * f.scale) +Base.:*(c::Number, f::ForcingCoils) = ForcingCoils(f.config, ComplexF64(c) * f.scale) Base.:*(c::Number, f::ForcingSpectrum) = ForcingSpectrum(f.modes, ComplexF64(c) * f.scale) Base.:*(c::Number, f::ForcingFieldSum) = ForcingFieldSum([c * t for t in f.terms]) Base.:*(f::ForcingField, c::Number) = c * f """ - snapshot_forcing_modes(ft_ctrl; verbose=false) -> Union{Nothing,Tuple{Vector{ForcingMode},String}} + snapshot_forcing_modes(f::ForcingFile; verbose=false) -> Tuple{Vector{ForcingMode},String} -The raw file-based forcing modes of `ft_ctrl` and their normalization tag, so they land in -`Input/RawInputs/ForcingTerms/` alongside the TOML blob; `nothing` for coil forcing, which is -recomputed from the `[[coil_set]]` TOML blob on replay. They feed only the writer: +The raw forcing modes of the file `f` and their normalization tag, so they land in +`Input/RawInputs/ForcingTerms/` alongside the TOML blob. They feed only the writer: the PE stage reads and normalizes the forcing file itself. """ -function snapshot_forcing_modes(ft_ctrl::ForcingTermsControl; verbose::Bool=false) - ft_ctrl.forcing_data_format in ("ascii", "hdf5") || return nothing +function snapshot_forcing_modes(f::ForcingFile; verbose::Bool=false) modes = ForcingMode[] - normalization = load_forcing_data!(modes, ft_ctrl.forcing_data_file, ft_ctrl.forcing_data_format, verbose) + normalization = load_forcing_data!(modes, f.path, f.format, verbose) return modes, normalization end diff --git a/src/GeneralizedPerturbedEquilibrium.jl b/src/GeneralizedPerturbedEquilibrium.jl index 62a2709c5a..38ef432277 100755 --- a/src/GeneralizedPerturbedEquilibrium.jl +++ b/src/GeneralizedPerturbedEquilibrium.jl @@ -199,7 +199,7 @@ function main_from_inputs( if deck.perturbed_equilibrium !== nothing pe = _timed_stage(runtimes, "perturbed_equilibrium", "Perturbed Equilibrium") do # A replay from stored coil geometry skips the source checks: the geometry files they read may be gone. - field = preloaded_coil_sets === nothing ? ForcingField(deck.forcing) : ForcingTerms.ForcingSource(deck.forcing, 1) + field = preloaded_coil_sets === nothing ? ForcingField(deck.forcing) : ForcingTerms.ForcingCoils(ForcingTerms.CoilConfig(deck.forcing), 1) perturbed_equilibrium(plasma_response(ffs; verbose, deck.perturbed_equilibrium.response...), field; coil_sets=preloaded_coil_sets, verbose, deck.perturbed_equilibrium.drive...) end diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 5c83824f0c..63e3aa6dd5 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -122,8 +122,8 @@ end compute_perturbed_equilibrium(resp, forcing; regularization_width=0.0, verbose=true, preloaded_coil_sets=CoilSet[])::PerturbedEquilibriumState -Drive the operators of `resp` with one external field: materialize `forcing` (a `ForcingTermsControl` -or any [`ForcingTerms.ForcingField`](@ref)) on the control surface, then apply the response and the +Drive the operators of `resp` with one external field: materialize `forcing` (any +[`ForcingTerms.ForcingField`](@ref)) on the control surface, then apply the response and the singular coupling to it, reconstruct the perturbed profiles, and contract any torque response with the forcing sources. Steps whose operators `resp` does not carry are skipped, leaving only the forcing spectrum. @@ -136,15 +136,14 @@ forcing spectrum. """ function compute_perturbed_equilibrium( resp::PlasmaResponse, - forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.ForcingField}; + forcing::ForcingTerms.ForcingField; regularization_width::Real=0.0, verbose::Bool=true, preloaded_coil_sets::Vector{CoilSet}=CoilSet[] )::PerturbedEquilibriumState ffs = resp.ffs modes, coil_sets = materialize_forcing_modes(ffs, forcing; preloaded_coil_sets, verbose) - state = PerturbedEquilibriumState(; response=resp, forcing=forcing isa ForcingTerms.ForcingField ? forcing : ForcingTerms.ForcingField(forcing), - forcing_modes=modes, + state = PerturbedEquilibriumState(; response=resp, forcing, forcing_modes=modes, coil_sets=isempty(coil_sets) ? preloaded_coil_sets : coil_sets, regularization_width=Float64(regularization_width)) isempty(resp.permeability_flux) || apply_response!(state; verbose) @@ -157,67 +156,51 @@ function compute_perturbed_equilibrium( end """ - materialize_forcing_modes(ffs, forcing; preloaded_coil_sets=CoilSet[], verbose=false) + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingCoils; preloaded_coil_sets=CoilSet[], verbose=false) -> (modes::Vector{ForcingMode}, coil_sets::Vector{CoilSet}) -Pure computation of the control-surface forcing spectrum: turn a forcing description into -fresh `ForcingMode`s, for every toroidal mode of the solve and in the unit-norm convention -the response step consumes. Nothing is mutated — the caller owns where the result lands. - -Coil formats build the geometry (or reuse `preloaded_coil_sets` from the gpec.h5 replay -path) and integrate the Biot-Savart field on the control surface; file formats read the -modes from `forcing_data_file` and convert their normalization onto the run's `mlow:mhigh`. Both branches evaluate on -`ffs.psilim`, the integration limit. The second return value is the coil geometry actually -used (empty for file formats), which the writer snapshots for replay. +Pure computation of the control-surface forcing spectrum of a coil leaf: build the geometry (or reuse +`preloaded_coil_sets` from the gpec.h5 replay path), integrate the Biot-Savart field on the control surface at +`ffs.psilim`, the integration limit, for every toroidal mode of the solve, and apply the leaf's weight. Modes are in +the unit-norm convention the response step consumes. The second return value is the coil geometry used, which the +writer snapshots for replay. Every `materialize_forcing_modes` method returns fresh modes and mutates nothing. """ function materialize_forcing_modes( ffs::ForceFreeStatesResult, - forcing::ForcingTerms.ForcingTermsControl; + field::ForcingTerms.ForcingCoils; preloaded_coil_sets::Vector{ForcingTerms.CoilSet}=ForcingTerms.CoilSet[], verbose::Bool=false ) - equil = ffs.equil + equil, cfg = ffs.equil, field.config + coil_sets = isempty(preloaded_coil_sets) ? ForcingTerms.load_coil_sets(cfg, ffs.nlow; equil=equil) : preloaded_coil_sets modes = ForcingMode[] - coil_sets = ForcingTerms.CoilSet[] - - if forcing.forcing_data_format == "coil" - cfg = ForcingTerms.CoilConfig(forcing) - coil_sets = isempty(preloaded_coil_sets) ? - ForcingTerms.load_coil_sets(cfg, ffs.nlow; equil=equil) : preloaded_coil_sets - for n in ffs.nlow:ffs.nhigh - modes_n = ForcingMode[] - ForcingTerms.compute_coil_forcing_modes!( - modes_n, coil_sets, equil, cfg, n, ffs.mlow, ffs.mhigh; - psi=ffs.psilim, verbose=verbose - ) - append!(modes, modes_n) - end - else - file_modes = ForcingMode[] - norm_tag = load_forcing_data!(file_modes, forcing.forcing_data_file, forcing.forcing_data_format, verbose) - for n in ffs.nlow:ffs.nhigh - modes_n = filter(m -> m.n == n, file_modes) - isempty(modes_n) && continue - # Normalize on the same control surface as the coil branch: psilim, the integration limit. - append!(modes, convert_forcing_normalization(modes_n, norm_tag, equil, n, ffs.mlow:ffs.mhigh; psi=ffs.psilim)) - end + for n in ffs.nlow:ffs.nhigh + modes_n = ForcingMode[] + ForcingTerms.compute_coil_forcing_modes!(modes_n, coil_sets, equil, cfg, n, ffs.mlow, ffs.mhigh; psi=ffs.psilim, verbose=verbose) + append!(modes, modes_n) end - + field.scale == 1 || (modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in modes]) return modes, coil_sets end """ - materialize_forcing_modes(ffs, field::ForcingTerms.ForcingSource; kwargs...) -> (modes, coil_sets) + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingFile; verbose=false, kwargs...) -> (modes, coil_sets) -Materialize a single-source [`ForcingTerms.ForcingField`](@ref) leaf and apply its weight. The -returned modes are fresh objects, so weighting never reaches back into any caller state. +Materialize a forcing-mode file: read its modes, convert their normalization onto the run's `mlow:mhigh` on the +control surface `ffs.psilim`, and apply the leaf's weight. No coil geometry is produced. """ -function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTerms.ForcingSource; kwargs...) - modes, coil_sets = materialize_forcing_modes(ffs, field.ctrl; kwargs...) - if field.scale != 1 - modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in modes] +function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTerms.ForcingFile; verbose::Bool=false, kwargs...) + file_modes = ForcingMode[] + norm_tag = load_forcing_data!(file_modes, field.path, field.format, verbose) + modes = ForcingMode[] + for n in ffs.nlow:ffs.nhigh + modes_n = filter(m -> m.n == n, file_modes) + isempty(modes_n) && continue + # Normalize on the same control surface as the coil field: psilim, the integration limit. + append!(modes, convert_forcing_normalization(modes_n, norm_tag, ffs.equil, n, ffs.mlow:ffs.mhigh; psi=ffs.psilim)) end - return modes, coil_sets + field.scale == 1 || (modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in modes]) + return modes, ForcingTerms.CoilSet[] end """ diff --git a/src/PerturbedEquilibrium/TorqueResponse.jl b/src/PerturbedEquilibrium/TorqueResponse.jl index 6eb4478796..62935ba2ba 100644 --- a/src/PerturbedEquilibrium/TorqueResponse.jl +++ b/src/PerturbedEquilibrium/TorqueResponse.jl @@ -126,28 +126,22 @@ end Contract the torque response of `state.response` with the forcing of `state` into `state.torque_response`. Every forcing source is one column of `T_source`: each coil set -(`state.coil_sets`, on the grid `forcing` carries) when the forcing is coils, otherwise the -applied spectrum as a single source named after its forcing file. A source's Φ_x column is +(`state.coil_sets`, on the grid `forcing` carries) when the forcing is a coil leaf, otherwise the +applied spectrum as a single source, named after its forcing file when it is one. A source's Φ_x column is referred to b̃ through `R = S·A`, so `T_source = B̃†·T_xe·B̃` with `B̃ = R⁻¹·Φ_source` (the Fortran `gcoil`). """ -function apply_torque_response!( - state::PerturbedEquilibriumState, - forcing::Union{ForcingTerms.ForcingTermsControl,ForcingTerms.ForcingField}; - verbose::Bool=false -) +function apply_torque_response!(state::PerturbedEquilibriumState, forcing::ForcingTerms.ForcingField; verbose::Bool=false) resp = state.response ffs = resp.ffs - ft_ctrl = forcing isa ForcingTerms.ForcingTermsControl ? forcing : - forcing isa ForcingTerms.ForcingSource ? forcing.ctrl : nothing source_b = zeros(ComplexF64, ffs.numpert_total, 0) source_names = String[] - if !isempty(state.coil_sets) && ft_ctrl !== nothing && ft_ctrl.forcing_data_format == "coil" + if forcing isa ForcingTerms.ForcingCoils && !isempty(state.coil_sets) flux_conform = resp.rootarea_to_area_weight .* resp.surface_area - source_b = flux_conform \ coil_flux_spectra(ffs, state.coil_sets, ForcingTerms.CoilConfig(ft_ctrl)) + source_b = flux_conform \ coil_flux_spectra(ffs, state.coil_sets, forcing.config) source_names = [cs.name for cs in state.coil_sets] elseif !isempty(state.forcing_b_rootarea) source_b = reshape(state.forcing_b_rootarea, :, 1) - source_names = [ft_ctrl === nothing ? "forcing" : basename(ft_ctrl.forcing_data_file)] + source_names = [forcing isa ForcingTerms.ForcingFile ? basename(forcing.path) : "forcing"] end T_xe = resp.T_xe diff --git a/src/PerturbedEquilibrium/Utils.jl b/src/PerturbedEquilibrium/Utils.jl index ed3fa6a65a..b175cba1bf 100644 --- a/src/PerturbedEquilibrium/Utils.jl +++ b/src/PerturbedEquilibrium/Utils.jl @@ -211,9 +211,9 @@ end function _record_forcing_snapshot!(file, state::PerturbedEquilibriumState) forcing = state.forcing forcing === nothing && return nothing - snapshot = forcing isa ForcingTerms.ForcingSource && forcing.scale == 1 ? ForcingTerms.snapshot_forcing_modes(forcing.ctrl) : + forcing isa ForcingTerms.ForcingCoils && forcing.scale == 1 && return nothing + snapshot = forcing isa ForcingTerms.ForcingFile && forcing.scale == 1 ? ForcingTerms.snapshot_forcing_modes(forcing) : (state.forcing_modes, "unit_flux") - snapshot === nothing && return nothing modes, normalization = snapshot ForcingTerms.save_forcing_to_h5(modes, replace_group!(file, "Input/RawInputs/ForcingTerms"); normalization) return nothing diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index f57f8a0f38..431b53f1ba 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -314,18 +314,29 @@ include("display_check.jl") end @testset "ForcingField infers its format and carries its scale" begin - @test ForcingField(table).ctrl.forcing_data_format == "ascii" - @test ForcingField(table_h5).ctrl.forcing_data_format == "hdf5" - @test isabspath(ForcingField(table).ctrl.forcing_data_file) + @test ForcingField(table) isa GPEC.ForcingTerms.ForcingFile + @test ForcingField(table).format == "ascii" + @test ForcingField(table_h5).format == "hdf5" + @test isabspath(ForcingField(table).path) @test ForcingField(table; scale=3.0).scale == 3.0 # One coil set or several, as NamedTuples or Dicts with the [[ForcingTerms.coil_set]] keys. c_coil = (name="c", currents=[1e3, 500, -500, -1e3, -500, 500]) coil_field = ForcingField(c_coil; machine="d3d") - @test coil_field.ctrl.forcing_data_format == "coil" - @test coil_field.ctrl.machine == "d3d" - @test coil_field.ctrl.coil_sets_raw == [Dict{String,Any}("name" => "c", "currents" => c_coil.currents)] - @test length(ForcingField([c_coil, Dict("name" => "iu", "currents" => fill(1e3, 6))]; machine="d3d").ctrl.coil_sets_raw) == 2 + @test coil_field isa GPEC.ForcingTerms.ForcingCoils + @test coil_field.config.machine == "d3d" + @test [sc.name for sc in coil_field.config.coil_sets] == ["c"] + @test coil_field.config.coil_sets[1].currents == c_coil.currents + @test length(ForcingField([c_coil, Dict("name" => "iu", "currents" => fill(1e3, 6))]; machine="d3d").config.coil_sets) == 2 + @test ForcingField(coil_field.config) isa GPEC.ForcingTerms.ForcingCoils @test repr(coil_field) == "ForcingField(d3d coils c)" + # A source's [ForcingTerms] table builds the same source back; the bundled geometry directory stays implicit. + coil_table = GPEC._forcing_table(coil_field) + @test !haskey(coil_table, "dat_dir") + rebuilt = ForcingField(GPEC.forcing_terms_control(Dict{String,Any}("ForcingTerms" => coil_table), forcing_dir)) + @test rebuilt.config.machine == "d3d" && rebuilt.config.dat_dir == coil_field.config.dat_dir + @test [(sc.name, sc.currents) for sc in rebuilt.config.coil_sets] == [(sc.name, sc.currents) for sc in coil_field.config.coil_sets] + file_table = GPEC._forcing_table(ForcingField(table_h5)) + @test ForcingField(GPEC.forcing_terms_control(Dict{String,Any}("ForcingTerms" => file_table), forcing_dir)).path == table_h5 end @testset "ForcingField checks its source when built" begin diff --git a/test/runtests_torque_response.jl b/test/runtests_torque_response.jl index a7ee1a1165..542fd978f6 100644 --- a/test/runtests_torque_response.jl +++ b/test/runtests_torque_response.jl @@ -146,8 +146,8 @@ compute_torque_response = true # Build the ψ-resolved torque response @testset "forcing-source matrix: a forcing file is one source" begin file_state = deepcopy(pe) - file_ctrl = _GPE_TR.ForcingTerms.ForcingTermsControl(; forcing_data_file="forcing.dat") - _PE_TR.apply_torque_response!(file_state, file_ctrl) + file_source = _GPE_TR.ForcingTerms.ForcingFile(abspath("forcing.dat"), "ascii", 1) + _PE_TR.apply_torque_response!(file_state, file_source) ts = file_state.torque_response @test ts.source_names == ["forcing.dat"] @test size(ts.T_source) == (1, 1, npsi) From 5c9055410b246b74b746150bb03c0b9efdcfc805 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 15:10:04 +0100 Subject: [PATCH 20/27] ForcingTerms - FEATURE - Add magnetic materials and the exact field of uniformly magnetized polyhedra --- src/ForcingTerms/ForcingTerms.jl | 2 + src/ForcingTerms/MagneticMaterial.jl | 271 +++++++++++++++++++++++++++ test/runtests_magnetic_material.jl | 164 ++++++++++++++++ test/suites.jl | 1 + 4 files changed, 438 insertions(+) create mode 100644 src/ForcingTerms/MagneticMaterial.jl create mode 100644 test/runtests_magnetic_material.jl diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index 01da33e910..e7fc69b212 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -4,6 +4,7 @@ module ForcingTerms using DelimitedFiles using HDF5 using LinearAlgebra +using StaticArrays: SVector import ..Equilibrium import ..Utilities.FourierTransforms @@ -203,6 +204,7 @@ end # Coil-forcing helpers; these depend on ForcingTermsControl and ForcingMode defined above. include("CoilGeometry.jl") include("BiotSavart.jl") +include("MagneticMaterial.jl") include("CoilFourier.jl") """ diff --git a/src/ForcingTerms/MagneticMaterial.jl b/src/ForcingTerms/MagneticMaterial.jl new file mode 100644 index 0000000000..e9a6c8d662 --- /dev/null +++ b/src/ForcingTerms/MagneticMaterial.jl @@ -0,0 +1,271 @@ +""" + MagneticMaterial + +A set of ferromagnetic (ferritic) elements, each a closed triangulated polyhedron that is uniformly magnetized. Each +element's volume and centroid are computed from its own surface at construction, which also checks that every +element is closed and outward-oriented. + +## Fields + + - `name::String` - Set identifier, e.g. `"iter_inserts"`. + - `vertices::Matrix{Float64}` - Vertex coordinates `[3, nvertex]` (x, y, z) in metres, in the same machine Cartesian frame as the coil geometry. + - `triangles::Matrix{Int}` - Vertex indices (1-based) of each triangle `[3, ntriangle]`, ordered counterclockwise seen from outside the element. + - `element_offsets::Vector{Int}` - Triangle offsets `[nelement + 1]`, from 0: element `e` is triangles `element_offsets[e]+1:element_offsets[e+1]`. + - `saturation_field::Float64` - Saturation magnetization μ₀M_s of the material, in tesla. + - `fill_fraction::Float64` - Fraction of each element's volume that is magnetic material, in (0, 1]. + - `volume::Vector{Float64}` - Volume of each element `[nelement]`, in m³. + - `centroid::Matrix{Float64}` - Centroid of each element `[3, nelement]`, in metres. +""" +struct MagneticMaterial + name::String + vertices::Matrix{Float64} + triangles::Matrix{Int} + element_offsets::Vector{Int} + saturation_field::Float64 + fill_fraction::Float64 + volume::Vector{Float64} + centroid::Matrix{Float64} + function MagneticMaterial(name, vertices, triangles, element_offsets, saturation_field, fill_fraction) + label = "magnetic material \"$name\"" + size(vertices, 1) == 3 || throw(ArgumentError("$label: vertices must be 3 × nvertex, got $(size(vertices))")) + size(triangles, 1) == 3 || throw(ArgumentError("$label: triangles must be 3 × ntriangle, got $(size(triangles))")) + all(isfinite, vertices) || throw(ArgumentError("$label: vertices must be finite")) + all(i -> 1 <= i <= size(vertices, 2), triangles) || throw(ArgumentError("$label: a triangle indexes a vertex outside 1:$(size(vertices, 2))")) + length(element_offsets) >= 2 && first(element_offsets) == 0 && last(element_offsets) == size(triangles, 2) && issorted(element_offsets) || + throw(ArgumentError("$label: element_offsets must rise from 0 to the triangle count $(size(triangles, 2))")) + isfinite(saturation_field) && saturation_field > 0 || throw(ArgumentError("$label: saturation_field must be positive, μ₀M_s in tesla")) + 0 < fill_fraction <= 1 || throw(ArgumentError("$label: fill_fraction must be in (0, 1], got $fill_fraction")) + saturation_field > MAX_SATURATION_FIELD && + @warn "$label: saturation_field = $saturation_field T exceeds any steel's μ₀M_s; is it M_s in A/m rather than μ₀M_s in tesla?" + nelement = length(element_offsets) - 1 + volume, centroid = zeros(nelement), zeros(3, nelement) + for e in 1:nelement + tris = (element_offsets[e]+1):element_offsets[e+1] + isempty(tris) && throw(ArgumentError("$label: element $e has no triangles")) + _check_closed(triangles, tris) || throw(ArgumentError("$label: element $e is not a closed, consistently oriented surface")) + # Divergence theorem: each triangle and the origin span a signed tetrahedron. + for t in tris + a, b, c = (view(vertices, :, triangles[k, t]) for k in 1:3) + v = dot(a, cross(b, c)) / 6 + volume[e] += v + centroid[:, e] .+= v .* (a .+ b .+ c) ./ 4 + end + volume[e] > 0 || throw(ArgumentError("$label: element $e has volume $(volume[e]) m³; its triangles must face outward")) + centroid[:, e] ./= volume[e] + end + return new(String(name), vertices, triangles, element_offsets, saturation_field, fill_fraction, volume, centroid) + end +end + +# μ₀M_s of iron is 2.15 T; anything above this is not a ferromagnetic steel. +const MAX_SATURATION_FIELD = 2.5 + +# A closed, consistently oriented surface uses every directed edge exactly once and its reverse exactly once. +function _check_closed(triangles, tris) + edges = Dict{Tuple{Int,Int},Int}() + for t in tris, k in 1:3 + edge = (triangles[k, t], triangles[mod1(k + 1, 3), t]) + edges[edge] = get(edges, edge, 0) + 1 + end + return all(n == 1 && get(edges, reverse(edge), 0) == 1 for (edge, n) in edges) +end + +""" + MagneticMaterialConfig + +One `[[ForcingTerms.magnetic_material]]` TOML block. + +## Fields + + - `name::String` - Set to read from the geometry file, and its identifier. + - `h5_file::String` - Geometry file holding `magnetic_material//`; see [`read_magnetic_material_h5`](@ref). + - `saturation_field::Float64` - Saturation magnetization μ₀M_s of the material, in tesla. + - `fill_fraction::Float64` - Fraction of each element's volume that is magnetic material (default 1). +""" +Base.@kwdef struct MagneticMaterialConfig + name::String = "" + h5_file::String = "" + saturation_field::Float64 = NaN + fill_fraction::Float64 = 1.0 +end + +function _parse_magnetic_material_config(d::AbstractDict) + known = Set(String.(fieldnames(MagneticMaterialConfig))) + unknown = sort([String(k) for k in keys(d) if !(String(k) in known)]) + isempty(unknown) || throw(ArgumentError("unknown keys $(unknown) in [[ForcingTerms.magnetic_material]]. Known: $(sort(collect(known))).")) + return MagneticMaterialConfig(; (Symbol(k) => v for (k, v) in d)...) +end + +""" + load_magnetic_material(cfg::MagneticMaterialConfig) -> MagneticMaterial + +Read the set `cfg.name` from `cfg.h5_file` and give it the material properties of `cfg`. +""" +function load_magnetic_material(cfg::MagneticMaterialConfig) + isempty(cfg.h5_file) && throw(ArgumentError("[[ForcingTerms.magnetic_material]] \"$(cfg.name)\" needs an h5_file")) + isnan(cfg.saturation_field) && throw(ArgumentError("[[ForcingTerms.magnetic_material]] \"$(cfg.name)\" needs a saturation_field (μ₀M_s in tesla)")) + g = only(read_magnetic_material_h5(cfg.h5_file; set=cfg.name)) + return MagneticMaterial(g.name, g.vertices, g.triangles, g.element_offsets, cfg.saturation_field, cfg.fill_fraction) +end + +# HDF5 layout of a magnetic material set (Julia order; h5py sees each array transposed): +# //vertices Float64[3, nvertex], metres +# //triangles Int[3, ntriangle], 0-based vertex indices, counterclockwise seen from outside +# //element_offsets Int[nelement + 1], 0-based triangle offsets +# / attrs saturation_field (T), fill_fraction; optional in geometry files + +""" + save_magnetic_material_to_h5(materials::Vector{MagneticMaterial}, group) + +Write each set as a subgroup (named by its `name`) under an already-open HDF5 `group`, with 0-based indices. Inverse +of [`load_magnetic_material_from_h5_group!`](@ref). +""" +function save_magnetic_material_to_h5(materials::Vector{MagneticMaterial}, group) + for mat in materials + g = create_group(group, mat.name) + g["vertices"] = mat.vertices + g["triangles"] = mat.triangles .- 1 + g["element_offsets"] = mat.element_offsets + HDF5.attrs(g)["saturation_field"] = mat.saturation_field + HDF5.attrs(g)["fill_fraction"] = mat.fill_fraction + end + return nothing +end + +""" + load_magnetic_material_from_h5_group!(materials, group) -> Vector{MagneticMaterial} + +Populate `materials` from an already-open HDF5 `group`, one set per subgroup holding `vertices`, `triangles` and +`element_offsets`. A set without `saturation_field`/`fill_fraction` attributes (a geometry-only file) gets +μ₀M_s = 1 T and fill fraction 1, to be replaced by its deck block. Mirror of [`save_magnetic_material_to_h5`](@ref). +""" +function load_magnetic_material_from_h5_group!(materials::Vector{MagneticMaterial}, group) + empty!(materials) + for key in keys(group) + sub = group[key] + (sub isa HDF5.Group && all(haskey(sub, k) for k in ("vertices", "triangles", "element_offsets"))) || continue + attrs = HDF5.attrs(sub) + saturation_field = haskey(attrs, "saturation_field") ? Float64(attrs["saturation_field"]) : 1.0 + fill_fraction = haskey(attrs, "fill_fraction") ? Float64(attrs["fill_fraction"]) : 1.0 + push!( + materials, + MagneticMaterial(String(key), Float64.(read(sub, "vertices")), Int.(read(sub, "triangles")) .+ 1, + Int.(read(sub, "element_offsets")), saturation_field, fill_fraction) + ) + end + return materials +end + +""" + read_magnetic_material_h5(filepath; group="magnetic_material", set=nothing) -> Vector{MagneticMaterial} + +Read the magnetic material sets under `group` of `filepath`, or only the one named `set`. Each set is a subgroup +holding `vertices` (`3 × nvertex` in Julia order, `nvertex × 3` as h5py writes it, in metres), `triangles` (0-based +vertex indices, counterclockwise seen from outside) and `element_offsets` (0-based triangle offsets, `nelement + 1`), +so one machine file can also hold `coils/`. +""" +function read_magnetic_material_h5(filepath::AbstractString; group::String="magnetic_material", set::Union{Nothing,String}=nothing) + isfile(filepath) || throw(ArgumentError("magnetic material file not found: $filepath")) + return h5open(filepath, "r") do file + haskey(file, group) || throw(ArgumentError("$filepath has no '$group' group")) + materials = load_magnetic_material_from_h5_group!(MagneticMaterial[], file[group]) + isempty(materials) && throw(ArgumentError("no magnetic material sets under '$group' in $filepath")) + set === nothing && return materials + idx = findfirst(m -> m.name == set, materials) + idx === nothing && throw(ArgumentError("magnetic material set '$set' not found under '$group' in $filepath; it has $(join([m.name for m in materials], ", "))")) + return MagneticMaterial[materials[idx]] + end +end + +""" + write_magnetic_material_h5(filepath, materials; group="magnetic_material") + +Write `materials` to a new HDF5 file under `group`, one subgroup per set. +""" +function write_magnetic_material_h5(filepath::AbstractString, materials::Vector{MagneticMaterial}; group::String="magnetic_material") + h5open(file -> save_magnetic_material_to_h5(materials, create_group(file, group)), filepath, "w") + return filepath +end + +""" + compute_magnetic_material_field!(B_R, B_phi, B_Z, obs_R, obs_phi, obs_Z, material, magnetization) + +Exact field of `material` with each element uniformly magnetized, `magnetization` `[3, nelement]` (Cartesian, A/m), +at observation points outside the material given in cylindrical coordinates (m, rad, m), as cylindrical components +in tesla. Uniform M is a surface charge σ = M·n̂ on each face, and a flat triangle with constant charge has a +closed-form field: ∫ (r − r′)/|r − r′|³ dA′ = n̂ Ω + Σ_edges m̂ₑ ln[(R₁ + R₂ + ℓ)/(R₁ + R₂ − ℓ)], with Ω the signed +solid angle the triangle subtends (Van Oosterom & Strackee, IEEE Trans. Biomed. Eng. 30, 125 (1983)) and m̂ₑ its +outward in-plane edge normals. Then B = μ₀/4π · Σ_faces σ (n̂ Ω + Σ_edges m̂ₑ Lₑ). Threaded over observation points; +the outputs are overwritten. +""" +function compute_magnetic_material_field!( + B_R::AbstractVector{Float64}, + B_phi::AbstractVector{Float64}, + B_Z::AbstractVector{Float64}, + obs_R::AbstractVector{Float64}, + obs_phi::AbstractVector{Float64}, + obs_Z::AbstractVector{Float64}, + material::MagneticMaterial, + magnetization::AbstractMatrix{<:Real} +) + nobs = length(obs_R) + @assert length(obs_phi) == nobs && length(obs_Z) == nobs + @assert length(B_R) == nobs && length(B_phi) == nobs && length(B_Z) == nobs + nelement = length(material.element_offsets) - 1 + size(magnetization) == (3, nelement) || throw(DimensionMismatch("magnetization must be 3 × $nelement, got $(size(magnetization))")) + faces = _charged_faces(material, magnetization) + Threads.@threads for i in 1:nobs + sp, cp = sincos(obs_phi[i]) + r = SVector(obs_R[i] * cp, obs_R[i] * sp, obs_Z[i]) + H = zero(SVector{3,Float64}) + for f in faces + H += f.σ * _triangle_kernel(r, f) + end + B_R[i] = MU0_OVER_4PI * (H[1] * cp + H[2] * sp) + B_phi[i] = MU0_OVER_4PI * (-H[1] * sp + H[2] * cp) + B_Z[i] = MU0_OVER_4PI * H[3] + end + return nothing +end + +# A triangle with its unit normal, outward in-plane edge normals, edge lengths and surface charge σ = M·n̂. +struct _ChargedFace + v::NTuple{3,SVector{3,Float64}} + n::SVector{3,Float64} + m::NTuple{3,SVector{3,Float64}} + len::NTuple{3,Float64} + σ::Float64 +end + +function _charged_faces(material::MagneticMaterial, magnetization) + faces = _ChargedFace[] + for e in 1:(length(material.element_offsets)-1) + M = SVector{3,Float64}(magnetization[1, e], magnetization[2, e], magnetization[3, e]) + iszero(M) && continue + for t in (material.element_offsets[e]+1):material.element_offsets[e+1] + v = ntuple(k -> SVector{3,Float64}(view(material.vertices, :, material.triangles[k, t])), 3) + normal = cross(v[2] - v[1], v[3] - v[1]) + n = normal / norm(normal) + σ = dot(M, n) + σ == 0 && continue + tangents = ntuple(k -> v[mod1(k + 1, 3)] - v[k], 3) + push!(faces, _ChargedFace(v, n, ntuple(k -> cross(tangents[k], n) / norm(tangents[k]), 3), ntuple(k -> norm(tangents[k]), 3), σ)) + end + end + return faces +end + +# ∫ (r − r′)/|r − r′|³ dA′ over a flat triangle: the signed solid angle along n̂ plus the edge terms. +@inline function _triangle_kernel(r, f::_ChargedFace) + a, b, c = f.v[1] - r, f.v[2] - r, f.v[3] - r + na, nb, nc = norm(a), norm(b), norm(c) + # Van Oosterom & Strackee: positive when r is on the side n̂ points to. + Ω = -2 * atan(dot(a, cross(b, c)), na * nb * nc + dot(a, b) * nc + dot(a, c) * nb + dot(b, c) * na) + R = (na, nb, nc) + edges = sum(f.m[k] * log((R[k] + R[mod1(k + 1, 3)] + f.len[k]) / (R[k] + R[mod1(k + 1, 3)] - f.len[k])) for k in 1:3) + return Ω * f.n + edges +end + +export MagneticMaterial, MagneticMaterialConfig, load_magnetic_material +export read_magnetic_material_h5, write_magnetic_material_h5, save_magnetic_material_to_h5, load_magnetic_material_from_h5_group! +export compute_magnetic_material_field! diff --git a/test/runtests_magnetic_material.jl b/test/runtests_magnetic_material.jl new file mode 100644 index 0000000000..8c474dc9ee --- /dev/null +++ b/test/runtests_magnetic_material.jl @@ -0,0 +1,164 @@ +using Test +using HDF5 +using LinearAlgebra +using GeneralizedPerturbedEquilibrium +using GeneralizedPerturbedEquilibrium.ForcingTerms + +const MU0 = 4π * 1e-7 + +# The 12 outward, counterclockwise triangles of a box with corners 1(−,−,−) 2(+,−,−) 3(+,+,−) 4(−,+,−) 5..8 (same, +z). +const BOX_TRIANGLES = [1 4 3; 1 3 2; 5 6 7; 5 7 8; 1 2 6; 1 6 5; 2 3 7; 2 7 6; 3 4 8; 3 8 7; 4 1 5; 4 5 8]' + +# Box corners [3, 8] with half-sizes `h`, rotated by `Q` and centred at `c`. +box_vertices(h; c=zeros(3), Q=I(3)) = + reduce(hcat, [c .+ Q * (h .* s) for s in ([-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1])]) + +# One magnetic material from a list of boxes, each `(h, c, Q)`. +function box_material(boxes; saturation_field=1.7, fill_fraction=1.0) + vertices = reduce(hcat, [box_vertices(h; c, Q) for (h, c, Q) in boxes]) + triangles = reduce(hcat, [BOX_TRIANGLES .+ 8(i - 1) for i in eachindex(boxes)]) + return MagneticMaterial("boxes", vertices, triangles, collect(0:12:12length(boxes)), saturation_field, fill_fraction) +end + +# Cylindrical (B_R, B_phi, B_Z) of `material` magnetized by `M` [3, nelement] at Cartesian points `obs` [3, nobs]. +function material_field(material, M, obs) + B = (zeros(size(obs, 2)), zeros(size(obs, 2)), zeros(size(obs, 2))) + compute_magnetic_material_field!(B..., hypot.(obs[1, :], obs[2, :]), atan.(obs[2, :], obs[1, :]), obs[3, :], material, M) + return B +end + +# The same field as Cartesian vectors, one column per point. +function cartesian_field(material, M, obs) + BR, Bφ, BZ = material_field(material, M, obs) + φ = atan.(obs[2, :], obs[1, :]) + return vcat((BR .* cos.(φ) .- Bφ .* sin.(φ))', (BR .* sin.(φ) .+ Bφ .* cos.(φ))', BZ') +end + +# Observation points on a sphere of radius d about `c`. +sphere_points(d; c=zeros(3)) = reduce(hcat, [c .+ d .* [sin(t) * cos(p), sin(t) * sin(p), cos(t)] for t in (0.3, 1.1, 1.9, 2.8) for p in (0.2, 1.7, 3.4, 5.0)]) + +@testset "Magnetic material" begin + h = [0.29, 0.235, 0.0195] # an ITER insert plate, 0.58 × 0.47 × 0.039 m + plate = box_material([(h, zeros(3), I(3))]) + Ms = 1.7 / MU0 + + @testset "element volume and centroid from the closed surface" begin + shifted = box_material([(h, [9.0, 1.0, 0.5], I(3)), (2h, [-3.0, 0.0, 2.0], I(3))]) + @test shifted.volume ≈ [8prod(h), 64prod(h)] rtol = 1e-12 + @test shifted.centroid ≈ [9.0 -3.0; 1.0 0.0; 0.5 2.0] atol = 1e-12 + end + + @testset "face charges: closed form against quadrature, at close range and far" begin + # B = μ₀/4π Σ σ ∫(r − r′)/|r − r′|³ dA′ by midpoint quadrature on each face, with an oblique M charging all six. + M = Ms .* normalize([0.3, -0.5, 0.8]) + V = box_vertices(h) + function quadrature(r; n=600) + H = zeros(3) + for f in 1:2:12 + # Triangles (a, b, c) and (a, c, d) make the face a-b-c-d; b - a and d - a span it, outward-oriented. + a, b, d = V[:, BOX_TRIANGLES[1, f]], V[:, BOX_TRIANGLES[2, f]], V[:, BOX_TRIANGLES[3, f+1]] + e1, e2 = b .- a, d .- a + σ, dA = dot(M, normalize(cross(e1, e2))), norm(cross(e1, e2)) / n^2 + for i in 1:n, j in 1:n + s = r .- (a .+ ((i - 0.5) / n) .* e1 .+ ((j - 0.5) / n) .* e2) + H .+= σ * dA .* s ./ norm(s)^3 + end + end + return MU0 / 4π .* H + end + obs = [0.05 0.40 -0.20 1.5; -0.03 0.10 0.30 -0.8; 0.06 -0.05 0.10 0.9] # 4 cm above the plate, beside it, and far + Bq = reduce(hcat, [quadrature(obs[:, k]) for k in axes(obs, 2)]) + @test cartesian_field(plate, reshape(M, 3, 1), obs) ≈ Bq rtol = 1e-4 + end + + @testset "uniform M equals its bound surface current: against the coil kernel" begin + # Magnetized along a box axis, the box is a sheet of M amperes per metre on the faces parallel to M (K = M × n̂). + obs = sphere_points(0.6) + for axis in (1, 3) + i, j = mod1(axis + 1, 3), mod1(axis + 2, 3) + nloop = 2000 + pts(s, u, v) = (p = zeros(3); p[i] = u * h[i]; p[j] = v * h[j]; p[axis] = -h[axis] + (s - 0.5) * 2h[axis] / nloop; p) + corners = [(-1, -1), (1, -1), (1, 1), (-1, 1), (-1, -1)] + X, Y, Z = (reshape([pts(s, u, v)[k] for s in 1:nloop, (u, v) in corners], nloop, 1, 5) for k in 1:3) + sheet = CoilSet("sheet", nloop, 1, 1.0, 5, X, Y, Z, fill(Ms * 2h[axis] / nloop, nloop)) + Bc = (zeros(size(obs, 2)), zeros(size(obs, 2)), zeros(size(obs, 2))) + compute_biot_savart_boundary!(Bc..., hypot.(obs[1, :], obs[2, :]), atan.(obs[2, :], obs[1, :]), obs[3, :], [sheet]) + M = zeros(3, 1) + M[axis] = Ms + Bm = material_field(plate, M, obs) + scale = maximum(maximum(abs, b) for b in Bc) + @test maximum(maximum(abs, bm .- bc) for (bm, bc) in zip(Bm, Bc)) < 1e-6 * scale + end + end + + @testset "far away a magnetized element is the point dipole m = M·V" begin + M = Ms .* normalize([1.0, 0.4, -0.7]) + m = M .* plate.volume[1] + function dipole_error(d) + obs = sphere_points(d) + Bm = cartesian_field(plate, reshape(M, 3, 1), obs) + Bd = reduce(hcat, [MU0 / 4π .* (3dot(m, r) .* r ./ norm(r)^5 .- m ./ norm(r)^3) for r in eachcol(obs)]) + return maximum(norm.(eachcol(Bm .- Bd))) / maximum(norm.(eachcol(Bd))) + end + e3, e30 = dipole_error(3.0), dipole_error(30.0) + @test e30 < 1e-3 + @test e30 < e3 / 50 # the finite-size correction falls as (size/d)² + end + + @testset "a toroidally magnetized ring of plates drives only n = k·N, and vanishes as N grows" begin + # An axisymmetric body magnetized along φ̂ has no external field; only its discreteness drives one. + R0, R1, Z1 = 2.0, 1.4, 0.3 + function ring_field(N, nobs) + φs = 2π .* (0:N-1) ./ N + rot(φ) = [cos(φ) -sin(φ) 0; sin(φ) cos(φ) 0; 0 0 1] + ring = box_material([([0.04, 2π * R0 / (3N), 0.03], R0 .* [cos(φ), sin(φ), 0.0], rot(φ)) for φ in φs]) + M = Ms .* vcat((-sin.(φs))', cos.(φs)', zeros(1, N)) + ψ = 2π .* (0:nobs-1) ./ nobs + B = (zeros(nobs), zeros(nobs), zeros(nobs)) + compute_magnetic_material_field!(B..., fill(R1, nobs), collect(ψ), fill(Z1, nobs), ring, M) + return ψ, B + end + harmonic(ψ, f, n) = abs(sum(f .* cis.(-n .* ψ))) / length(ψ) + N = 12 + ψ, B = ring_field(N, 8N) + for f in B + @test all(harmonic(ψ, f, n) < 1e-10 * maximum(abs, f) for n in 1:N-1) + end + @test harmonic(ψ, B[1], N) > 1e-3 * maximum(abs, B[1]) + peak(N) = maximum(maximum(abs, f) for f in ring_field(N, 8N)[2]) + @test peak(24) < peak(12) / 10 + end + + @testset "construction checks, HDF5 round trip and deck blocks" begin + V = box_vertices(h) + @test_throws "not a closed" MagneticMaterial("open", V, BOX_TRIANGLES[:, 1:11], [0, 11], 1.7, 1.0) + @test_throws "must face outward" MagneticMaterial("inside-out", V, BOX_TRIANGLES[[1, 3, 2], :], [0, 12], 1.7, 1.0) + @test_throws "element_offsets" MagneticMaterial("x", V, BOX_TRIANGLES, [0, 11], 1.7, 1.0) + @test_throws "fill_fraction" MagneticMaterial("x", V, BOX_TRIANGLES, [0, 12], 1.7, 1.5) + @test_throws "saturation_field" MagneticMaterial("x", V, BOX_TRIANGLES, [0, 12], 0.0, 1.0) + @test_logs (:warn, r"M_s in A/m") MagneticMaterial("x", V, BOX_TRIANGLES, [0, 12], 1.4e6, 1.0) + + dir = mktempdir() + two = box_material([(h, zeros(3), I(3)), (h, [1.0, 0, 0], I(3))]; saturation_field=1.6, fill_fraction=0.9) + path = write_magnetic_material_h5(joinpath(dir, "material.h5"), [two]) + h5open(path) do f + @test minimum(read(f, "magnetic_material/boxes/triangles")) == 0 # 0-based on disk + end + back = only(read_magnetic_material_h5(path; set="boxes")) + @test back.vertices == two.vertices && back.triangles == two.triangles && back.element_offsets == two.element_offsets + @test back.saturation_field == 1.6 && back.fill_fraction == 0.9 && back.volume ≈ two.volume + @test_throws "not found" read_magnetic_material_h5(path; set="missing") + + # A geometry-only file, as a CAD export writes it, takes its material from the deck block. + geometry = joinpath(dir, "geometry.h5") + h5open(geometry, "w") do f + g = create_group(create_group(f, "magnetic_material"), "plate") + g["vertices"], g["triangles"], g["element_offsets"] = V, BOX_TRIANGLES .- 1, [0, 12] + end + cfg = ForcingTerms._parse_magnetic_material_config(Dict{String,Any}("name" => "plate", "h5_file" => geometry, "saturation_field" => 1.6)) + loaded = load_magnetic_material(cfg) + @test loaded.saturation_field == 1.6 && loaded.fill_fraction == 1.0 && loaded.volume ≈ [8prod(h)] + @test_throws "unknown keys" ForcingTerms._parse_magnetic_material_config(Dict{String,Any}("name" => "plate", "mu0Ms" => 1.6)) + @test_throws "needs a saturation_field" load_magnetic_material(MagneticMaterialConfig(; name="plate", h5_file=geometry)) + end +end diff --git a/test/suites.jl b/test/suites.jl index 0b05f2b513..bbf0e6267b 100644 --- a/test/suites.jl +++ b/test/suites.jl @@ -55,6 +55,7 @@ const TEST_SUITES = [ "runtests_fullruns.jl" => "api", "runtests_torque_response.jl" => "api", "runtests_coils.jl" => "api", + "runtests_magnetic_material.jl" => "api", "runtests_imas.jl" => "api", "runtests_rerun_from_h5.jl" => "api", "runtests_deck_roundtrip.jl" => "api", From a1fefaf5d232b3eef108eb0990e1746967c8f6a0 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 22:43:25 +0100 Subject: [PATCH 21/27] Equilibrium - FEATURE - Evaluate the machine-frame equilibrium field outside the plasma equilibrium_field(equil, R, Z) returns (B_R, B_phi, B_Z) in T in the right-handed (R, phi, Z) frame of the source file, and the normalized flux, at arrays of machine coordinates. It works from the g-file or IMAS flux map psi(R, Z), rescaled to the axis as the solver does, with B_pol signed by the plasma current and B_phi = bt_sign F / R. F follows the profile inside the last closed flux surface and is the edge value outside it, including the private-flux region below an X-point. It errors for equilibria without a flux map outside the plasma and for points outside the flux grid, asking for a re-export on a larger grid. Tests check the flux and |B| on the outermost traced surface, Ampere's law against the g-file current, the sign against a coil hoop through the Biot-Savart kernel, sign reversal, F inside and outside the plasma, and both errors. Co-Authored-By: Claude Opus 5.5 --- src/Equilibrium/Derived/EquilibriumField.jl | 46 +++++++++++++++ src/Equilibrium/Equilibrium.jl | 3 +- test/runtests_equil.jl | 62 +++++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 src/Equilibrium/Derived/EquilibriumField.jl diff --git a/src/Equilibrium/Derived/EquilibriumField.jl b/src/Equilibrium/Derived/EquilibriumField.jl new file mode 100644 index 0000000000..4bf43dce03 --- /dev/null +++ b/src/Equilibrium/Derived/EquilibriumField.jl @@ -0,0 +1,46 @@ +""" + equilibrium_field(equil, R, Z) -> (; B_R, B_phi, B_Z, psi_norm) + +The equilibrium magnetic field in T at machine coordinates `R`, `Z` in m (arrays of one shape), in the +right-handed (R, φ, Z) frame of the source file, and the normalized poloidal flux there. It comes from the +file's flux map ψ(R, Z) and F profile; outside the last closed flux surface F takes its edge value. + +The equilibrium must come from a g-file or IMAS, and every point must lie inside its flux grid. +""" +function equilibrium_field(equil::PlasmaEquilibrium, R::AbstractArray{<:Real}, Z::AbstractArray{<:Real}) + ingest = equil.ingest + ingest isa DirectIngest || error("equilibrium_field needs the flux map outside the plasma, which only g-file " * + "and IMAS equilibria carry; eq_type = \"$(equil.config.eq_type)\" has none") + size(R) == size(Z) || throw(DimensionMismatch("R has size $(size(R)) and Z has size $(size(Z))")) + for (r, z) in zip(R, Z) + (ingest.rmin <= r <= ingest.rmax && ingest.zmin <= z <= ingest.zmax) || + error( + @sprintf("(R, Z) = (%.3f, %.3f) m lies outside the equilibrium's flux grid R ∈ [%.3f, %.3f], Z ∈ [%.3f, %.3f] m; ", + r, z, ingest.rmin, ingest.rmax, ingest.zmin, ingest.zmax) * + "re-export the equilibrium on a grid that covers it" + ) + end + + psi_in = cubic_interp((ingest.psi_xs, ingest.psi_ys), ingest.psi_rz; extrap=ExtendExtrap()) + F_in = cubic_interp(ingest.sq_xs, ingest.sq_fs[:, 1]; extrap=ExtendExtrap()) + # The solver rescales ψ to equal psio exactly at the magnetic axis; do the same. + scale = ingest.psio / psi_in((equil.ro, equil.zo)) + psi_norm_at(r, z) = 1 - scale * psi_in((r, z)) / ingest.psio + # Flux surfaces are star-shaped about the axis, so a point is inside the last closed flux surface when the + # segment to it from the axis stays at ψ_N < 1; below an X-point it crosses ψ_N ≥ 1. + h = min(ingest.psi_xs[2] - ingest.psi_xs[1], ingest.psi_ys[2] - ingest.psi_ys[1]) + inside(r, z) = all(t -> psi_norm_at(equil.ro + t * (r - equil.ro), equil.zo + t * (z - equil.zo)) < 1, + range(0, 1; length=max(2, ceil(Int, hypot(r - equil.ro, z - equil.zo) / h) + 1))) + + B_R, B_phi, B_Z, psi_norm = (similar(R, Float64) for _ in 1:4) + for i in eachindex(R, Z) + r, z = Float64(R[i]), Float64(Z[i]) + psi_norm[i] = psi_norm_at(r, z) + # The processed ψ peaks at the axis whatever the current's direction; ip_sign restores it. + B_R[i] = -ingest.ip_sign * scale * psi_in((r, z); deriv=DerivOp(0, 1)) / r + B_Z[i] = ingest.ip_sign * scale * psi_in((r, z); deriv=DerivOp(1, 0)) / r + F = psi_norm[i] < 1 && inside(r, z) ? F_in(psi_norm[i]) : ingest.sq_fs[end, 1] + B_phi[i] = ingest.bt_sign * F / r + end + return (; B_R, B_phi, B_Z, psi_norm) +end diff --git a/src/Equilibrium/Equilibrium.jl b/src/Equilibrium/Equilibrium.jl index 769b2cfe52..be83736076 100644 --- a/src/Equilibrium/Equilibrium.jl +++ b/src/Equilibrium/Equilibrium.jl @@ -57,6 +57,7 @@ include("Axisymmetric/DirectArcLength.jl") include("Axisymmetric/DirectByInversion.jl") include("Axisymmetric/Inverse.jl") include("Derived/GeometryProfiles.jl") +include("Derived/EquilibriumField.jl") include("KineticProfiles.jl") include("Construction.jl") include("Derived/GlobalParameters.jl") @@ -67,7 +68,7 @@ export reform, EquilibriumConfig, PlasmaEquilibrium, EquilibriumParameters, Anal ProfileSplines, GeometryProfileSplines, compute_geometry_profiles, KineticProfileSplines, kinetic_profile_splines, shift_exb_rotation, KineticProfileData, IonSpecies, read_kinetic_file, write_kinetic_h5, attach_kinetic_profiles! -export flux_surface_metric, flux_surface_area +export flux_surface_metric, flux_surface_area, equilibrium_field export wants_two_pass, refined_psi_grid, merge_mandatory_nodes, bracket_mandatory_nodes, enforce_min_spacing, implied_knot_count export compute_jac_delpsi, compute_sqrt_jac_delpsi, compute_sqrtamat, rootarea_to_area_weight, area_to_rootarea_weight diff --git a/test/runtests_equil.jl b/test/runtests_equil.jl index 8378c52cd5..d546bb8a52 100644 --- a/test/runtests_equil.jl +++ b/test/runtests_equil.jl @@ -278,6 +278,68 @@ using TOML @test finite(eq_r) end + @testset "Machine-frame equilibrium field" begin + EQ = GeneralizedPerturbedEquilibrium.Equilibrium + FT = GeneralizedPerturbedEquilibrium.ForcingTerms + gfile = joinpath(@__DIR__, "..", "examples", "DIIID-like_ideal_example", "TkMkr_D3Dlike_Hmode.geqdsk") + cfg = EQ.EquilibriumConfig(; eq_filename=gfile, eq_type="efit", jac_type="hamada", grid_type="core_edge_packed", psilow=0.01, psihigh=0.995, mpsi=64, mtheta=256) + equil = EQ.PlasmaEquilibrium(cfg) + ingest = equil.ingest + + # A flux surface at scale × its traced minor radius, counterclockwise in the (R, Z) plane. + psi = equil.rzphi_xs[end] + function surface(θ; scale=1.0) + rminor = scale .* sqrt.(equil.rzphi_rsquared.(Ref(psi), θ)) + η = 2π .* (θ .+ equil.rzphi_offset.(Ref(psi), θ)) + return equil.ro .+ rminor .* cos.(η), equil.zo .+ rminor .* sin.(η) + end + + # On the traced knots of the outermost surface: its flux, and |B| as the solver found it. + R, Z = surface(equil.rzphi_ys) + B = EQ.equilibrium_field(equil, R, Z) + @test maximum(abs, B.psi_norm .- psi) < 1e-7 + @test sqrt.(B.B_R .^ 2 .+ B.B_phi .^ 2 .+ B.B_Z .^ 2) ≈ equil.eqfun_B.(Ref(psi), equil.rzphi_ys) rtol = 1e-4 + @test all(sign.(B.B_phi) .== ingest.bt_sign) + + # Ampère just outside the plasma: counterclockwise in (R, Z) circulates about -φ̂, so the loop integral is -μ₀ I_φ. + R, Z = surface(collect(range(0, 1; length=4001)); scale=1.03) + B = EQ.equilibrium_field(equil, R, Z) + mid(v) = (v[1:end-1] .+ v[2:end]) ./ 2 + ip = parse(Float64, readlines(gfile)[4][1:16]) # the header's plasma current, in A + @test sum(mid(B.B_R) .* diff(R) .+ mid(B.B_Z) .* diff(Z)) ≈ -sign(ip) * 4π * 1e-7 * abs(ip) rtol = 1e-3 + + # The coil kernel's frame: a hoop at the axis carrying current with the plasma's sign gives the same B_Z outboard. + φ = range(0, 2π; length=721) + hoop = FT.CoilSet("hoop", 1, 1, 1.0, 721, reshape(equil.ro .* cos.(φ), 1, 1, :), reshape(equil.ro .* sin.(φ), 1, 1, :), + fill(equil.zo, 1, 1, 721), [ingest.ip_sign * 1e6]) + r_out = [maximum(R) + 0.05] + Bc = (zeros(1), zeros(1), zeros(1)) + FT.compute_biot_savart_boundary!(Bc..., r_out, [0.0], [equil.zo], [hoop]) + @test sign(Bc[3][1]) == sign(EQ.equilibrium_field(equil, r_out, [equil.zo]).B_Z[1]) == -ingest.ip_sign + + # Reversing the file's signs reverses the matching components. + flipped = deepcopy(equil) + flipped.ingest = EQ.DirectIngest(ingest.sq_xs, ingest.sq_fs, ingest.psi_xs, ingest.psi_ys, ingest.psi_rz, ingest.rmin, ingest.rmax, + ingest.zmin, ingest.zmax, ingest.psio, -ingest.bt_sign, -ingest.ip_sign) + Bf = EQ.equilibrium_field(flipped, R, Z) + @test Bf.B_R == -B.B_R && Bf.B_Z == -B.B_Z && Bf.B_phi == -B.B_phi + + # F follows the profile inside the plasma and is the edge value outside it, also past the X-point where ψ_N < 1. + law = EQ.separatrix_q_law(equil) + rx, zx = law.r_x[1], law.z_x[1] + d = hypot(rx - equil.ro, zx - equil.zo) + rr = [equil.ro, ingest.rmax - 0.01, rx + 0.06 * (rx - equil.ro) / d] + zz = [equil.zo, equil.zo, zx + 0.06 * (zx - equil.zo) / d] + Bv = EQ.equilibrium_field(equil, rr, zz) + @test Bv.psi_norm[1] < 1e-6 && Bv.psi_norm[2] > 1 && Bv.psi_norm[3] < 1 + @test Bv.B_phi .* rr ≈ ingest.bt_sign .* ingest.sq_fs[[1, end, end], 1] rtol = 1e-6 + @test abs(ingest.sq_fs[1, 1] - ingest.sq_fs[end, 1]) > 1e-3 * ingest.sq_fs[end, 1] + + @test_throws "outside the equilibrium's flux grid" EQ.equilibrium_field(equil, [ingest.rmax + 0.1], [0.0]) + sol = EQ.PlasmaEquilibrium(EQ.EquilibriumConfig(; eq_type="sol", psilow=0.01, psihigh=0.99, mpsi=16, mtheta=32), EQ.SolovevConfig(; mr=32, mz=32, ma=32)) + @test_throws "only g-file and IMAS" EQ.equilibrium_field(sol, [1.0], [0.0]) + end + @testset "Load TokaMaker i-file" begin Eq = GeneralizedPerturbedEquilibrium.Equilibrium # One TokaMaker solve written by save_eqdsk (g65) and save_ifile (i33x65, real*8 and real*4) From f67f86ea78af39076d89d946ee410b5fbc67a602 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Mon, 16 Nov 2026 22:43:25 +0100 Subject: [PATCH 22/27] ForcingTerms - API! - Default the toroidal coil grid to 32(|n| + 1) points With nzeta_coil = 0 the boundary grid used 32|n| toroidal points. A source close to the plasma carries toroidal structure of its own, and at n = 1 those 32 points alias it into the spectrum: for the ITER ferritic inserts on the control surface, n = 31-35 folds onto n = 1 and moves its spectrum by 16%, against 2e-5 with 64 points. The default is now 32(|n| + 1): the 32 points per period that helical windings need, plus one more period's worth for the source's own structure. n = 1 gets 64 points, n = 2 gets 96. The DIII-D-like example decks and the coil docs no longer set nzeta_coil = 32, so they use the default. Cases run from those decks move. Co-Authored-By: Claude Opus 5.5 --- docs/src/forcing_terms.md | 1 - examples/DIIID-like_error_field_example/gpec.toml | 1 - examples/DIIID-like_gal_resistive_example/gpec.toml | 1 - examples/DIIID-like_ideal_example/gpec.toml | 1 - examples/DIIID-like_ideal_multi_n_example/gpec.toml | 1 - examples/DIIID-like_riccati_deltaprime_example/gpec.toml | 1 - src/ErrorFields/Overlap.jl | 2 +- src/ForcingTerms/CoilFourier.jl | 6 +++--- src/ForcingTerms/CoilGeometry.jl | 2 +- src/ForcingTerms/ForcingTerms.jl | 2 +- 10 files changed, 6 insertions(+), 12 deletions(-) diff --git a/docs/src/forcing_terms.md b/docs/src/forcing_terms.md index 2cd2ea5915..fba0808a36 100644 --- a/docs/src/forcing_terms.md +++ b/docs/src/forcing_terms.md @@ -49,7 +49,6 @@ From `examples/DIIID-like_ideal_example/gpec.toml` (the first block) and the oth forcing_data_format = "coil" machine = "d3d" mtheta_coil = 480 -nzeta_coil = 32 # ASCII .dat file, resolved to {dat_dir}/{machine}_{name}.dat [[ForcingTerms.coil_set]] diff --git a/examples/DIIID-like_error_field_example/gpec.toml b/examples/DIIID-like_error_field_example/gpec.toml index 3089f801f8..84d83264f6 100644 --- a/examples/DIIID-like_error_field_example/gpec.toml +++ b/examples/DIIID-like_error_field_example/gpec.toml @@ -74,7 +74,6 @@ renorm_threshold = 1e3 # Column-norm threshold that triggers solution re forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation -nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) [[ForcingTerms.coil_set]] name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils): the nominal n=1 source diff --git a/examples/DIIID-like_gal_resistive_example/gpec.toml b/examples/DIIID-like_gal_resistive_example/gpec.toml index ea441ca260..c630a4bc4d 100644 --- a/examples/DIIID-like_gal_resistive_example/gpec.toml +++ b/examples/DIIID-like_gal_resistive_example/gpec.toml @@ -82,7 +82,6 @@ gamma = 1.6666666666666667 # Ratio of specific he forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation -nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) [[ForcingTerms.coil_set]] name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) diff --git a/examples/DIIID-like_ideal_example/gpec.toml b/examples/DIIID-like_ideal_example/gpec.toml index 1c9f17ed44..4ead78a230 100644 --- a/examples/DIIID-like_ideal_example/gpec.toml +++ b/examples/DIIID-like_ideal_example/gpec.toml @@ -70,7 +70,6 @@ renorm_threshold = 1e3 # Column-norm threshold that triggers solution re forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation -nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) [[ForcingTerms.coil_set]] name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) diff --git a/examples/DIIID-like_ideal_multi_n_example/gpec.toml b/examples/DIIID-like_ideal_multi_n_example/gpec.toml index 71f8da0b84..14b2a4a690 100644 --- a/examples/DIIID-like_ideal_multi_n_example/gpec.toml +++ b/examples/DIIID-like_ideal_multi_n_example/gpec.toml @@ -63,7 +63,6 @@ renorm_threshold = 1e3 # Column-norm threshold that triggers solution re forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation -nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) [[ForcingTerms.coil_set]] name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) diff --git a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml index 062459afed..910772eb2a 100644 --- a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml +++ b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml @@ -61,7 +61,6 @@ save_interval = 1 # Store every Nth solver step of each chunk (1=al forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation -nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) [[ForcingTerms.coil_set]] name = "c" # Coil set; resolves to coil_geometries/d3d_c.dat (DIII-D C-coil, 6 coils) diff --git a/src/ErrorFields/Overlap.jl b/src/ErrorFields/Overlap.jl index 1d89eaf5b5..dff6e4b0af 100644 --- a/src/ErrorFields/Overlap.jl +++ b/src/ErrorFields/Overlap.jl @@ -104,7 +104,7 @@ end function _warn_coarse_toroidal_grid(cfg::CoilConfig, rc::ResonantCoupling) for n in sort(unique(rc.n_modes)) - nzeta = cfg.nzeta_coil > 0 ? cfg.nzeta_coil : ForcingTerms.NZETA_POINTS_PER_PERIOD * max(1, abs(n)) + nzeta = cfg.nzeta_coil > 0 ? cfg.nzeta_coil : ForcingTerms.NZETA_POINTS_PER_PERIOD * (abs(n) + 1) per_period = nzeta / max(1, abs(n)) per_period < MIN_NZETA_PER_PERIOD && @warn "Toroidal boundary grid is $(round(per_period; digits=1)) points per period for n = $n, " * "below the $MIN_NZETA_PER_PERIOD where helical coils are converged. Pass nzeta_coil to override the stored deck's value." diff --git a/src/ForcingTerms/CoilFourier.jl b/src/ForcingTerms/CoilFourier.jl index 524737b712..b361b9dce8 100644 --- a/src/ForcingTerms/CoilFourier.jl +++ b/src/ForcingTerms/CoilFourier.jl @@ -16,7 +16,7 @@ suitable for the perturbed equilibrium pipeline. using FastInterpolations: cubic_interp, PeriodicBC, DerivOp -# Default toroidal points per period when nzeta_coil is not specified +# Toroidal points per period of n; the default grid is this × (|n| + 1), the extra period resolving the source's own toroidal structure. const NZETA_POINTS_PER_PERIOD = 32 """ @@ -254,11 +254,11 @@ end CoilForcingGrid(equil, cfg, n; psi=equil.rzphi_xs[end]) Sample the control surface `psi` at `cfg.mtheta_coil × nzeta` points, with `nzeta` taken -from `cfg.nzeta_coil` or `NZETA_POINTS_PER_PERIOD` per toroidal period of `n`. Pass +from `cfg.nzeta_coil` or `NZETA_POINTS_PER_PERIOD × (|n| + 1)`. Pass `psi = psilim` whenever a solve is at hand (see `sample_boundary_grid`). """ function CoilForcingGrid(equil::Equilibrium.PlasmaEquilibrium, cfg::CoilConfig, n::Int; psi::Float64=equil.rzphi_xs[end]) - nzeta = cfg.nzeta_coil > 0 ? cfg.nzeta_coil : NZETA_POINTS_PER_PERIOD * max(1, abs(n)) + nzeta = cfg.nzeta_coil > 0 ? cfg.nzeta_coil : NZETA_POINTS_PER_PERIOD * (abs(n) + 1) grid = sample_boundary_grid(equil, cfg.mtheta_coil, nzeta; psi) # Lay out observation points: (theta_i, zeta_j) → cylindrical (R, phi, Z) diff --git a/src/ForcingTerms/CoilGeometry.jl b/src/ForcingTerms/CoilGeometry.jl index 6d27f68a54..800765b86e 100644 --- a/src/ForcingTerms/CoilGeometry.jl +++ b/src/ForcingTerms/CoilGeometry.jl @@ -145,7 +145,7 @@ Top-level coil configuration from the `[ForcingTerms]` TOML section when - `machine`: machine name prefix for .dat files (e.g. "d3d") - `dat_dir`: directory containing .dat files; defaults to bundled `coil_geometries/` - `mtheta_coil`: poloidal grid resolution for boundary field evaluation (default: 480) - - `nzeta_coil`: toroidal grid resolution; 0 = auto (32 × n) + - `nzeta_coil`: toroidal grid resolution; 0 = auto, 32(|n| + 1) - `coil_sets`: parsed `[[ForcingTerms.coil_set]]` blocks """ Base.@kwdef struct CoilConfig diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index e7fc69b212..6c1a2a2149 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -28,7 +28,7 @@ Coil settings (used when `forcing_data_format = "coil"`): - `machine::String` - Machine name prefix for .dat files (e.g. "d3d") - `dat_dir::String` - Directory containing .dat files; defaults to bundled `coil_geometries/` - `mtheta_coil::Int` - Poloidal grid resolution for boundary field evaluation (default: 480) - - `nzeta_coil::Int` - Toroidal grid resolution; 0 = auto (32 × n) + - `nzeta_coil::Int` - Toroidal grid resolution; 0 = auto, 32(|n| + 1) - `coil_sets_raw::Vector{Dict{String,Any}}` - Parsed `[[ForcingTerms.coil_set]]` TOML blocks """ @kwdef struct ForcingTermsControl From 970e225a2d29f7b1f193a509eb6fdd0156c0fd58 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Tue, 17 Nov 2026 13:40:17 +0100 Subject: [PATCH 23/27] ForcingTerms - API! - Sum every source in [ForcingTerms] and drop forcing_data_format = "coil" --- benchmarks/benchmark_against_fortran_run.jl | 1 - docs/src/error_fields.md | 2 +- docs/src/forcing_terms.md | 5 ++- docs/src/workflow.md | 1 - .../DIIID-like_error_field_example/gpec.toml | 1 - .../gpec.toml | 1 - examples/DIIID-like_ideal_example/gpec.toml | 1 - .../gpec.toml | 1 - .../gpec.toml | 1 - examples/Solovev_ideal_example_3D/gpec.toml | 2 +- examples/TJ_ideal_example/gpec.toml | 2 +- examples/TJ_kinetic_NTV_example/gpec.toml | 2 +- .../TJ_kinetic_calculated_example/gpec.toml | 2 +- .../TJ_kinetic_multiion_example/gpec.toml | 2 +- src/Analysis/Registry.jl | 2 +- src/Deck.jl | 9 +++--- src/ErrorFields/ErrorFieldsStructs.jl | 2 +- src/ForcingTerms/CoilGeometry.jl | 3 +- src/ForcingTerms/ForcingTerms.jl | 31 +++++++++++-------- src/Precompile.jl | 2 +- src/Rerun.jl | 4 +++ test/error_fields_fixture.jl | 2 +- test/runtests_analysis_plots.jl | 4 +-- test/runtests_error_fields.jl | 2 +- test/runtests_rerun_from_h5.jl | 2 +- test/runtests_solve_api.jl | 14 ++++++++- test/runtests_torque_response.jl | 1 - 27 files changed, 56 insertions(+), 46 deletions(-) diff --git a/benchmarks/benchmark_against_fortran_run.jl b/benchmarks/benchmark_against_fortran_run.jl index 87464dc8b5..7e76b03d1c 100644 --- a/benchmarks/benchmark_against_fortran_run.jl +++ b/benchmarks/benchmark_against_fortran_run.jl @@ -426,7 +426,6 @@ function write_gpec_toml_coil( println(io, "save_interval = $(p.euler_stride)") println(io) println(io, "[ForcingTerms]") - println(io, "forcing_data_format = \"coil\"") println(io, "mtheta_coil = $(p.mtheta_coil)") println(io, "nzeta_coil = $(p.nzeta_coil)") for (name, currents) in zip(p.coil_names, p.coil_currents) diff --git a/docs/src/error_fields.md b/docs/src/error_fields.md index 1cd5c3b47c..a876bd625f 100644 --- a/docs/src/error_fields.md +++ b/docs/src/error_fields.md @@ -47,7 +47,7 @@ It holds only while the plasma still rotates, so the current is capped at ``I_\m ## Running it -The stage needs a `[PerturbedEquilibrium]` run with `forcing_data_format = "coil"` and the singular coupling computed; `examples/DIIID-like_error_field_example` is the complete case, with the DIII-D C-coil as the n = 1 source and the eighteen F coils as single-filament hoops whose error-field content is entirely their sensitivity to misalignment. +The stage needs a `[PerturbedEquilibrium]` run with `[ForcingTerms]` coil sets and the singular coupling computed; `examples/DIIID-like_error_field_example` is the complete case, with the DIII-D C-coil as the n = 1 source and the eighteen F coils as single-filament hoops whose error-field content is entirely their sensitivity to misalignment. From its deck: ```toml diff --git a/docs/src/forcing_terms.md b/docs/src/forcing_terms.md index fba0808a36..bb5390257a 100644 --- a/docs/src/forcing_terms.md +++ b/docs/src/forcing_terms.md @@ -1,7 +1,7 @@ # Forcing Terms `ForcingTerms` specifies the external magnetic perturbation that drives the perturbed equilibrium: the spectrum of the normal field on the control surface at `psilim`, given either as a file of (m, n) amplitudes or computed by Biot–Savart from coil geometry. -The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs; its result is the `ForcingField` that `perturbed_equilibrium` applies to the plasma response. +The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs. Every source it holds (a `forcing_data_file`, coil sets) drives the plasma, and their spectra are summed into the `ForcingField` that `perturbed_equilibrium` applies to the plasma response. ## Normalization @@ -39,14 +39,13 @@ end ## Coils -`forcing_data_format = "coil"` computes the field from coil geometry: the plasma boundary is sampled on an `mtheta_coil × nzeta_coil` grid, the Biot–Savart field of every coil set is evaluated there, projected onto the normal flux and Fourier decomposed. +Coil sets compute the field from coil geometry: the plasma boundary is sampled on an `mtheta_coil × nzeta_coil` grid, the Biot–Savart field of every coil set is evaluated there, projected onto the normal flux and Fourier decomposed. The toroidal angle of each observation point includes the straight-field-line offset ``\nu(\psi, \theta)`` and the helicity ``\mathrm{sign}(B_T)\,\mathrm{sign}(I_p)`` of the equilibrium, without which the decomposition would be wrong. Each `[[ForcingTerms.coil_set]]` block supplies one coil set, selected by `source`; shifts and tilts (`shiftx/y/z`, `tiltx/y/z`, `n_tilt`, …) apply to every source, which is what the [Error Fields](error_fields.md) stage sweeps. From `examples/DIIID-like_ideal_example/gpec.toml` (the first block) and the other sources: ```toml [ForcingTerms] -forcing_data_format = "coil" machine = "d3d" mtheta_coil = 480 diff --git a/docs/src/workflow.md b/docs/src/workflow.md index 2519cb5c26..32711a6cbd 100644 --- a/docs/src/workflow.md +++ b/docs/src/workflow.md @@ -130,7 +130,6 @@ vac_flag = true integrator = "Forward" # [PerturbedEquilibrium] needs a dense ξ solution and no [Wall]; "Riccati" (the default) supplies one too [ForcingTerms] -forcing_data_format = "coil" machine = "d3d" [[ForcingTerms.coil_set]] diff --git a/examples/DIIID-like_error_field_example/gpec.toml b/examples/DIIID-like_error_field_example/gpec.toml index 84d83264f6..0bc4851732 100644 --- a/examples/DIIID-like_error_field_example/gpec.toml +++ b/examples/DIIID-like_error_field_example/gpec.toml @@ -71,7 +71,6 @@ save_interval = 1 # Save every Nth ODE step (1=all). Always saves n renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation diff --git a/examples/DIIID-like_gal_resistive_example/gpec.toml b/examples/DIIID-like_gal_resistive_example/gpec.toml index c630a4bc4d..5896c99bc2 100644 --- a/examples/DIIID-like_gal_resistive_example/gpec.toml +++ b/examples/DIIID-like_gal_resistive_example/gpec.toml @@ -79,7 +79,6 @@ rotation = [1.0, 1.0, 1.0, 1.0] # Per-surface rotation gamma = 1.6666666666666667 # Ratio of specific heats Γ for the resistive-layer coefficients (5/3) [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation diff --git a/examples/DIIID-like_ideal_example/gpec.toml b/examples/DIIID-like_ideal_example/gpec.toml index 4ead78a230..5ea96390c6 100644 --- a/examples/DIIID-like_ideal_example/gpec.toml +++ b/examples/DIIID-like_ideal_example/gpec.toml @@ -67,7 +67,6 @@ save_interval = 1 # Save every Nth ODE step (1=all). Always saves n renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation diff --git a/examples/DIIID-like_ideal_multi_n_example/gpec.toml b/examples/DIIID-like_ideal_multi_n_example/gpec.toml index 14b2a4a690..0be1d46710 100644 --- a/examples/DIIID-like_ideal_multi_n_example/gpec.toml +++ b/examples/DIIID-like_ideal_multi_n_example/gpec.toml @@ -60,7 +60,6 @@ save_interval = 1 # Save every Nth ODE step (1=all). Always saves n renorm_threshold = 1e3 # Column-norm threshold that triggers solution renormalization [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation diff --git a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml index 910772eb2a..1e8ef72572 100644 --- a/examples/DIIID-like_riccati_deltaprime_example/gpec.toml +++ b/examples/DIIID-like_riccati_deltaprime_example/gpec.toml @@ -58,7 +58,6 @@ eulerlagrange_tolerance = 1e-10 # Relative tolerance for ODE integration of Eule save_interval = 1 # Store every Nth solver step of each chunk (1=all); chunk ends and the edge-dW scan band are always stored [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) machine = "d3d" # Geometry prefix; resolves to bundled coil_geometries/d3d_*.dat mtheta_coil = 480 # Poloidal grid for boundary B·n̂ evaluation diff --git a/examples/Solovev_ideal_example_3D/gpec.toml b/examples/Solovev_ideal_example_3D/gpec.toml index e24fd00d1e..4febeb2e76 100644 --- a/examples/Solovev_ideal_example_3D/gpec.toml +++ b/examples/Solovev_ideal_example_3D/gpec.toml @@ -62,7 +62,7 @@ equal_arc_wall = false # Equal arc length distribution of nodes # Uncomment to enable perturbed equilibrium calculations: # [PerturbedEquilibrium] # forcing_data_file = "forcing.dat" # Manual mode table (n, m, amplitude_real, amplitude_imag) -# forcing_data_format = "ascii" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +# forcing_data_format = "ascii" # Format of the forcing-mode table: "ascii" or "hdf5" # compute_singular_coupling = true # Compute singular layer coupling metrics # Solovev analytic equilibrium parameters; this section selects the equilibrium. See SolovevConfig in src/Equilibrium. [Solovev] diff --git a/examples/TJ_ideal_example/gpec.toml b/examples/TJ_ideal_example/gpec.toml index 2a6cdcf52f..520d2c7f8a 100644 --- a/examples/TJ_ideal_example/gpec.toml +++ b/examples/TJ_ideal_example/gpec.toml @@ -16,7 +16,7 @@ mtheta = 256 # Number of poloidal grid points [ForcingTerms] forcing_data_file = "forcing.dat" # Manual mode table (n, m, amplitude_real, amplitude_imag) -forcing_data_format = "ascii" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +forcing_data_format = "ascii" # Format of the forcing-mode table: "ascii" or "hdf5" [PerturbedEquilibrium] compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/examples/TJ_kinetic_NTV_example/gpec.toml b/examples/TJ_kinetic_NTV_example/gpec.toml index 09215540aa..901deb4d72 100644 --- a/examples/TJ_kinetic_NTV_example/gpec.toml +++ b/examples/TJ_kinetic_NTV_example/gpec.toml @@ -18,7 +18,7 @@ mtheta = 256 # Number of poloidal grid points [ForcingTerms] forcing_data_file = "forcing.dat" # Manual mode table (n, m, amplitude_real, amplitude_imag) -forcing_data_format = "ascii" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +forcing_data_format = "ascii" # Format of the forcing-mode table: "ascii" or "hdf5" [PerturbedEquilibrium] compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/examples/TJ_kinetic_calculated_example/gpec.toml b/examples/TJ_kinetic_calculated_example/gpec.toml index 6e4cae56e6..8d4d142c3c 100644 --- a/examples/TJ_kinetic_calculated_example/gpec.toml +++ b/examples/TJ_kinetic_calculated_example/gpec.toml @@ -30,7 +30,7 @@ fraction = 0.5 # This species' share of the total main- [ForcingTerms] forcing_data_file = "forcing.dat" # Manual mode table (n, m, amplitude_real, amplitude_imag) -forcing_data_format = "ascii" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +forcing_data_format = "ascii" # Format of the forcing-mode table: "ascii" or "hdf5" [PerturbedEquilibrium] compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/examples/TJ_kinetic_multiion_example/gpec.toml b/examples/TJ_kinetic_multiion_example/gpec.toml index db9c1bdd5a..59ed94ae09 100644 --- a/examples/TJ_kinetic_multiion_example/gpec.toml +++ b/examples/TJ_kinetic_multiion_example/gpec.toml @@ -30,7 +30,7 @@ fraction = 0.5 # This species' share of the total main- [ForcingTerms] forcing_data_file = "forcing.dat" # Manual mode table (n, m, amplitude_real, amplitude_imag) -forcing_data_format = "ascii" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) +forcing_data_format = "ascii" # Format of the forcing-mode table: "ascii" or "hdf5" [PerturbedEquilibrium] compute_singular_coupling = true # Compute singular layer coupling metrics diff --git a/src/Analysis/Registry.jl b/src/Analysis/Registry.jl index 6332d2d375..4406b500ca 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -57,7 +57,7 @@ const REASONS = Dict{Symbol,String}( :response_n => "needs the stored normal field and displacement: run PerturbedEquilibrium on a free-boundary result", :penetrated_field => "needs a penetrated field: ideal runs have none; it comes from a matched (resistive) run", :response_b => "needs the reconstructed perturbed field b: run PerturbedEquilibrium on a free-boundary result", - :coil_sets => "needs coil forcing: give ForcingTerms coil sets (forcing_data_format = \"coil\")", + :coil_sets => "needs coil forcing: give [ForcingTerms] coil sets", :forcing_modes => "needs forcing modes: give ForcingTerms a forcing", :ef_sensitivities => "needs the coil sensitivities: add an [ErrorFields] section", :dominant_mode => "needs the dominant resonant-coupling mode: run PerturbedEquilibrium with compute_singular_coupling = true", diff --git a/src/Deck.jl b/src/Deck.jl index 21ffa16f1b..4c323166f5 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -410,9 +410,8 @@ relative file paths resolved against the deck directory `path`. The `[[ForcingTe array of tables is passed through as `coil_sets_raw`. """ function forcing_terms_control(inputs::AbstractDict, path::AbstractString) - "ForcingTerms" in keys(inputs) || return ForcingTerms.ForcingTermsControl(; forcing_data_file=joinpath(path, "forcing.dat")) + "ForcingTerms" in keys(inputs) || return ForcingTerms.ForcingTermsControl() forcing_raw = _deck_paths(inputs["ForcingTerms"], path, ("forcing_data_file", "dat_dir")) - haskey(forcing_raw, "forcing_data_file") || (forcing_raw["forcing_data_file"] = joinpath(path, "forcing.dat")) coil_sets_raw = Dict{String,Any}[_deck_paths(d, path, ("dat_file", "h5_file")) for d in get(forcing_raw, "coil_set", Dict{String,Any}[])] kwargs = section_keywords(_without(forcing_raw, "coil_set"), "ForcingTerms", _struct_fields(ForcingTerms.ForcingTermsControl, (:coil_sets_raw,))) return ForcingTerms.ForcingTermsControl(; kwargs..., coil_sets_raw=coil_sets_raw) @@ -486,8 +485,8 @@ function parse_deck(inputs::AbstractDict, path::AbstractString) forcing = forcing_terms_control(inputs, path) if haskey(inputs, "ErrorFields") perturbed_equilibrium === nothing && error("[ErrorFields] needs a [PerturbedEquilibrium] section") - forcing.forcing_data_format == "coil" || - error("[ErrorFields] linearizes coil geometry, so [ForcingTerms] must use forcing_data_format = \"coil\" (got \"$(forcing.forcing_data_format)\")") + !isempty(forcing.coil_sets_raw) && isempty(forcing.forcing_data_file) || + error("[ErrorFields] linearizes coil geometry, so [ForcingTerms] must hold coil sets and no forcing_data_file") end tearing_model = haskey(inputs, "Tearing") ? get(inputs["Tearing"], "inner_model", nothing) : nothing match_model = match === nothing ? nothing : _inner_model_token(match.model) @@ -623,7 +622,7 @@ _forcing_table(f::ForcingTerms.ForcingFile) = Dict{String,Any}("forcing_data_fil function _forcing_table(f::ForcingTerms.ForcingCoils) cfg, default = f.config, ForcingTerms.CoilSetConfig() - table = Dict{String,Any}("forcing_data_format" => "coil", "machine" => cfg.machine, "mtheta_coil" => cfg.mtheta_coil, "nzeta_coil" => cfg.nzeta_coil) + table = Dict{String,Any}("machine" => cfg.machine, "mtheta_coil" => cfg.mtheta_coil, "nzeta_coil" => cfg.nzeta_coil) cfg.dat_dir == ForcingTerms.BUNDLED_COIL_DIR || (table["dat_dir"] = cfg.dat_dir) table["coil_set"] = Any[ Dict{String,Any}(String(k) => _deck_out(getfield(sc, k)) for k in fieldnames(ForcingTerms.CoilSetConfig) if !isequal(getfield(sc, k), getfield(default, k))) diff --git a/src/ErrorFields/ErrorFieldsStructs.jl b/src/ErrorFields/ErrorFieldsStructs.jl index 9b882c3795..34ae162c85 100644 --- a/src/ErrorFields/ErrorFieldsStructs.jl +++ b/src/ErrorFields/ErrorFieldsStructs.jl @@ -2,7 +2,7 @@ ErrorFieldsControl Control parameters for the `[ErrorFields]` TOML section. The sweep needs a coil-forced -perturbed-equilibrium solve (`forcing_data_format = "coil"` with the singular-coupling step on); +perturbed-equilibrium solve (`[ForcingTerms]` coil sets, with the singular-coupling step on); everything here concerns only how the coil linearization is taken and where it is written. Analysis choices (which resonant surfaces count, which singular mode, which normalization) are never inputs: the full spectra are stored and projected post hoc with [`sensitivity_table`](@ref). diff --git a/src/ForcingTerms/CoilGeometry.jl b/src/ForcingTerms/CoilGeometry.jl index 800765b86e..0f0c3b81e6 100644 --- a/src/ForcingTerms/CoilGeometry.jl +++ b/src/ForcingTerms/CoilGeometry.jl @@ -137,8 +137,7 @@ end """ CoilConfig -Top-level coil configuration from the `[ForcingTerms]` TOML section when -`forcing_data_format = "coil"`. +Top-level coil configuration from the `[ForcingTerms]` TOML section. ## Fields diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index 6c1a2a2149..1af7581501 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -18,12 +18,14 @@ file paths against the deck directory; a script's resolve against the working di ## Fields -Forcing Data: +Every source the section holds drives the perturbed equilibrium, and their spectra are summed. - - `forcing_data_file::String` - Path to forcing data file (n, m, complex amplitude) - - `forcing_data_format::String` - Format: "ascii", "hdf5", or "coil" +Forcing file: -Coil settings (used when `forcing_data_format = "coil"`): + - `forcing_data_file::String` - Path to a forcing-mode table (n, m, complex amplitude); empty for none + - `forcing_data_format::String` - Format of the forcing-mode table: "ascii" or "hdf5" + +Coils: - `machine::String` - Machine name prefix for .dat files (e.g. "d3d") - `dat_dir::String` - Directory containing .dat files; defaults to bundled `coil_geometries/` @@ -32,11 +34,9 @@ Coil settings (used when `forcing_data_format = "coil"`): - `coil_sets_raw::Vector{Dict{String,Any}}` - Parsed `[[ForcingTerms.coil_set]]` TOML blocks """ @kwdef struct ForcingTermsControl - # Forcing data file settings (ascii/hdf5 formats) - forcing_data_file::String = "forcing.dat" + forcing_data_file::String = "" forcing_data_format::String = "ascii" - # Coil calculation settings (coil format) machine::String = "" dat_dir::String = "" mtheta_coil::Int = 480 @@ -276,7 +276,7 @@ drive several solves. The first form points at a forcing-mode file, `format` defaulting to `"hdf5"` for an `.h5` or `.hdf5` extension and `"ascii"` otherwise. The second form takes one coil set or a vector of them, each a -NamedTuple or Dict with the `[[ForcingTerms.coil_set]]` keys, and selects the coil format: +NamedTuple or Dict with the `[[ForcingTerms.coil_set]]` keys: ```julia ForcingField((name="c", currents=[1e3, 500, -500, -1e3, -500, 500]); machine="d3d") # the DIII-D C-coil, in amperes @@ -286,7 +286,7 @@ ForcingField((source="pf_hoop", radius=12.0, height=1.2, currents=[2e3])) Its remaining `kwargs` are the [`ForcingTermsControl`](@ref) coil settings (`machine`, `dat_dir`, `mtheta_coil`, `nzeta_coil`). The third form takes the same coil description already parsed, and the fourth a deck's `[ForcingTerms]` -section. The file forms return a [`ForcingFile`](@ref) leaf and the coil forms a [`ForcingCoils`](@ref) leaf. The last form +section, the sum of every source it holds. The file forms return a [`ForcingFile`](@ref) leaf and the coil forms a [`ForcingCoils`](@ref) leaf. The last form takes a control-surface spectrum computed elsewhere, already in the unit-norm `Φ_x` convention, and returns a spectrum-literal leaf ([`ForcingSpectrum`](@ref)). @@ -438,14 +438,19 @@ function ForcingField(cfg::CoilConfig; scale::Number=1.0) end function ForcingField(path::AbstractString; format::String=_infer_format(path), scale::Number=1.0) - format in ("ascii", "hdf5") || throw(ArgumentError("ForcingField: forcing_data_format \"$format\" is not \"ascii\", \"hdf5\" or \"coil\"")) + format in ("ascii", "hdf5") || throw(ArgumentError("ForcingField: forcing_data_format \"$format\" is not \"ascii\" or \"hdf5\"")) _check_forcing_file(abspath(path), format) return ForcingFile(abspath(path), format, ComplexF64(scale)) end function ForcingField(ctrl::ForcingTermsControl; scale::Number=1.0) - ctrl.forcing_data_format == "coil" && return ForcingField(CoilConfig(ctrl); scale) - return ForcingField(ctrl.forcing_data_file; format=ctrl.forcing_data_format, scale) + ctrl.forcing_data_format in ("ascii", "hdf5") || + throw(ArgumentError("ForcingField: forcing_data_format \"$(ctrl.forcing_data_format)\" is not \"ascii\" or \"hdf5\"")) + sources = ForcingField[] + isempty(ctrl.coil_sets_raw) || push!(sources, ForcingField(CoilConfig(ctrl))) + isempty(ctrl.forcing_data_file) || push!(sources, ForcingField(ctrl.forcing_data_file; format=ctrl.forcing_data_format)) + isempty(sources) && throw(ArgumentError("ForcingField: [ForcingTerms] holds no forcing source; give [[ForcingTerms.coil_set]] blocks or a forcing_data_file")) + return scale * sum(sources) end # A coil set as the [[ForcingTerms.coil_set]] table: a Dict or NamedTuple, keys as strings or symbols. @@ -454,7 +459,7 @@ _coil_dict(nt::NamedTuple) = Dict{String,Any}(string(k) => v for (k, v) in pairs _coil_dict(x) = throw(ArgumentError("ForcingField: a coil set is a Dict or NamedTuple of [[ForcingTerms.coil_set]] keys, not a $(typeof(x))")) ForcingField(coil_sets::AbstractVector; scale::Number=1.0, kwargs...) = - ForcingField(ForcingTermsControl(; forcing_data_format="coil", coil_sets_raw=_coil_dict.(coil_sets), kwargs...); scale) + ForcingField(ForcingTermsControl(; coil_sets_raw=_coil_dict.(coil_sets), kwargs...); scale) ForcingField(coil_set::Union{AbstractDict,NamedTuple}; kwargs...) = ForcingField([coil_set]; kwargs...) function ForcingField(modes::Vector{ForcingMode}; scale::Number=1.0) diff --git a/src/Precompile.jl b/src/Precompile.jl index 7f6bbe9ea3..6520213a31 100644 --- a/src/Precompile.jl +++ b/src/Precompile.jl @@ -51,7 +51,7 @@ import Logging ), "Forward" => Dict{String,Any}("eulerlagrange_tolerance" => 1e-6), "ForcingTerms" => Dict{String,Any}( - "forcing_data_format" => "coil", "machine" => "d3d", "mtheta_coil" => 32, "nzeta_coil" => 8, + "machine" => "d3d", "mtheta_coil" => 32, "nzeta_coil" => 8, "coil_set" => [Dict{String,Any}("name" => "c", "currents" => [1000.0, 500.0, -500.0, -1000.0, -500.0, 500.0])] ), "PerturbedEquilibrium" => Dict{String,Any}("compute_singular_coupling" => true, "regularization_width" => 0.05), diff --git a/src/Rerun.jl b/src/Rerun.jl index 17c3fe2d3e..c7363b7883 100644 --- a/src/Rerun.jl +++ b/src/Rerun.jl @@ -303,6 +303,8 @@ function build_inputs_from_h5(args::Vector{String}) ) end + use_coils && forcing_snapshot !== nothing && + error("--coil-source coils replays a run forced by coils alone; $source_h5 records its forcing as modes (a file, a weighted source or a sum)") output_dir, output_name = resolve_rerun_output_path(source_h5, cli.output_dir, cli.output_name) isdir(output_dir) || mkpath(output_dir) @@ -317,6 +319,8 @@ function build_inputs_from_h5(args::Vector{String}) modes, normalization = forcing_snapshot h5open(f -> ForcingTerms.save_forcing_to_h5(modes, f; normalization), joinpath(output_dir, forcing_file), "w") ft = get!(inputs, "ForcingTerms", Dict{String,Any}()) + # The recorded modes are the whole forcing, so the replay drops every other source. + delete!(ft, "coil_set") ft["forcing_data_file"] = forcing_file ft["forcing_data_format"] = "hdf5" end diff --git a/test/error_fields_fixture.jl b/test/error_fields_fixture.jl index 760fba6389..c93454c3c1 100644 --- a/test/error_fields_fixture.jl +++ b/test/error_fields_fixture.jl @@ -11,7 +11,7 @@ function error_fields_fixture(dir) toml_path = joinpath(dir, "gpec.toml") inputs = TOML.parsefile(toml_path) inputs["ForcingTerms"] = Dict{String,Any}( - "forcing_data_format" => "coil", "mtheta_coil" => 240, "nzeta_coil" => 32, + "mtheta_coil" => 240, "nzeta_coil" => 32, "coil_set" => [ Dict{String,Any}("name" => "hoop_tilted", "source" => "pf_hoop", "radius" => 12.0, "height" => 1.2, "currents" => [2.0e3], "tiltx" => [3.0]), Dict{String,Any}("name" => "hoop_axi", "source" => "pf_hoop", "radius" => 12.0, "height" => -1.2, "currents" => [2.0e3]), diff --git a/test/runtests_analysis_plots.jl b/test/runtests_analysis_plots.jl index 2b29792809..7d64b55fdc 100644 --- a/test/runtests_analysis_plots.jl +++ b/test/runtests_analysis_plots.jl @@ -76,7 +76,7 @@ using TOML "regression_tj_ideal_example"; ffs=Dict{String,Any}("dW_edge_scan_start" => 0.95), sections=Dict{String,Any}( - "ForcingTerms" => Dict{String,Any}("forcing_data_format" => "coil", "mtheta_coil" => 240, "nzeta_coil" => 32, + "ForcingTerms" => Dict{String,Any}("mtheta_coil" => 240, "nzeta_coil" => 32, "coil_set" => [Dict{String,Any}("name" => "hoop", "source" => "pf_hoop", "radius" => 12.0, "height" => 1.2, "currents" => [2.0e3], "tiltx" => [3.0])]), "PerturbedEquilibrium" => Dict{String,Any}("compute_singular_coupling" => true)) @@ -153,7 +153,7 @@ using TOML edit=d -> (d["ForceFreeStates"]["integrator"] = "Riccati"; d["Riccati"] = delete!(pop!(d, "Forward"), "renorm_threshold")), sections=Dict{String,Any}( "Match" => Dict{String,Any}("eta" => 1e-7, "rho" => 3e-7, "rotation" => 1.0), - "ForcingTerms" => Dict{String,Any}("forcing_data_format" => "coil", "mtheta_coil" => 240, "nzeta_coil" => 32, + "ForcingTerms" => Dict{String,Any}("mtheta_coil" => 240, "nzeta_coil" => 32, "coil_set" => [Dict{String,Any}("name" => "hoop", "source" => "pf_hoop", "radius" => 12.0, "height" => 1.2, "currents" => [2.0e3], "tiltx" => [3.0])]), "PerturbedEquilibrium" => Dict{String,Any}("compute_singular_coupling" => true)) diff --git a/test/runtests_error_fields.jl b/test/runtests_error_fields.jl index 99bbcd622e..53592d0566 100644 --- a/test/runtests_error_fields.jl +++ b/test/runtests_error_fields.jl @@ -549,7 +549,7 @@ include("error_fields_fixture.jl") toml_path = joinpath(dir, "gpec.toml") inputs = TOML.parsefile(toml_path) inputs["ForcingTerms"] = Dict{String,Any}( - "forcing_data_format" => "coil", "mtheta_coil" => 240, "nzeta_coil" => 32, + "mtheta_coil" => 240, "nzeta_coil" => 32, "coil_set" => [ Dict{String,Any}("name" => "hoop_tilted", "source" => "pf_hoop", "radius" => 1.5, "height" => 0.4, "currents" => [2.0e3], "tiltx" => [3.0]) diff --git a/test/runtests_rerun_from_h5.jl b/test/runtests_rerun_from_h5.jl index e16638ad05..a99efbe32c 100644 --- a/test/runtests_rerun_from_h5.jl +++ b/test/runtests_rerun_from_h5.jl @@ -230,7 +230,7 @@ end inputs["PerturbedEquilibrium"] = Dict{String,Any}( "compute_singular_coupling" => true) inputs["ForcingTerms"] = Dict{String,Any}( - "forcing_data_format" => "coil", "mtheta_coil" => 64, "nzeta_coil" => 32, + "mtheta_coil" => 64, "nzeta_coil" => 32, "coil_set" => [Dict{String,Any}( "dat_file" => coil_dat, "currents" => fill(1.0e3, 6) diff --git a/test/runtests_solve_api.jl b/test/runtests_solve_api.jl index 431b53f1ba..23ce737a5f 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -339,12 +339,24 @@ include("display_check.jl") @test ForcingField(GPEC.forcing_terms_control(Dict{String,Any}("ForcingTerms" => file_table), forcing_dir)).path == table_h5 end + @testset "[ForcingTerms] sums every source it holds" begin + forcing_section = section -> GPEC.forcing_terms_control(Dict{String,Any}("ForcingTerms" => section), forcing_dir) + c_coil = Dict{String,Any}("name" => "c", "currents" => [1e3, 500, -500, -1e3, -500, 500]) + both = ForcingField(forcing_section(Dict{String,Any}("machine" => "d3d", "coil_set" => [c_coil], "forcing_data_file" => "forcing.dat"))) + @test both isa GPEC.ForcingTerms.ForcingFieldSum + @test [typeof(t) for t in both.terms] == [GPEC.ForcingTerms.ForcingCoils, GPEC.ForcingTerms.ForcingFile] + @test ForcingField(forcing_section(Dict{String,Any}("machine" => "d3d", "coil_set" => [c_coil]))) isa GPEC.ForcingTerms.ForcingCoils + @test ForcingField(forcing_section(Dict{String,Any}("forcing_data_file" => "forcing.dat"))) isa GPEC.ForcingTerms.ForcingFile + @test_throws "holds no forcing source" ForcingField(GPEC.forcing_terms_control(Dict{String,Any}(), forcing_dir)) + @test_throws "is not \"ascii\" or \"hdf5\"" ForcingField(forcing_section(Dict{String,Any}("forcing_data_format" => "coil", "machine" => "d3d", "coil_set" => [c_coil]))) + end + @testset "ForcingField checks its source when built" begin @test_throws "no forcing file" ForcingField(joinpath(forcing_dir, "missing.dat")) geometry = joinpath(pkgdir(GPEC), "src", "ForcingTerms", "coil_geometries", "d3d_c.dat") @test_throws "is not a forcing-mode table" ForcingField(geometry) @test_throws "is not a forcing-mode table" ForcingField(table; format="hdf5") - @test_throws "is not \"ascii\", \"hdf5\" or \"coil\"" ForcingField(table; format="csv") + @test_throws "is not \"ascii\" or \"hdf5\"" ForcingField(table; format="csv") @test_throws "has no currents" ForcingField((name="c",); machine="d3d") @test_throws "currents for its 6 conductors" ForcingField((name="c", currents=ones(7)); machine="d3d") @test_throws "pass machine" ForcingField((name="c", currents=ones(6))) diff --git a/test/runtests_torque_response.jl b/test/runtests_torque_response.jl index 542fd978f6..7851a86215 100644 --- a/test/runtests_torque_response.jl +++ b/test/runtests_torque_response.jl @@ -14,7 +14,6 @@ include("h5_metadata_check.jl") const _TORQUE_RESPONSE_SECTIONS = """ [ForcingTerms] -forcing_data_format = "coil" # Format: "ascii", "hdf5", or "coil" (Biot-Savart from 3D wires) mtheta_coil = 128 # Poloidal grid for boundary B·n̂ evaluation nzeta_coil = 32 # Toroidal grid (0 = auto = 32·n) From 1c6743a8745ff3952edc979e581960c3fd0bc713 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Thu, 26 Nov 2026 11:28:42 +0100 Subject: [PATCH 24/27] ForcingTerms - FEATURE - Drive the perturbed equilibrium with saturated magnetic material ForcingField(materials) and [[ForcingTerms.magnetic_material]] blocks (name, h5_file, saturation_field, fill_fraction) add a ForcingMagneticMaterial leaf to the forcing sum. When materialized, every element is saturated along the equilibrium field at its centroid, M = f mu0Ms B0_hat / mu0 (saturated_magnetization), and its exact field is sampled on the mtheta_coil x nzeta_coil control-surface grid, projected onto the normal flux and Fourier decomposed per n (material_forcing_modes). Every vertex must lie inside the equilibrium's flux grid and outside the separatrix (psi_N >= 1, below an X-point too), and the field kernel errors on a control-surface point inside an element. A replay runs from the recorded forcing modes and drops the material blocks; [ErrorFields] refuses a deck with material. Tests check the magnitude and direction of M, the three guards, that a ring of identical elements drives only multiples of its count, that a broken ring drives n = 1, and the leaf from the API and from a deck. Co-Authored-By: Claude Opus 5.5 --- docs/src/forcing_terms.md | 17 +++- src/Deck.jl | 15 ++-- src/Display.jl | 3 +- src/ForcingTerms/ForcingTerms.jl | 54 ++++++++++-- src/ForcingTerms/MagneticMaterial.jl | 86 ++++++++++++++++++- .../PerturbedEquilibrium.jl | 19 ++++ src/Rerun.jl | 1 + test/runtests_magnetic_material.jl | 60 +++++++++++++ 8 files changed, 238 insertions(+), 17 deletions(-) diff --git a/docs/src/forcing_terms.md b/docs/src/forcing_terms.md index bb5390257a..4685b2a15e 100644 --- a/docs/src/forcing_terms.md +++ b/docs/src/forcing_terms.md @@ -1,7 +1,7 @@ # Forcing Terms `ForcingTerms` specifies the external magnetic perturbation that drives the perturbed equilibrium: the spectrum of the normal field on the control surface at `psilim`, given either as a file of (m, n) amplitudes or computed by Biot–Savart from coil geometry. -The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs. Every source it holds (a `forcing_data_file`, coil sets) drives the plasma, and their spectra are summed into the `ForcingField` that `perturbed_equilibrium` applies to the plasma response. +The `[ForcingTerms]` section is read when `[PerturbedEquilibrium]` runs. Every source it holds (a `forcing_data_file`, coil sets, magnetic materials) drives the plasma, and their spectra are summed into the `ForcingField` that `perturbed_equilibrium` applies to the plasma response. ## Normalization @@ -108,6 +108,21 @@ forcing_grid = CoilForcingGrid(equil, cfg, n; psi=ffs.psilim) spectra = [coil_forcing_modes(cs, forcing_grid, n, m_low, m_high) for cs in coil_sets] ``` +## Magnetic materials + +Each `[[ForcingTerms.magnetic_material]]` block adds a set of ferritic elements, closed triangulated polyhedra read from an HDF5 geometry file (`magnetic_material//vertices`, `triangles`, `element_offsets`; see `read_magnetic_material_h5`). +Every element is saturated along the equilibrium field at its centroid, ``M = f\,\mu_0 M_s\,\hat B_0/\mu_0``, and its field is the exact field of a uniformly magnetized polyhedron: a surface charge ``M\cdot\hat n`` on each face, each triangle integrated in closed form (Van Oosterom & Strackee, IEEE Trans. Biomed. Eng. 30, 125 (1983)). +That field is sampled on the same `mtheta_coil × nzeta_coil` boundary grid as the coils. +The equilibrium must carry its flux map outside the plasma (a g-file or IMAS), every vertex must lie inside that map's grid and outside the separatrix, and no control-surface point may lie inside an element. + +```toml +[[ForcingTerms.magnetic_material]] +name = "iter_inserts" # set to read from the geometry file +h5_file = "iter_inserts.h5" # magnetic_material// geometry +saturation_field = 1.7 # μ₀M_s, in tesla +fill_fraction = 1.0 # magnetic fraction of each element's volume +``` + ## Outputs The applied spectrum is written with the response: `PerturbedEquilibrium/ForcingModes/` (`m`, `n`, `amplitude`) and the control-surface spectra `PerturbedEquilibrium/forcing_b`, `forcing_b_root_area` and `forcing_b_area` (see [Perturbed Equilibrium](perturbed_equilibrium.md)). diff --git a/src/Deck.jl b/src/Deck.jl index 4c323166f5..3ea5435af2 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -407,14 +407,16 @@ end The `[ForcingTerms]` section of a parsed deck as a control struct, defaults when absent, with its relative file paths resolved against the deck directory `path`. The `[[ForcingTerms.coil_set]]` -array of tables is passed through as `coil_sets_raw`. +and `[[ForcingTerms.magnetic_material]]` arrays of tables are passed through as `coil_sets_raw` and `magnetic_materials_raw`. """ function forcing_terms_control(inputs::AbstractDict, path::AbstractString) "ForcingTerms" in keys(inputs) || return ForcingTerms.ForcingTermsControl() forcing_raw = _deck_paths(inputs["ForcingTerms"], path, ("forcing_data_file", "dat_dir")) coil_sets_raw = Dict{String,Any}[_deck_paths(d, path, ("dat_file", "h5_file")) for d in get(forcing_raw, "coil_set", Dict{String,Any}[])] - kwargs = section_keywords(_without(forcing_raw, "coil_set"), "ForcingTerms", _struct_fields(ForcingTerms.ForcingTermsControl, (:coil_sets_raw,))) - return ForcingTerms.ForcingTermsControl(; kwargs..., coil_sets_raw=coil_sets_raw) + magnetic_materials_raw = Dict{String,Any}[_deck_paths(d, path, ("h5_file",)) for d in get(forcing_raw, "magnetic_material", Dict{String,Any}[])] + kwargs = section_keywords(_without(_without(forcing_raw, "coil_set"), "magnetic_material"), "ForcingTerms", + _struct_fields(ForcingTerms.ForcingTermsControl, (:coil_sets_raw, :magnetic_materials_raw))) + return ForcingTerms.ForcingTermsControl(; kwargs..., coil_sets_raw, magnetic_materials_raw) end """ @@ -485,8 +487,8 @@ function parse_deck(inputs::AbstractDict, path::AbstractString) forcing = forcing_terms_control(inputs, path) if haskey(inputs, "ErrorFields") perturbed_equilibrium === nothing && error("[ErrorFields] needs a [PerturbedEquilibrium] section") - !isempty(forcing.coil_sets_raw) && isempty(forcing.forcing_data_file) || - error("[ErrorFields] linearizes coil geometry, so [ForcingTerms] must hold coil sets and no forcing_data_file") + !isempty(forcing.coil_sets_raw) && isempty(forcing.forcing_data_file) && isempty(forcing.magnetic_materials_raw) || + error("[ErrorFields] linearizes coil geometry, so [ForcingTerms] must hold coil sets and no forcing_data_file or magnetic material") end tearing_model = haskey(inputs, "Tearing") ? get(inputs["Tearing"], "inner_model", nothing) : nothing match_model = match === nothing ? nothing : _inner_model_token(match.model) @@ -612,8 +614,9 @@ end # [ForcingTerms] of a forcing control, its coil sets as [[ForcingTerms.coil_set]]. function _forcing_table(ctrl::ForcingTerms.ForcingTermsControl) - table = _deck_table(ctrl, (:coil_sets_raw,)) + table = _deck_table(ctrl, (:coil_sets_raw, :magnetic_materials_raw)) isempty(ctrl.coil_sets_raw) || (table["coil_set"] = Any[_deck_out(d) for d in ctrl.coil_sets_raw]) + isempty(ctrl.magnetic_materials_raw) || (table["magnetic_material"] = Any[_deck_out(d) for d in ctrl.magnetic_materials_raw]) return table end diff --git a/src/Display.jl b/src/Display.jl index e0c3a544f0..188f2382c5 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -11,7 +11,7 @@ using .PerturbedEquilibrium: PerturbedEquilibriumState using .KineticForces: MethodResult, KineticForcesState using .ErrorFields: MonteCarloResult, RiskResult, EFCCoupling using .Tearing: GrowthRateResult -using .ForcingTerms: ForcingFile, ForcingCoils, ForcingSpectrum, ForcingLeaf, ForcingFieldSum +using .ForcingTerms: ForcingFile, ForcingCoils, ForcingSpectrum, ForcingMagneticMaterial, ForcingLeaf, ForcingFieldSum _fmt(x::Real) = @sprintf("%.4g", x) _fmt(::Nothing) = "—" @@ -298,6 +298,7 @@ function _field_label(f::ForcingCoils) sets = [!isempty(sc.name) ? sc.name : !isempty(sc.source) ? sc.source : "coil set" for sc in c.coil_sets] return string(isempty(c.machine) ? "" : c.machine * " ", "coils ", _list(sets)) end +_field_label(f::ForcingMagneticMaterial) = string("magnetic material ", _list([m.name for m in f.materials])) _field_label(f::ForcingSpectrum) = string("spectrum of ", _plural(length(f.modes), "mode"), ", n = ", _irange([m.n for m in f.modes])) Base.show(io::IO, f::ForcingLeaf) = print(io, "ForcingField(", f.scale == 1 ? "" : _weight(f.scale), _field_label(f), ")") diff --git a/src/ForcingTerms/ForcingTerms.jl b/src/ForcingTerms/ForcingTerms.jl index 1af7581501..0d15ab0b50 100644 --- a/src/ForcingTerms/ForcingTerms.jl +++ b/src/ForcingTerms/ForcingTerms.jl @@ -4,6 +4,7 @@ module ForcingTerms using DelimitedFiles using HDF5 using LinearAlgebra +using Printf: @sprintf using StaticArrays: SVector import ..Equilibrium @@ -25,13 +26,14 @@ Forcing file: - `forcing_data_file::String` - Path to a forcing-mode table (n, m, complex amplitude); empty for none - `forcing_data_format::String` - Format of the forcing-mode table: "ascii" or "hdf5" -Coils: +Coils and magnetic materials (both sampled on the `mtheta_coil × nzeta_coil` boundary grid): - `machine::String` - Machine name prefix for .dat files (e.g. "d3d") - `dat_dir::String` - Directory containing .dat files; defaults to bundled `coil_geometries/` - `mtheta_coil::Int` - Poloidal grid resolution for boundary field evaluation (default: 480) - `nzeta_coil::Int` - Toroidal grid resolution; 0 = auto, 32(|n| + 1) - `coil_sets_raw::Vector{Dict{String,Any}}` - Parsed `[[ForcingTerms.coil_set]]` TOML blocks + - `magnetic_materials_raw::Vector{Dict{String,Any}}` - Parsed `[[ForcingTerms.magnetic_material]]` TOML blocks; see [`MagneticMaterialConfig`](@ref) """ @kwdef struct ForcingTermsControl forcing_data_file::String = "" @@ -42,6 +44,7 @@ Coils: mtheta_coil::Int = 480 nzeta_coil::Int = 0 coil_sets_raw::Vector{Dict{String,Any}} = Dict{String,Any}[] + magnetic_materials_raw::Vector{Dict{String,Any}} = Dict{String,Any}[] end """ @@ -273,6 +276,7 @@ drive several solves. ForcingField(cfg::CoilConfig; scale=1.0) ForcingField(ctrl::ForcingTermsControl; scale=1.0) ForcingField(modes::Vector{ForcingMode}; scale=1.0) + ForcingField(materials::Vector{MagneticMaterial}; mtheta_coil=480, nzeta_coil=0, scale=1.0) The first form points at a forcing-mode file, `format` defaulting to `"hdf5"` for an `.h5` or `.hdf5` extension and `"ascii"` otherwise. The second form takes one coil set or a vector of them, each a @@ -288,7 +292,9 @@ Its remaining `kwargs` are the [`ForcingTermsControl`](@ref) coil settings (`mac `nzeta_coil`). The third form takes the same coil description already parsed, and the fourth a deck's `[ForcingTerms]` section, the sum of every source it holds. The file forms return a [`ForcingFile`](@ref) leaf and the coil forms a [`ForcingCoils`](@ref) leaf. The last form takes a control-surface spectrum computed elsewhere, already in the unit-norm `Φ_x` convention, and returns a -spectrum-literal leaf ([`ForcingSpectrum`](@ref)). +spectrum-literal leaf ([`ForcingSpectrum`](@ref)). The material form takes one [`MagneticMaterial`](@ref) set or several, +saturated along the equilibrium field, whose field is sampled on the `mtheta_coil × nzeta_coil` boundary grid, and +returns a [`ForcingMagneticMaterial`](@ref) leaf. ## Algebra @@ -362,20 +368,41 @@ struct ForcingSpectrum <: ForcingField scale::ComplexF64 end +""" + ForcingMagneticMaterial + +A magnetic-material [`ForcingField`](@ref) leaf: sets of ferritic elements, each saturated along the equilibrium field at +its centroid when materialized, whose exact field is sampled on the control surface, plus a complex weight. Built by +`ForcingField(materials)`; scalar multiplication rescales the weight. + +## Fields + + - `materials::Vector{MagneticMaterial}` - The material sets. + - `mtheta::Int` - Poloidal points of the boundary grid. + - `nzeta::Int` - Toroidal points of the boundary grid; 0 = auto, 32(|n| + 1). + - `scale::ComplexF64` - The source's weight in a linear combination, as for [`ForcingFile`](@ref). +""" +struct ForcingMagneticMaterial <: ForcingField + materials::Vector{MagneticMaterial} + mtheta::Int + nzeta::Int + scale::ComplexF64 +end + # A single-source ForcingField: one forcing description plus its weight. -const ForcingLeaf = Union{ForcingFile,ForcingCoils,ForcingSpectrum} +const ForcingLeaf = Union{ForcingFile,ForcingCoils,ForcingSpectrum,ForcingMagneticMaterial} """ ForcingFieldSum -A lazy linear combination of [`ForcingFile`](@ref), [`ForcingCoils`](@ref) and [`ForcingSpectrum`](@ref) leaves, built by `+`/`-` +A lazy linear combination of [`ForcingFile`](@ref), [`ForcingCoils`](@ref), [`ForcingSpectrum`](@ref) and [`ForcingMagneticMaterial`](@ref) leaves, built by `+`/`-` on [`ForcingField`](@ref)s. Holds the flattened term list; scalar multiplication distributes onto the leaves. Materialization evaluates each term against the equilibrium and sums the mode amplitudes — valid because the perturbed-equilibrium response is linear in the forcing. ## Fields - - `terms::Vector{Union{ForcingFile,ForcingCoils,ForcingSpectrum}}` - The flattened weighted leaves. + - `terms::Vector{ForcingLeaf}` - The flattened weighted leaves. """ struct ForcingFieldSum <: ForcingField terms::Vector{ForcingLeaf} @@ -449,7 +476,15 @@ function ForcingField(ctrl::ForcingTermsControl; scale::Number=1.0) sources = ForcingField[] isempty(ctrl.coil_sets_raw) || push!(sources, ForcingField(CoilConfig(ctrl))) isempty(ctrl.forcing_data_file) || push!(sources, ForcingField(ctrl.forcing_data_file; format=ctrl.forcing_data_format)) - isempty(sources) && throw(ArgumentError("ForcingField: [ForcingTerms] holds no forcing source; give [[ForcingTerms.coil_set]] blocks or a forcing_data_file")) + isempty(ctrl.magnetic_materials_raw) || + push!(sources, ForcingField(load_magnetic_material.(_parse_magnetic_material_config.(ctrl.magnetic_materials_raw)); + ctrl.mtheta_coil, ctrl.nzeta_coil)) + isempty(sources) && throw( + ArgumentError( + "ForcingField: [ForcingTerms] holds no forcing source; give [[ForcingTerms.coil_set]] " * + "or [[ForcingTerms.magnetic_material]] blocks, or a forcing_data_file" + ) + ) return scale * sum(sources) end @@ -462,6 +497,12 @@ ForcingField(coil_sets::AbstractVector; scale::Number=1.0, kwargs...) = ForcingField(ForcingTermsControl(; coil_sets_raw=_coil_dict.(coil_sets), kwargs...); scale) ForcingField(coil_set::Union{AbstractDict,NamedTuple}; kwargs...) = ForcingField([coil_set]; kwargs...) +function ForcingField(materials::Vector{MagneticMaterial}; mtheta_coil::Int=480, nzeta_coil::Int=0, scale::Number=1.0) + isempty(materials) && throw(ArgumentError("ForcingField: a magnetic material source needs at least one set")) + return ForcingMagneticMaterial(materials, mtheta_coil, nzeta_coil, ComplexF64(scale)) +end +ForcingField(material::MagneticMaterial; kwargs...) = ForcingField([material]; kwargs...) + function ForcingField(modes::Vector{ForcingMode}; scale::Number=1.0) isempty(modes) && throw(ArgumentError("ForcingField: a spectrum needs at least one forcing mode")) all(m -> isfinite(m.amplitude), modes) || throw(ArgumentError("ForcingField: a spectrum amplitude is not finite")) @@ -480,6 +521,7 @@ Base.:-(a::ForcingField, b::ForcingField) = a + (-1 * b) Base.:*(c::Number, f::ForcingFile) = ForcingFile(f.path, f.format, ComplexF64(c) * f.scale) Base.:*(c::Number, f::ForcingCoils) = ForcingCoils(f.config, ComplexF64(c) * f.scale) Base.:*(c::Number, f::ForcingSpectrum) = ForcingSpectrum(f.modes, ComplexF64(c) * f.scale) +Base.:*(c::Number, f::ForcingMagneticMaterial) = ForcingMagneticMaterial(f.materials, f.mtheta, f.nzeta, ComplexF64(c) * f.scale) Base.:*(c::Number, f::ForcingFieldSum) = ForcingFieldSum([c * t for t in f.terms]) Base.:*(f::ForcingField, c::Number) = c * f diff --git a/src/ForcingTerms/MagneticMaterial.jl b/src/ForcingTerms/MagneticMaterial.jl index e9a6c8d662..6f7606ff85 100644 --- a/src/ForcingTerms/MagneticMaterial.jl +++ b/src/ForcingTerms/MagneticMaterial.jl @@ -191,8 +191,8 @@ end compute_magnetic_material_field!(B_R, B_phi, B_Z, obs_R, obs_phi, obs_Z, material, magnetization) Exact field of `material` with each element uniformly magnetized, `magnetization` `[3, nelement]` (Cartesian, A/m), -at observation points outside the material given in cylindrical coordinates (m, rad, m), as cylindrical components -in tesla. Uniform M is a surface charge σ = M·n̂ on each face, and a flat triangle with constant charge has a +at observation points given in cylindrical coordinates (m, rad, m), as cylindrical components in tesla; a point +inside an element is an error. Uniform M is a surface charge σ = M·n̂ on each face, and a flat triangle with constant charge has a closed-form field: ∫ (r − r′)/|r − r′|³ dA′ = n̂ Ω + Σ_edges m̂ₑ ln[(R₁ + R₂ + ℓ)/(R₁ + R₂ − ℓ)], with Ω the signed solid angle the triangle subtends (Van Oosterom & Strackee, IEEE Trans. Biomed. Eng. 30, 125 (1983)) and m̂ₑ its outward in-plane edge normals. Then B = μ₀/4π · Σ_faces σ (n̂ Ω + Σ_edges m̂ₑ Lₑ). Threaded over observation points; @@ -214,9 +214,11 @@ function compute_magnetic_material_field!( nelement = length(material.element_offsets) - 1 size(magnetization) == (3, nelement) || throw(DimensionMismatch("magnetization must be 3 × $nelement, got $(size(magnetization))")) faces = _charged_faces(material, magnetization) + lo, hi = _element_boxes(material) Threads.@threads for i in 1:nobs sp, cp = sincos(obs_phi[i]) r = SVector(obs_R[i] * cp, obs_R[i] * sp, obs_Z[i]) + _check_outside(material, lo, hi, r) H = zero(SVector{3,Float64}) for f in faces H += f.σ * _triangle_kernel(r, f) @@ -228,6 +230,34 @@ function compute_magnetic_material_field!( return nothing end +# Bounding box of each element, [3, nelement] lower and upper corners. +function _element_boxes(material::MagneticMaterial) + nelement = length(material.element_offsets) - 1 + lo, hi = fill(Inf, 3, nelement), fill(-Inf, 3, nelement) + for e in 1:nelement, t in (material.element_offsets[e]+1):material.element_offsets[e+1], k in 1:3 + v = view(material.vertices, :, material.triangles[k, t]) + lo[:, e] .= min.(view(lo, :, e), v) + hi[:, e] .= max.(view(hi, :, e), v) + end + return lo, hi +end + +# The field formula holds only outside the material: the solid angles of an element's faces sum to ±4π inside it, 0 outside. +function _check_outside(material::MagneticMaterial, lo, hi, r) + for e in axes(lo, 2) + all(k -> lo[k, e] <= r[k] <= hi[k, e], 1:3) || continue + Ω = 0.0 + for t in (material.element_offsets[e]+1):material.element_offsets[e+1] + a, b, c = (SVector{3,Float64}(view(material.vertices, :, material.triangles[k, t])) - r for k in 1:3) + na, nb, nc = norm(a), norm(b), norm(c) + Ω -= 2 * atan(dot(a, cross(b, c)), na * nb * nc + dot(a, b) * nc + dot(a, c) * nb + dot(b, c) * na) + end + abs(Ω) > 2π && throw(ArgumentError(@sprintf("magnetic material \"%s\": the point (x, y, z) = (%.3f, %.3f, %.3f) m lies inside element %d", + material.name, r[1], r[2], r[3], e))) + end + return nothing +end + # A triangle with its unit normal, outward in-plane edge normals, edge lengths and surface charge σ = M·n̂. struct _ChargedFace v::NTuple{3,SVector{3,Float64}} @@ -266,6 +296,56 @@ end return Ω * f.n + edges end -export MagneticMaterial, MagneticMaterialConfig, load_magnetic_material +""" + saturated_magnetization(material, equil) -> Matrix{Float64} + +Magnetization `[3, nelement]` in A/m (Cartesian) of each element of `material`, saturated along the equilibrium +field at its centroid: M = f μ₀M_s B̂₀ / μ₀ with f the fill fraction. Every vertex must lie inside the equilibrium's flux +grid and outside the separatrix (ψ_N ≥ 1). +""" +function saturated_magnetization(material::MagneticMaterial, equil::Equilibrium.PlasmaEquilibrium) + V = material.vertices + psi_norm = Equilibrium.equilibrium_field(equil, hypot.(V[1, :], V[2, :]), V[3, :]).psi_norm + k = findfirst(<(1), psi_norm) + k === nothing || throw( + ArgumentError( + @sprintf( + "magnetic material \"%s\": vertex %d at (R, Z) = (%.3f, %.3f) m lies at ψ_N = %.4f, inside the separatrix", + material.name, k, hypot(V[1, k], V[2, k]), V[3, k], psi_norm[k]) + ) + ) + c = material.centroid + φ = atan.(c[2, :], c[1, :]) + B = Equilibrium.equilibrium_field(equil, hypot.(c[1, :], c[2, :]), c[3, :]) + Bx, By = B.B_R .* cos.(φ) .- B.B_phi .* sin.(φ), B.B_R .* sin.(φ) .+ B.B_phi .* cos.(φ) + Ms = material.fill_fraction * material.saturation_field / (4π * MU0_OVER_4PI) + Bmag = sqrt.(Bx .^ 2 .+ By .^ 2 .+ B.B_Z .^ 2) + return Ms .* vcat((Bx ./ Bmag)', (By ./ Bmag)', (B.B_Z ./ Bmag)') +end + +""" + material_forcing_modes(materials, magnetizations, equil, cfg::CoilConfig, n, m_low, m_high; psi) -> Vector{ForcingMode} + +Unit-norm forcing modes (`Φ_x`) of toroidal mode `n` and poloidal modes `m_low:m_high` driven by `materials`, each +magnetized by the matching entry of `magnetizations` (see [`saturated_magnetization`](@ref)), on the control surface +`psi` sampled on the boundary grid of `cfg` (`mtheta_coil`, `nzeta_coil`). +""" +function material_forcing_modes(materials::Vector{MagneticMaterial}, magnetizations, equil::Equilibrium.PlasmaEquilibrium, + cfg::CoilConfig, n::Int, m_low::Int, m_high::Int; psi::Float64) + forcing_grid = CoilForcingGrid(equil, cfg, n; psi) + nobs = length(forcing_grid.obs_R) + B_R, B_Z = zeros(nobs), zeros(nobs) + B = (zeros(nobs), zeros(nobs), zeros(nobs)) + for (material, M) in zip(materials, magnetizations) + compute_magnetic_material_field!(B..., forcing_grid.obs_R, forcing_grid.obs_phi, forcing_grid.obs_Z, material, M) + B_R .+= B[1] + B_Z .+= B[3] + end + bn = zeros(forcing_grid.grid.mtheta, forcing_grid.grid.nzeta) + project_normal_flux!(bn, B_R, B_Z, forcing_grid.grid) + return fourier_decompose_bn(bn, forcing_grid.grid, n, m_low, m_high) +end + +export MagneticMaterial, MagneticMaterialConfig, load_magnetic_material, saturated_magnetization, material_forcing_modes export read_magnetic_material_h5, write_magnetic_material_h5, save_magnetic_material_to_h5, load_magnetic_material_from_h5_group! export compute_magnetic_material_field! diff --git a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl index 63e3aa6dd5..865f731ec0 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -203,6 +203,25 @@ function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTer return modes, ForcingTerms.CoilSet[] end +""" + materialize_forcing_modes(ffs, field::ForcingTerms.ForcingMagneticMaterial; verbose=false, kwargs...) -> (modes, coil_sets) + +Materialize a magnetic-material leaf: saturate each set along the equilibrium field, sample its exact field on the +control surface `ffs.psilim` for every toroidal mode of the solve, and apply the leaf's weight. No coil geometry is produced. +""" +function materialize_forcing_modes(ffs::ForceFreeStatesResult, field::ForcingTerms.ForcingMagneticMaterial; verbose::Bool=false, kwargs...) + equil = ffs.equil + magnetizations = [ForcingTerms.saturated_magnetization(material, equil) for material in field.materials] + cfg = ForcingTerms.CoilConfig(; mtheta_coil=field.mtheta, nzeta_coil=field.nzeta) + modes = ForcingMode[] + for n in ffs.nlow:ffs.nhigh + verbose && @info "Computing magnetic material forcing modes for n = $n" + append!(modes, ForcingTerms.material_forcing_modes(field.materials, magnetizations, equil, cfg, n, ffs.mlow, ffs.mhigh; psi=ffs.psilim)) + end + field.scale == 1 || (modes = [ForcingMode(; n=mode.n, m=mode.m, amplitude=field.scale * mode.amplitude) for mode in modes]) + return modes, ForcingTerms.CoilSet[] +end + """ materialize_forcing_modes(ffs, field::ForcingTerms.ForcingSpectrum; kwargs...) -> (modes, coil_sets) diff --git a/src/Rerun.jl b/src/Rerun.jl index c7363b7883..a09648bf4a 100644 --- a/src/Rerun.jl +++ b/src/Rerun.jl @@ -321,6 +321,7 @@ function build_inputs_from_h5(args::Vector{String}) ft = get!(inputs, "ForcingTerms", Dict{String,Any}()) # The recorded modes are the whole forcing, so the replay drops every other source. delete!(ft, "coil_set") + delete!(ft, "magnetic_material") ft["forcing_data_file"] = forcing_file ft["forcing_data_format"] = "hdf5" end diff --git a/test/runtests_magnetic_material.jl b/test/runtests_magnetic_material.jl index 8c474dc9ee..fd8d15a897 100644 --- a/test/runtests_magnetic_material.jl +++ b/test/runtests_magnetic_material.jl @@ -161,4 +161,64 @@ sphere_points(d; c=zeros(3)) = reduce(hcat, [c .+ d .* [sin(t) * cos(p), sin(t) @test_throws "unknown keys" ForcingTerms._parse_magnetic_material_config(Dict{String,Any}("name" => "plate", "mu0Ms" => 1.6)) @test_throws "needs a saturation_field" load_magnetic_material(MagneticMaterialConfig(; name="plate", h5_file=geometry)) end + + @testset "a point inside an element is an error" begin + @test_throws "lies inside element 1" material_field(plate, zeros(3, 1) .+ [0.0, 0.0, Ms], reshape([0.01, -0.02, 0.005], 3, 1)) + end + + @testset "saturated along the equilibrium field, driving only n = k·N from a ring" begin + EQ = GeneralizedPerturbedEquilibrium.Equilibrium + FT = GeneralizedPerturbedEquilibrium.ForcingTerms + gfile = joinpath(@__DIR__, "..", "examples", "DIIID-like_ideal_example", "TkMkr_D3Dlike_Hmode.geqdsk") + equil = EQ.PlasmaEquilibrium( + EQ.EquilibriumConfig(; eq_filename=gfile, eq_type="efit", jac_type="hamada", + grid_type="core_edge_packed", psilow=0.01, psihigh=0.995, mpsi=64, mtheta=256) + ) + rot(φ) = [cos(φ) -sin(φ) 0; sin(φ) cos(φ) 0; 0 0 1] + R0, Z0, hb = 2.38, equil.zo, [0.015, 0.04, 0.05] # outboard, between the separatrix and the flux grid's edge + ring(N) = box_material([(hb, rot(φ) * [R0, 0.0, Z0], rot(φ)) for φ in 2π .* (0:N-1) ./ N]; saturation_field=1.6, fill_fraction=0.8) + + one = box_material([(hb, [R0, 0.0, Z0], I(3))]; saturation_field=1.6, fill_fraction=0.8) + M = saturated_magnetization(one, equil) + B0 = EQ.equilibrium_field(equil, [R0], [Z0]) + @test norm(M) ≈ 0.8 * 1.6 / MU0 + @test M[:, 1] ./ norm(M) ≈ normalize([B0.B_R[1], B0.B_phi[1], B0.B_Z[1]]) # at φ = 0, (x, y, z) = (R, φ, Z) + inside = box_material([(hb, [equil.ro + 0.3, 0.0, equil.zo], I(3))]) + @test_throws "inside the separatrix" saturated_magnetization(inside, equil) + @test_throws "outside the equilibrium's flux grid" saturated_magnetization(box_material([(hb, [3.0, 0.0, 0.0], I(3))]), equil) + + # Axisymmetric B₀ makes every element of a ring identical up to rotation, so only n = k·N survives. + N = 8 + mats = [ring(N)] + mags = [saturated_magnetization(mats[1], equil)] + cfg = FT.CoilConfig(; mtheta_coil=128) + psi = equil.rzphi_xs[end] + peak(n) = maximum(abs(mode.amplitude) for mode in material_forcing_modes(mats, mags, equil, cfg, n, -10, 20; psi)) + @test peak(N) > 0 + @test peak(1) < 1e-8 * peak(N) && peak(3) < 1e-8 * peak(N) + # Breaking the ring by removing one element drives n = 1. + broken = box_material([(hb, rot(φ) * [R0, 0.0, Z0], rot(φ)) for φ in 2π .* (1:N-1) ./ N]; saturation_field=1.6, fill_fraction=0.8) + @test maximum(abs(m.amplitude) for m in material_forcing_modes([broken], [saturated_magnetization(broken, equil)], equil, cfg, 1, -10, 20; psi)) > + 1e-3 * peak(N) + end + + @testset "a ForcingField leaf, from the API and from a deck" begin + GPEC = GeneralizedPerturbedEquilibrium + dir = mktempdir() + geometry = write_magnetic_material_h5(joinpath(dir, "plates.h5"), [box_material([(h, [9.0, 0.0, 0.0], I(3))])]) + leaf = ForcingField(only(read_magnetic_material_h5(geometry)); nzeta_coil=64) + @test leaf isa GPEC.ForcingTerms.ForcingMagneticMaterial && leaf.nzeta == 64 && leaf.mtheta == 480 + @test (2im * leaf).scale == 2im && repr(leaf) == "ForcingField(magnetic material boxes)" + write(joinpath(dir, "forcing.dat"), "1 2 1e-4 0.0\n") + block = Dict{String,Any}("name" => "boxes", "h5_file" => "plates.h5", "saturation_field" => 1.7, "fill_fraction" => 0.5) + ctrl = GPEC.forcing_terms_control( + Dict{String,Any}("ForcingTerms" => Dict{String,Any}("forcing_data_file" => "forcing.dat", + "mtheta_coil" => 96, "magnetic_material" => [block])), dir) + field = ForcingField(ctrl) + @test [typeof(t) for t in field.terms] == [GPEC.ForcingTerms.ForcingFile, GPEC.ForcingTerms.ForcingMagneticMaterial] + material = field.terms[2] + @test material.mtheta == 96 && material.nzeta == 0 + @test only(material.materials).saturation_field == 1.7 && only(material.materials).fill_fraction == 0.5 + @test GPEC._forcing_table(ctrl)["magnetic_material"][1]["h5_file"] == joinpath(dir, "plates.h5") + end end From d539a3878e6e1a01769a48f1430171240225b650 Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Thu, 26 Nov 2026 16:04:22 +0100 Subject: [PATCH 25/27] ForcingTerms - PERF - Decompose the control-surface field without building the Fourier basis repeatedly --- src/ForcingTerms/CoilFourier.jl | 18 +++++------------- test/runtests_coils.jl | 8 ++++++++ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/ForcingTerms/CoilFourier.jl b/src/ForcingTerms/CoilFourier.jl index b361b9dce8..bf1086b39a 100644 --- a/src/ForcingTerms/CoilFourier.jl +++ b/src/ForcingTerms/CoilFourier.jl @@ -171,21 +171,13 @@ function fourier_decompose_bn( ) mtheta = grid.mtheta nzeta = grid.nzeta - - # Build Fourier basis: exp(-i*(m*θ - n*ζ)) - # Using 3D call with npert=1, nlow=n gives shape (mpert, mtheta*nzeta) - basis = compute_fourier_coefficients(mtheta, m_low:m_high, nzeta, [n]) - - bn_flat = vec(bn) # column-major: bn_flat[i + (j-1)*mtheta] = bn[i,j] + @assert size(bn) == (mtheta, nzeta) scale = 2.0 / (mtheta * nzeta) - bmn = scale .* (basis * bn_flat) - - modes = ForcingMode[] - for (idx, m) in enumerate(m_low:m_high) - push!(modes, ForcingMode(; n=n, m=m, amplitude=bmn[idx])) - end - return modes + # The sum separates: Σ_i e^{-imθᵢ} Σ_j bn[i,j] e^{inζⱼ}, on the uniform θ = 2π(i-1)/mtheta, ζ = 2π(j-1)/nzeta grid. + bn_n = bn * cis.(n .* range(0; length=nzeta, step=2π / nzeta)) + θ = range(0; length=mtheta, step=2π / mtheta) + return [ForcingMode(; n=n, m=m, amplitude=scale * sum(bn_n[i] * cis(-m * θ[i]) for i in 1:mtheta)) for m in m_low:m_high] end """ diff --git a/test/runtests_coils.jl b/test/runtests_coils.jl index 2a12db7f8b..7726bb5113 100644 --- a/test/runtests_coils.jl +++ b/test/runtests_coils.jl @@ -275,6 +275,14 @@ end i == idx && continue @test abs(mode.amplitude) < 0.05 end + + # A general field against the full 2D basis the decomposition sums over. + bn_rand = [sin(3θ + 0.7) * cos(2ζ) + 0.3cos(7θ - ζ) + 0.1 * (i + 3j) / (mtheta + nzeta) for (i, θ) in enumerate(theta_grid), (j, ζ) in enumerate(zeta_grid)] + for n in (0, 1, 2, -3) + basis = ForcingTerms.compute_fourier_coefficients(mtheta, -12:12, nzeta, [n]) + direct = (2 / (mtheta * nzeta)) .* (basis * vec(bn_rand)) + @test [m.amplitude for m in ForcingTerms.fourier_decompose_bn(bn_rand, grid, n, -12, 12)] ≈ direct rtol = 1e-12 + end end # --------------------------------------------------------------------------- From 99f771bd49aafe8380160ccf82a4363b8b6fa84f Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Thu, 26 Nov 2026 20:00:14 +0100 Subject: [PATCH 26/27] PerturbedEquilibrium - FEATURE! - Record each forcing source's control-surface field and dominant-mode overlap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A perturbed equilibrium now keeps every forcing source's contribution beside the total. A source is a coil set, a forcing file (named after it), a spectrum literal or a magnetic material set; a new optional `group` key on [[ForcingTerms.coil_set]] and [[ForcingTerms.magnetic_material]] blocks, and ForcingField(materials; groups), reports sets sharing a label as one source named by it. Repeated names get a numeric suffix. Materialization returns each source's spectrum and the total is their sum. Each source's root-area-weighted field b̃ and its overlap with the dominant modes are written to PerturbedEquilibrium/ForcingSources/ (source_name, forcing_b_root_area on (mode, source), dominant_forcing_overlap on (rank, source)), and their columns sum to forcing_b_root_area and DominantMode/forcing_overlap. The torque response's T_source uses the same sources, so a magnetic material or a sum gets one column per source rather than one for the whole forcing, and coil runs no longer evaluate Biot-Savart a second time for it (coil_flux_spectra is removed). Tests check each coil set's b̃ against an independent build, T_source for separate and grouped coil sets, a forcing file as one source, the HDF5 round trip, group parsing from deck blocks and the API, and the grouping, naming and summing of sources. Co-Authored-By: Claude Opus 5.5 --- docs/development/hdf5-conventions.md | 2 +- docs/src/forcing_terms.md | 7 ++ docs/src/perturbed_equilibrium.md | 1 - src/Display.jl | 3 + src/ForcingTerms/CoilGeometry.jl | 3 + src/ForcingTerms/ForcingTerms.jl | 19 +-- src/ForcingTerms/MagneticMaterial.jl | 2 + .../PerturbedEquilibrium.jl | 116 +++++++++--------- .../PerturbedEquilibriumStructs.jl | 13 +- src/PerturbedEquilibrium/Response.jl | 2 + src/PerturbedEquilibrium/TorqueResponse.jl | 43 +------ src/PerturbedEquilibrium/Utils.jl | 18 ++- test/runtests_magnetic_material.jl | 24 ++++ test/runtests_torque_response.jl | 42 +++++-- 14 files changed, 183 insertions(+), 112 deletions(-) diff --git a/docs/development/hdf5-conventions.md b/docs/development/hdf5-conventions.md index edc98ead68..944df0f9f7 100644 --- a/docs/development/hdf5-conventions.md +++ b/docs/development/hdf5-conventions.md @@ -43,7 +43,7 @@ Top level (11 groups): | `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (the gal surface list, `gal_basis_output`-gated `Basis/`), `Solutions/Match/` (closed ξ profiles of a `[Match]` in the shared layout, on the grid of the Galerkin or Riccati outer solutions), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | | `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_raw_freeboundary`/`Delta_prime_raw_fixedboundary`/`Delta_EF`/`edge_response`, the free-boundary `Delta_prime_matrix`/`pest3_A`/`pest3_B`/`pest3_Gamma` and their `_fixedboundary` counterparts (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | -| `PerturbedEquilibrium/` | `ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | +| `PerturbedEquilibrium/` | `ForcingModes/`, `ForcingSources/` (each forcing source's b̃ and dominant-mode overlap, summing to the totals), `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | | `KineticForces/` | `/` (torque/energy profiles, `dTdpsi_ell` resolved by bounce harmonic on the `ell` scale, `KineticMatrices/`); multi-ion runs add `PerSpecies///` with the same per-method layout, summing to the top-level total | | `ErrorFields/` | `CoilSensitivities/` (per-coil-set control-surface spectra and their rigid shift/tilt derivatives, `DominantMode/` full-window projection); `MonteCarlo/` (intrinsic and corrected `\|δ\|` histograms over the sampled tolerances, per batch and averaged); `Risk/` (threshold density, `P(lock\|δ)`, locking probabilities, `ToleranceScan/`); `NTV/` (correction-coil overlap and NTV torque couplings per kAt) | | `Tearing/` | `PerSurface/` (+ `DpMatrix/`), `Roots/`, `LayerWidths/`, `Diagnostics/{ValidRoots,Poles,FilteredRoots}` (+ `*Winding` with `root_classification = winding`), `Scan/Surface_/`, `CriticalResonantField/` (+ `Scan/Surface_/`) | diff --git a/docs/src/forcing_terms.md b/docs/src/forcing_terms.md index 4685b2a15e..e4a2095baf 100644 --- a/docs/src/forcing_terms.md +++ b/docs/src/forcing_terms.md @@ -123,9 +123,16 @@ saturation_field = 1.7 # μ₀M_s, in tesla fill_fraction = 1.0 # magnetic fraction of each element's volume ``` +## Forcing sources + +Each coil set, forcing file, spectrum and magnetic material set is one forcing source, and the run records each source's contribution beside the total. +Give several `[[ForcingTerms.coil_set]]` or `[[ForcingTerms.magnetic_material]]` blocks the same `group = "