From 78020ca51ec2d332d24d7a376c87cef1c37cacff Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 4 Nov 2026 17:13:25 +0100 Subject: [PATCH 01/10] 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/10] 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/10] 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 b6bfdf98d9456b02f1dbe41e61f3f57dd146b83e Mon Sep 17 00:00:00 2001 From: Matthew Pharr Date: Wed, 18 Nov 2026 21:29:42 +0100 Subject: [PATCH 04/10] 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 05/10] =?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 06/10] =?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 07/10] 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 08/10] 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 09/10] 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 10/10] 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