diff --git a/docs/development/architecture.md b/docs/development/architecture.md index 5c5a4a356..a199d95e6 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -212,7 +212,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 e562d9e72..edc98ead6 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/` (the gal surface list, `gal_basis_output`-gated `Basis/`), `Solutions/Match/` (closed ξ profiles of a `[Match]` in the shared layout, on the grid of the Galerkin or Riccati outer solutions), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | -| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_matrix`/`Delta_prime_raw`/`Delta_coil`/`pest3_A`/`pest3_B`/`pest3_Gamma` (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | +| `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 0ea045475..9423892e7 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 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 `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 @@ -138,13 +138,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] +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. -The problem needs a Δ′ payload with coil-response columns, so it accepts Galerkin (`rpec_flag=true`) and Riccati (`vac_flag=true`) results. Both publish the outer solutions the match combines in `ffs.basis`; the composite inner-region profiles need Galerkin's `cut_solution=true`, and a Riccati basis always carries its cut solution. +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`). Both publish the outer solutions the match combines in `ffs.basis`, so either gives the matched `solution` and `wp`; the composite inner-region profiles need Galerkin's `cut_solution=true`, and a Riccati basis always carries its cut solution. `GGJModel()` is the closure-capable model; `SLAYERModel()` is slab-only and drives the tearing solve instead. ## Tearing stability diff --git a/docs/src/galerkin.md b/docs/src/galerkin.md index 56c274df5..2f37f90c2 100644 --- a/docs/src/galerkin.md +++ b/docs/src/galerkin.md @@ -23,25 +23,25 @@ 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'`` | -| `ForceFreeStates/Solutions/GalerkinIntegration/` | the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | -| `ForceFreeStates/Solutions/Match/` | with a `[Match]` section, the closed ``\xi`` profiles on the Galerkin grid | - -Nothing is written under `ForceFreeStates/FreeBoundaryStability/`. +| `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`, `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 ideal closed ``\xi`` profiles on the Galerkin grid (`error_field_response = true`), the surface list, the factorization used (`solver`) and, with `basis_output = true`, the `Basis/` group | +| `ForceFreeStates/Solutions/Match/` | with a `[Match]` section, the matched ``\xi`` profiles on the Galerkin grid, in place of the ideal ones | +| `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 aa6f53553..ceca95326 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 `"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/inner_layer.md b/docs/src/inner_layer.md index 115a7159b..5977b93a0 100644 --- a/docs/src/inner_layer.md +++ b/docs/src/inner_layer.md @@ -51,7 +51,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 b5b9d27a9..0d5c2e8e6 100644 --- a/docs/src/perturbed_equilibrium.md +++ b/docs/src/perturbed_equilibrium.md @@ -41,7 +41,9 @@ 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 | + +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: @@ -91,15 +93,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]`. -`"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 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 @@ -141,8 +143,9 @@ 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/*_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/docs/src/stability.md b/docs/src/stability.md index 76850be4c..ce22828f2 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" (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 @@ -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 ``` @@ -102,8 +102,9 @@ 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 Δ′ 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, `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/docs/src/workflow.md b/docs/src/workflow.md index a76507dd7..2519cb5c2 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 `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 @@ -68,7 +68,7 @@ Page: [Local Stability](ballooning.md). ### Match -Matches the outer-region Δ′ to a resistive inner layer (`inner_model = "GGJ"`, the default, or the drift-resistive `"CCC"`, with its options in an optional section of the same name) 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 default, or the drift-resistive `"CCC"`, with its options in an optional section of the same name) 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 `"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). @@ -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]`), the toroidal resistive-MHD `GGJ` (`[GGJ]`) or its drift-resistive extension `CCC` (`[CCC]`), 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" # [PerturbedEquilibrium] needs a dense ξ solution and no [Wall]; "Riccati" (the default) supplies one too [ForcingTerms] forcing_data_format = "coil" @@ -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 | @@ -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_SLAYER_example/gpec.toml b/examples/DIIID-like_SLAYER_example/gpec.toml index 3d7467449..c8085f58c 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 f8315025b..3089f801f 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 c7e2efdeb..ea441ca26 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 rpec coil-response columns (delta_coil). -# 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,14 +48,14 @@ 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) 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 +68,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. @@ -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 2b020622c..1c9f17ed4 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 54aae8451..71f8da0b8 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 fca015a0c..062459afe 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 ec1d684c7..b0102e0b1 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 6d491b40a..de32ed4b8 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 6a116042a..16b691375 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 c3741147b..434c7c171 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] @@ -59,11 +58,11 @@ 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) -# 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 167a20a35..5e5f0ff64 100644 --- a/examples/LAR_resistive_match_test/gpec.toml +++ b/examples/LAR_resistive_match_test/gpec.toml @@ -60,11 +60,11 @@ 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) -# 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/examples/Solovev_ideal_example/gpec.toml b/examples/Solovev_ideal_example/gpec.toml index b4ce76caa..fa7f22c5b 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 79d63b426..e24fd00d1 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 c49a8132a..755136ed3 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 0ba417cdb..2a6cdcf52 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 a5ed48d3e..09215540a 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 518e102b7..6e4cae56e 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 f37e0b511..db9c1bdd5 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 a990d5a64..b1e783eed 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/ext/GPECMakieExt/forcefreestates.jl b/ext/GPECMakieExt/forcefreestates.jl index cee4dc93c..084132807 100644 --- a/ext/GPECMakieExt/forcefreestates.jl +++ b/ext/GPECMakieExt/forcefreestates.jl @@ -37,15 +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]; xticks=WholeTicks(), 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]; xticks=WholeTicks(), 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] @@ -53,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 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) @@ -80,7 +102,8 @@ function _eigenvectors!(gl, d; nmodes=nothing) v = abs.(d.wt) m = d.mlow .+ (0:(size(v, 1)-1)) k = min(size(v, 2), something(nmodes, size(v, 2))) - ax = Axis(gl[1, 1]; xticks=WholeTicks(), 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]; xticks=WholeTicks(), xlabel="poloidal harmonic m", ylabel="eigenmode", yreversed=true, title, yticks=k <= 15 ? (1:k) : [1; 5:5: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)")) @@ -215,16 +238,16 @@ function FFS._plot_delta_prime_raw(dp; part=:real) end end -function FFS._plot_delta_coil(dp; part=:real) +function FFS._plot_delta_ef(dp; part=:real) return themed() do ns = length(dp.labels) - me = dp.mlow .+ (0:(size(dp.coil, 1)-1)) + me = dp.mlow .+ (0:(size(dp.ef, 1)-1)) fig = _figure((900, 560)) ax = _surface_side_axes!(fig[1, 1], dp.labels; xgroups=false, xticks=WholeTicks(), xlabel="applied edge harmonic m", - title=rich(_part_label(part, sub("Δ", "coil")), ": surface response to each edge harmonic"), + title=rich(_part_label(part, sub("Δ", "EF")), ": surface response to each edge harmonic"), limits=((me[1] - 0.5, me[end] + 0.5), (0.5, 2ns + 0.5))) - hm = _complex_heatmap!(ax, me, 1:(2ns), _part(dp.coil, part), part) - Colorbar(fig[1, 2], hm; label=_part_label(part, sub("Δ", "coil"))) + hm = _complex_heatmap!(ax, me, 1:(2ns), _part(dp.ef, part), part) + Colorbar(fig[1, 2], hm; label=_part_label(part, sub("Δ", "EF"))) fig end end diff --git a/ext/GPECMakieExt/perturbedequilibrium.jl b/ext/GPECMakieExt/perturbedequilibrium.jl index 19a19da46..ebb12d9a8 100644 --- a/ext/GPECMakieExt/perturbedequilibrium.jl +++ b/ext/GPECMakieExt/perturbedequilibrium.jl @@ -14,11 +14,12 @@ 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) - 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,20 +27,21 @@ 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) - :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/ext/GPECMakieExt/theme.jl b/ext/GPECMakieExt/theme.jl index 38f5ca4e2..7dbe1b0a2 100644 --- a/ext/GPECMakieExt/theme.jl +++ b/ext/GPECMakieExt/theme.jl @@ -56,6 +56,9 @@ function _num(v) return minus(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/regression-harness/cases/diiid_multi_n.toml b/regression-harness/cases/diiid_multi_n.toml index 0b0871270..2f616e0f6 100644 --- a/regression-harness/cases/diiid_multi_n.toml +++ b/regression-harness/cases/diiid_multi_n.toml @@ -159,11 +159,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/regression-harness/cases/diiid_n1_riccati.toml b/regression-harness/cases/diiid_n1_riccati.toml index 3dbbb2d9b..b9d9a28ef 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] @@ -21,18 +20,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 @@ -153,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 691b9c949..afe693ca0 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,12 +103,12 @@ label = "||gal match cout||" noise_threshold = 1e-6 order = 42 -# Penetrated resonant field at each layer center (msing × mcoil) — 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 @@ -112,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/src/Analysis/ForceFreeStates.jl b/src/Analysis/ForceFreeStates.jl index afcd7bf24..61dd0b18c 100644 --- a/src/Analysis/ForceFreeStates.jl +++ b/src/Analysis/ForceFreeStates.jl @@ -23,6 +23,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) @@ -33,30 +37,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 === :unit_edge && 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 - # An ODE integrator stores its profiles in ForwardIntegration, a matched solution in Match. - group = isempty(fid["$_FWD/xi_psi"]) ? _MATCH : _FWD - (; mlow=read(fid["Info/mlow"]), psi=read(fid["$group/psi"]), xi=read(fid["$group/xi_psi"])[:, 1, :], - dW=_first_energy(read(fid["$_FBS/eigenmode_energies"]))) + # An ODE integrator stores its profiles in ForwardIntegration, a Galerkin solve in GalerkinIntegration, a matched solution in Match. + group = !isempty(fid["$_FWD/xi_psi"]) ? _FWD : haskey(fid, "$_MATCH/xi_psi") ? _MATCH : _GAL + 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 != _FWD) + 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 @@ -73,23 +98,27 @@ function _edge_scan_data(h5path::AbstractString) end # The Δ′ family with "m/n" labels for the surfaces it spans: Galerkin solves across its in-band subset of the rational surfaces. -# `coil` is (edge harmonic × surface side), empty when the run computed no coil response. +# The free-boundary Δ′ and raw D′, or the fixed-boundary ones when the run has no vacuum. `ef` is Δ_EF as +# (edge harmonic × surface side), empty when the run computed none. function _delta_prime_data(r::ForceFreeStatesResult) dp = r.delta_prime - k = size(dp.matrix, 1) + blocks, raw = dp.freeboundary === nothing ? (dp.fixedboundary, dp.raw_fixedboundary) : (dp.freeboundary, dp.raw_freeboundary) + k = size(blocks.Delta, 1) g = r.galerkin m, n = g !== nothing && length(g.sing_m) == k ? (g.sing_m, g.sing_n) : ([s.m[1] for s in r.surfaces[1:k]], [s.n[1] for s in r.surfaces[1:k]]) - return (; matrix=dp.matrix, raw=dp.raw, coil=permutedims(dp.coil), labels=["$mi/$ni" for (mi, ni) in zip(m, n)], mlow=r.mlow) + return (; matrix=blocks.Delta, raw, ef=permutedims(dp.ef), labels=["$mi/$ni" for (mi, ni) in zip(m, n)], mlow=r.mlow) end function _delta_prime_data(h5path::AbstractString) h5open(h5path, "r") do fid - matrix = read(fid["SingularSurfaces/Delta_prime_matrix"]) + suffix = haskey(fid, "SingularSurfaces/Delta_prime_matrix") ? "" : "_fixedboundary" + matrix = read(fid["SingularSurfaces/Delta_prime_matrix$suffix"]) k = size(matrix, 1) group = haskey(fid, "$_GAL/rational_m") && length(fid["$_GAL/rational_m"]) == k ? _GAL : "SingularSurfaces" m, n = vec(read(fid["$group/rational_m"]))[1:k], vec(read(fid["$group/rational_n"]))[1:k] - coil = haskey(fid, "SingularSurfaces/Delta_coil") ? read(fid["SingularSurfaces/Delta_coil"]) : zeros(ComplexF64, 0, 2k) - (; matrix, raw=read(fid["SingularSurfaces/Delta_prime_raw"]), coil, labels=["$mi/$ni" for (mi, ni) in zip(m, n)], mlow=read(fid["Info/mlow"])) + ef = haskey(fid, "SingularSurfaces/Delta_EF") ? read(fid["SingularSurfaces/Delta_EF"]) : zeros(ComplexF64, 0, 2k) + raw = read(fid["SingularSurfaces/Delta_prime_raw_$(isempty(suffix) ? "freeboundary" : "fixedboundary")"]) + (; matrix, raw, ef, labels=["$mi/$ni" for (mi, ni) in zip(m, n)], mlow=read(fid["Info/mlow"])) end end @@ -118,7 +147,7 @@ function _plot_eigenvalues end function _plot_edge_stability_scan end function _plot_delta_prime end function _plot_delta_prime_raw end -function _plot_delta_coil end +function _plot_delta_ef end function _plot_cond_fbar end function _plot_ballooning_alpha_boundary end function _plot_ballooning_alpha_boundaries end @@ -299,14 +328,14 @@ function plot_delta_prime_raw(src::Source; part=:real, save_path=nothing) end """ - plot_delta_coil(src; part=:real, save_path=nothing) + plot_delta_ef(src; part=:real, save_path=nothing) -Plot Δ_coil, the response at each side of each rational surface to a unit source on each edge poloidal harmonic, -as a heatmap. +Plot Δ_EF, the small-solution coefficient at each side of each rational surface for a unit edge displacement in each +edge poloidal harmonic, as a heatmap. ### Arguments - - `src`: A Riccati `ForceFreeStatesResult` or a Galerkin one solved with `rpec_flag = true`, or the path of a `gpec.h5` it was saved to + - `src`: A Riccati or Galerkin `ForceFreeStatesResult` solved with `error_field_response = true`, or the path of a `gpec.h5` it was saved to ### Keyword arguments @@ -317,10 +346,10 @@ as a heatmap. A Makie `Figure`. """ -function plot_delta_coil(src::Source; part=:real, save_path=nothing) +function plot_delta_ef(src::Source; part=:real, save_path=nothing) _check_part(part) - _require(plot_delta_coil, src) - return _draw(_plot_delta_coil, _delta_prime_data(src); part, save_path) + _require(plot_delta_ef, src) + return _draw(_plot_delta_ef, _delta_prime_data(src); part, save_path) end """ @@ -437,7 +466,7 @@ register!(plot_energy_eigenvectors, (ForceFreeStatesResult, AbstractString), (:f register!(plot_edge_stability_scan, (ForceFreeStatesResult, AbstractString), (:edge_scan,), "edge energies against the truncation q") register!(plot_delta_prime, (ForceFreeStatesResult, AbstractString), (:delta_prime,), "Δ′ matrix between rational surfaces") register!(plot_delta_prime_raw, (ForceFreeStatesResult, AbstractString), (:delta_prime,), "raw outer-region matching matrix D′") -register!(plot_delta_coil, (ForceFreeStatesResult, AbstractString), (:delta_coil,), "Δ_coil: surface response to each edge harmonic") +register!(plot_delta_ef, (ForceFreeStatesResult, AbstractString), (:delta_ef,), "Δ_EF: surface response to each edge harmonic") register!(plot_cond_fbar, (ForceFreeStatesResult, AbstractString), (:kinetic_scan,), "cond(F̄) scan for kinetic singular surfaces") register!(plot_ballooning_alpha_boundary, (LocalStabilityResult, AbstractString), (:ballooning_scan,), "ballooning α against its first stability boundary") diff --git a/src/Analysis/PerturbedEquilibrium.jl b/src/Analysis/PerturbedEquilibrium.jl index 6ceabfe16..eee4ea367 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_prime=s.delta_prime, 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_prime=rd("Delta_prime"), 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), @@ -77,14 +91,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_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 -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 @@ -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,22 +180,24 @@ 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_prime(src; save_path=nothing) + plot_driven_delta_mn(src; asymptotic=nothing, 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 @@ -183,15 +205,17 @@ equilibrium's own Δ′ of a Riccati or Galerkin solve, see `ForceFreeStates.plo ### 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_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; asymptotic::Union{Nothing,Bool}=nothing, save_path=nothing) + _require(plot_driven_delta_mn, src) + 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) @@ -535,16 +598,16 @@ 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") -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 747d32e62..9d5b413a1 100644 --- a/src/Analysis/Registry.jl +++ b/src/Analysis/Registry.jl @@ -44,19 +44,19 @@ What each capability needs, worded as what to change in the run to get it. const REASONS = Dict{Symbol,String}( :equilibrium => "needs an equilibrium", :singular_surfaces => "needs rational surfaces in the integration domain", - :solution_profiles => "needs stored ξ profiles: use the Forward or Riccati integrator, or a matched Galerkin solve (unmatched Galerkin stores none)", + :solution_profiles => "needs stored ξ profiles: use the Forward or Riccati integrator, or Galerkin with error_field_response = true", :fixed_boundary_criterion => "needs the critical determinant scan: use the Forward or Riccati integrator (Galerkin computes none)", - :free_boundary => "needs the free-boundary energies: run with vac_flag = true and the Forward or Riccati integrator", + :free_boundary => "needs the free-boundary energies: run with vac_flag = true (Galerkin also needs error_field_response = true)", :edge_scan => "needs the edge stability scan: set dW_edge_scan_start below psilim", :delta_prime => "needs the Δ′ matrix: use the Riccati or Galerkin integrator (Forward computes none)", - :delta_coil => "needs Δ_coil: use the Riccati integrator, or Galerkin with rpec_flag = true", + :delta_ef => "needs Δ_EF: use Galerkin, or Riccati with vac_flag = true, with error_field_response = true", :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", @@ -89,8 +89,8 @@ function capabilities(r::ForceFreeStatesResult) diag === nothing || isempty(diag.crit_store) || push!(caps, :fixed_boundary_criterion) diag === nothing || isempty(diag.edge_scan.psi) || push!(caps, :edge_scan) r.free_boundary === nothing || isempty(r.free_boundary.et) || push!(caps, :free_boundary) - r.delta_prime === nothing || isempty(r.delta_prime.matrix) || push!(caps, :delta_prime) - r.delta_prime === nothing || isempty(r.delta_prime.coil) || push!(caps, :delta_coil) + r.delta_prime === nothing || push!(caps, :delta_prime) + r.delta_prime === nothing || isempty(r.delta_prime.ef) || push!(caps, :delta_ef) isempty(r.kinetic.scan_psi) || push!(caps, :kinetic_scan) return caps end @@ -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) @@ -132,15 +132,17 @@ end const _H5_CAPABILITIES = ( :equilibrium => "Equilibrium/Profiles/psi", :singular_surfaces => "SingularSurfaces/rational_psi", - :solution_profiles => ("ForceFreeStates/Solutions/ForwardIntegration/xi_psi", "ForceFreeStates/Solutions/Match/xi_psi"), + :solution_profiles => + ("ForceFreeStates/Solutions/ForwardIntegration/xi_psi", "ForceFreeStates/Solutions/GalerkinIntegration/xi_psi", "ForceFreeStates/Solutions/Match/xi_psi"), :fixed_boundary_criterion => "ForceFreeStates/Solutions/ForwardIntegration/crit", :edge_scan => "ForceFreeStates/EdgeScan/psi", :free_boundary => "ForceFreeStates/FreeBoundaryStability/eigenmode_energies", - :delta_prime => "SingularSurfaces/Delta_prime_matrix", - :delta_coil => "SingularSurfaces/Delta_coil", + :delta_prime => ("SingularSurfaces/Delta_prime_matrix", "SingularSurfaces/Delta_prime_matrix_fixedboundary"), + :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/Deck.jl b/src/Deck.jl index ece4f7589..7ca036360 100644 --- a/src/Deck.jl +++ b/src/Deck.jl @@ -33,14 +33,15 @@ 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)..., (k => "moved to [Forward]" for k in _FORWARD_DECK_KEYS)..., ("gal_$k" => "moved to [Match] as $k" for k in ("eta", "rho", "rotation", "gamma"))..., ("gal_inner_$k" => "moved to [GGJ] as $k" for k in ("xfac", "nx", "nq", "cutoff", "kmax"))..., ("gal_$k" => "moved to [Galerkin] as $k" for k in ("nx", "nq", "pfac", "dx0", "dx1", "dx2", "cutoff", "tol", "gnstep", - "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")), @@ -354,7 +355,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) inner_model = _selector(inputs["Match"], "Match", "inner_model", _TOROIDAL_LAYER_TOKENS, "GGJ") delete!(problem, :inner_model) @@ -477,8 +478,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/Display.jl b/src/Display.jl index bd09cdfa0..b08730f55 100644 --- a/src/Display.jl +++ b/src/Display.jl @@ -134,8 +134,9 @@ function Base.show(io::IO, fb::FreeBoundaryResult) end function Base.show(io::IO, d::DeltaPrimeData) - source = d.A === nothing ? "Riccati" : "Galerkin" - return print(io, "DeltaPrimeData(", source, ", ", _shape(d.matrix), ")") + boundaries = join([b for (b, blocks) in (("free", d.freeboundary), ("fixed", d.fixedboundary)) if blocks !== nothing], " + ") + msing = size(something(d.freeboundary, d.fixedboundary).Delta, 1) + return print(io, "DeltaPrimeData(", boundaries, " boundary, ", _plural(msing, "surface"), isempty(d.ef) ? "" : ", Δ_EF", ")") end function Base.show(io::IO, g::GalerkinResult) @@ -193,17 +194,18 @@ 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. function _delta_prime_labels(r::ForceFreeStates.ForceFreeStatesResult) - k = minimum(size(r.delta_prime.matrix)) + k = size(something(r.delta_prime.freeboundary, r.delta_prime.fixedboundary).Delta, 1) g = r.galerkin g !== nothing && length(g.sing_m) == k && return ["$(m)/$(n)" for (m, n) in zip(g.sing_m, g.sing_n)] length(r.surfaces) == k && return _surface_label.(r.surfaces) @@ -217,11 +219,14 @@ 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 - dp = r.delta_prime.matrix - _row(io, "Δ′_ii (ψ_N)", _list(["$l: $(_fmt(real(dp[i, i])))" for (i, l) in enumerate(_delta_prime_labels(r))]; max=4)) + free = r.delta_prime.freeboundary !== nothing + dp = something(r.delta_prime.freeboundary, r.delta_prime.fixedboundary).Delta + _row(io, free ? "Δ′_ii (ψ_N)" : "Δ′_ii fixed boundary (ψ_N)", _list(["$l: $(_fmt(real(dp[i, i])))" for (i, l) in enumerate(_delta_prime_labels(r))]; max=4)) end _row(io, "Solution", _solution_note(r)) r.galerkin === nothing || _row(io, "Galerkin", "$(_plural(r.galerkin.msing, "surface")), $(r.galerkin.solver) factorization") @@ -240,7 +245,7 @@ function Base.show(io::IO, ::MIME"text/plain", m::MatchResult) print(io, "MatchResult ", InnerLayer.model_name(m.model)) _row(io, "Surfaces", "$(size(m.deltar, 1)) matched, $(size(m.cout, 2)) edge drives") _row(io, "Residual", _fmt(m.residual)) - _row(io, "Forced γ [rad/s]", isempty(m.rpec_eig) ? "none" : _list(_fmt.(m.rpec_eig); max=3)) + _row(io, "Forced γ [rad/s]", isempty(m.forced_eigenvalue) ? "none" : _list(_fmt.(m.forced_eigenvalue); max=3)) outer = isempty(m.xi) ? "not computed" : "$(_shape(m.xi)) (one column per edge drive)" _row(io, "Stored", "matched outer ξ $outer, inner profiles $(isempty(m.inner_psi) ? "not computed" : "on $(length(m.inner_psi)) surfaces")") return nothing @@ -253,7 +258,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 @@ -273,10 +277,13 @@ 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", "matched solution, unit edge displacement") + r.unit_edge_basis && _row(io, "Basis", "unit edge displacement") _plots_row(io, r) return nothing end diff --git a/src/ForceFreeStates/CoreTypes.jl b/src/ForceFreeStates/CoreTypes.jl index 6f772bd4c..8c5a0b366 100644 --- a/src/ForceFreeStates/CoreTypes.jl +++ b/src/ForceFreeStates/CoreTypes.jl @@ -132,7 +132,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 9391ce454..e0f20cdaf 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/Free.jl b/src/ForceFreeStates/Free.jl index a77192029..f64bd45ab 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 55d093194..5c453a1c8 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 27401d16b..508b21873 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[], "none") + return GalerkinResult(0, Float64[], Float64[], Int[], Int[], Float64[], ComplexF64[], "none", Matrix{ComplexF64}(undef, 0, 0)) end """ @@ -57,9 +102,9 @@ Compute the outer-region Δ′ matching matrix by the singular Galerkin method. as an [`OuterSolutionBasis`](@ref); if there are no resonant surfaces in the domain it returns an empty result and two `nothing`s. -`wv` is the vacuum energy matrix from `free_run`, which supplies the free-boundary edge term -`wv_edge = wv · psio²`; pass `nothing` for a fixed-boundary edge. `cut_solution` also keeps the -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) @@ -94,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 --- @@ -101,10 +147,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, @@ -119,15 +165,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 @@ -145,43 +183,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" basis = 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, edge_response[:, 1:(2msing)]) + 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, ws.solver), dp, basis + return GalerkinResult(msing, sing_psi, sing_q, sing_m, sing_n, di, alpha, ws.solver, edge_response), dp, basis end """ @@ -206,30 +238,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; basis_output=false) @@ -335,7 +343,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 6cf5b9183..b0e142fdb 100644 --- a/src/ForceFreeStates/Galerkin/GalerkinStructs.jl +++ b/src/ForceFreeStates/Galerkin/GalerkinStructs.jl @@ -124,6 +124,8 @@ Solver internals and FEM diagnostics of the outer-region Galerkin solve. The Δ core→edge, in the order the Δ′ matrices are indexed. - `di::Vector{Float64}`, `alpha::Vector{ComplexF64}` — Mercier index and exponent per surface. - `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 @@ -134,4 +136,5 @@ struct GalerkinResult di::Vector{Float64} alpha::Vector{ComplexF64} solver::String + edge_response::Matrix{ComplexF64} end diff --git a/src/ForceFreeStates/Integrators.jl b/src/ForceFreeStates/Integrators.jl index ad112307d..2b540463d 100644 --- a/src/ForceFreeStates/Integrators.jl +++ b/src/ForceFreeStates/Integrators.jl @@ -38,12 +38,15 @@ Chunked Riccati integration and the singular-surface boundary-value solve. - `save_interval::Int` - Store every Nth solver step of each chunk; chunk ends and the edge-dW scan band are always stored. - `nchunks::Int` - Target chunk count; zero derives the count from the singular surfaces. - `extended_precision_bvp::Bool` - Solve the Delta-prime BVP in Complex{Double64} instead of ComplexF64; far slower, and needed only beyond about 150 poloidal harmonics. + - `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-10 save_interval::Int = 1 nchunks::Int = 0 extended_precision_bvp::Bool = false + error_field_response::Bool = true end """ @@ -67,7 +70,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. @@ -84,7 +90,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 1295d6a0c..fb1eb7202 100644 --- a/src/ForceFreeStates/Matching/DeltaPrime.jl +++ b/src/ForceFreeStates/Matching/DeltaPrime.jl @@ -1,39 +1,71 @@ """ - 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, 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`) +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. + - `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`. """ 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} + edge_response::Matrix{ComplexF64} + freeboundary::Union{Nothing,PEST3Blocks} + fixedboundary::Union{Nothing,PEST3Blocks} end +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)) + """ OuterSolutionBasis diff --git a/src/ForceFreeStates/Matching/MatchProblem.jl b/src/ForceFreeStates/Matching/MatchProblem.jl index fa119d2d5..b9c51d9be 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())` (or another toroidal layer model, e.g. `CCCModel()`) 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`. +`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 @@ -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,15 +90,15 @@ 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 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`, `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. """ function CommonSolve.solve(prob::MatchProblem, model::InnerLayer.InnerLayerModel) closure_capable(model) || error("$(nameof(typeof(model))) cannot solve a MatchProblem (use GGJModel() or CCCModel(); 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. @@ -111,87 +107,77 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel 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 basis = ffs.basis - 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.ToroidalLayerParameters[] - 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 - InnerLayer.check_layer_inputs(model, msing) - inner_params = [InnerLayer.layer_parameters(model, sings[i], equil; eta=prob.eta[i], rho=prob.rho[i], gamma=prob.gamma, ising=i) for i in 1:msing] - profiles = true - for i in 1:msing - params = inner_params[i] - γ = 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 + InnerLayer.check_layer_inputs(model, msing) + inner_params = [InnerLayer.layer_parameters(model, sings[i], equil; eta=prob.eta[i], rho=prob.rho[i], gamma=prob.gamma, ising=i) for i in 1:msing] + profiles = true + for i in 1:msing + params = inner_params[i] + γ = 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] + # 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 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) + small_coefficients = Matrix{ComplexF64}(dp.ef .+ transpose(dp.raw_fixedboundary) * cout) - # Matched outer ξ per coil: coil column + Σ cout·plasma columns. + # Matched outer ξ per EF column: EF column + Σ cout·plasma columns. if basis === nothing xi = Array{ComplexF64,3}(undef, 0, 0, 0) xi_deriv = Array{ComplexF64,3}(undef, 0, 0, 0) @@ -203,9 +189,9 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel sols_deriv = basis.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] @@ -220,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) @@ -245,16 +231,16 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel 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) @@ -267,18 +253,23 @@ function _compute_match(prob::MatchProblem, model::InnerLayer.ToroidalLayerModel end end - return MatchResult(cout, cin, deltar, rpec_eig, 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 -# 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) - # Without a matched ξ, the ideal solution stands only for the ideal reference. - solution = isempty(match.xi) ? (ideal ? ffs.solution : nothing) : _matched_profiles(ffs.basis, match, ffs.mats) - ideal && return _with(ffs; match=match, solution=solution) - # The ideal δW does not describe the matched plasma; PE gates on its absence. - return _with(ffs; closure=:matched, bpen=match.bpen, match=match, solution=solution, - wp=nothing, free_boundary=nothing) +# Copy of ffs with the match applied: 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. +function _matched_result(ffs::ForceFreeStatesResult, match::MatchResult) + solution = isempty(match.xi) ? nothing : _unit_edge_profiles(ffs.basis, match.xi, match.xi_deriv, ffs.mats) + # 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, 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 a53a84e3b..4d76e0587 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. + - `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)`). - `inner_params`: per-surface layer parameters used (`GGJParameters`, `CCCParameters`). @@ -27,10 +27,10 @@ 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} + penetrated_area_weighted_field::Matrix{ComplexF64} + small_coefficients::Matrix{ComplexF64} xi::Array{ComplexF64,3} xi_deriv::Array{ComplexF64,3} inner_psi::Vector{Vector{Float64}} @@ -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 @@ -80,9 +80,9 @@ 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/rpec_eig"] = m.rpec_eig + 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) out_h5["$g/Inner/psi_$i"] = m.inner_psi[i] @@ -104,24 +104,24 @@ 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")), - "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...), + "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") ] 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 a42269525..2770f428e 100644 --- a/src/ForceFreeStates/Output.jl +++ b/src/ForceFreeStates/Output.jl @@ -25,9 +25,10 @@ function save_to_hdf5( diag = result.diagnostics msing = length(result.surfaces) # Closed ξ profiles share dataset names and (mode, solution, psi) axis order across the Solutions groups: - # ForwardIntegration for an ODE integrator's columns, Match for a MatchProblem solution (on its basis's grid). + # ForwardIntegration for an ODE integrator's columns, GalerkinIntegration for the ideal Galerkin solution and Match + # for a MatchProblem solution (the last two on the grid of the outer solutions). xi_solution = (result.solution !== nothing && result.solution.basis === :el_axis) ? result.solution : nothing - matched_solution = (result.solution !== nothing && result.solution.basis === :unit_edge) ? result.solution : nothing + unit_edge_solution = (result.solution !== nothing && result.solution.basis === :unit_edge) ? result.solution : nothing # File-level metadata contract (schema_version, Conventions, title, date). @@ -41,13 +42,13 @@ function save_to_hdf5( write_galerkin!(out_h5, gal_data, result.basis; basis_output=result.control.algorithm.basis_output) end - if matched_solution !== nothing - group = "ForceFreeStates/Solutions/Match" - out_h5["$group/psi"] = matched_solution.psi_store - out_h5["$group/q"] = matched_solution.q_store - out_h5["$group/xi_psi"] = matched_solution.u_store[:, :, 1, :] - out_h5["$group/dxi_psidpsi"] = matched_solution.du_store - out_h5["$group/xi_s"] = matched_solution.xi_s_store + if unit_edge_solution !== nothing + group = result.closure === :matched ? "ForceFreeStates/Solutions/Match" : "ForceFreeStates/Solutions/GalerkinIntegration" + out_h5["$group/psi"] = unit_edge_solution.psi_store + out_h5["$group/q"] = unit_edge_solution.q_store + out_h5["$group/xi_psi"] = unit_edge_solution.u_store[:, :, 1, :] + out_h5["$group/dxi_psidpsi"] = unit_edge_solution.du_store + out_h5["$group/xi_s"] = unit_edge_solution.xi_s_store end save_equilibrium_ingest!(out_h5, equil) @@ -80,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 @@ -179,22 +181,19 @@ 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)) + 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 + 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) @@ -212,7 +211,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 00d80e381..60bc2a787 100644 --- a/src/ForceFreeStates/Result.jl +++ b/src/ForceFreeStates/Result.jl @@ -8,7 +8,8 @@ formalism produced the solution. ## Fields - `basis::Symbol` - The basis the profiles are in: `:el_axis` (an ODE integrator's solution columns) or - `:unit_edge` (a `MatchProblem` solution; each column has unit displacement of one edge mode). + `:unit_edge` (the ideal Galerkin solution or a `MatchProblem` solution; each column has unit displacement of one + edge mode). - `step::Int` - Number of stored radial nodes. - `psi_store::Vector{Float64}` - ψ at each node. - `q_store::Vector{Float64}` - Safety factor at each node. @@ -39,9 +40,11 @@ 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 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. ## Fields @@ -57,18 +60,21 @@ Every final result records how its basis crosses the rational surfaces, so bpen - `kinetic::NamedTuple` - Kinetic singular-surface scan (`kmsing`, `kinsing`, `scan_psi`, `scan_cond`, `scan_threshold`); empty unless the finder ran. - `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 no ideal δW: `wp` and `free_boundary` are `nothing`. - - `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. + `:matched` (an inner-layer solution was matched in). A `:matched` result carries the matched edge response as `wp`. + - `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 a match). + formalism produced none (Galerkin without `error_field_response`). - `basis::Union{Nothing,OuterSolutionBasis}` - The outer-region solutions a `MatchProblem` combines, from a - Galerkin solve or a Riccati solve that computed Δ′ with a vacuum edge; `nothing` otherwise. + Galerkin solve or a Riccati solve that computed Δ_EF; `nothing` otherwise. - `diagnostics::Union{Nothing,OdeState}` - The integrator's raw ODE state (ψ trace, `crit`, edge scan, asymptotic coefficients). Written to HDF5; not a consumable solution. - - `wp::Union{Nothing,Matrix{ComplexF64}}` - Fixed-boundary plasma energy matrix `W_p = (U₂·U₁⁻¹)/ψ₀²` at - `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. @@ -106,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. @@ -145,16 +151,22 @@ function require_solution(result::ForceFreeStatesResult, calc::AbstractString) return false end -# Pack the matched solution `m`, on the grid of `basis`, into `SolutionProfiles`: on-surface `issing` points are -# dropped and Ξ_s = −A⁻¹(B·Ξ′ + C·Ξ) as in `sing_der!`. -function _matched_profiles(basis::OuterSolutionBasis, m::MatchResult, mats::MatrixSplines) - npert = size(m.xi, 1) +# 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 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 the closed columns `xi`, `xi_deriv` (npert, ngrid, ncol) on the grid of `basis`: on-surface +# `issing` points are dropped and Ξ_s = −A⁻¹(B·Ξ′ + C·Ξ) as in `sing_der!`. +function _unit_edge_profiles(basis::OuterSolutionBasis, xi::AbstractArray{ComplexF64,3}, xi_deriv::AbstractArray{ComplexF64,3}, mats::MatrixSplines) + npert = size(xi, 1) keep = .!basis.issing psi_f = basis.psi[keep] q_f = basis.q[keep] - xi_f = m.xi[:, keep, :] # (npert, ngrid_f, mcoil) - dxi_f = m.xi_deriv[:, keep, :] + 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. @@ -179,8 +191,9 @@ end -> ForceFreeStatesResult Assemble the published result once the solve is finished, with the ideal or regular closure (a -`MatchProblem` solve transforms it afterwards). Materializes the forward path's derivative stores and forms `W_p` -when the free-boundary stage did not run; everything else is copied or aliased. +`MatchProblem` solve transforms it afterwards). Materializes the ODE integrators' 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` the Galerkin internals (`nothing` otherwise), and `delta_prime` and `basis` the Δ′ payload and outer solutions of a Riccati or Galerkin solve (`nothing` otherwise). @@ -198,12 +211,17 @@ function build_result( delta_prime::Union{Nothing,DeltaPrimeData}, basis::Union{Nothing,OuterSolutionBasis} ) + # The Galerkin EF columns (ξ = eⱼ at the edge, no big-solution drive) are its ideal closure. + gal_ef = gal_data === nothing || basis === nothing ? (1:0) : gal_ef_columns(gal_data) + # The ODE integrators' stores need materializing; doing it here keeps # `SolutionProfiles.du_store`/`xi_s_store` populated by construction. solution = if odet !== nothing materialize_derivative_stores!(odet, equil, mats, intr) SolutionProfiles(:el_axis, odet.step, odet.psi_store, odet.q_store, odet.u_store, odet.du_store, odet.xi_s_store) + elseif !isempty(gal_ef) + _unit_edge_profiles(basis, @view(basis.xi[:, :, gal_ef]), @view(basis.xi_deriv[:, :, gal_ef]), mats) else nothing end @@ -212,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. @@ -220,6 +238,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 @@ -229,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/DeltaPrimeBVP.jl b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl index 22657b0f1..c72dfb1b6 100644 --- a/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl +++ b/src/ForceFreeStates/Riccati/DeltaPrimeBVP.jl @@ -26,26 +26,29 @@ function warn_unresolved_surfaces(bases::AbstractDict, surfaces::Vector{SingType end """ - compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> (delta_prime, coefficients) + compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, + extended_precision=false, error_field_response=true) -> (delta_prime, coefficients) -Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix -[Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]. +Solve the STRIDE boundary-value problem for the inter-surface Δ' matrices +[Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37]: with the vacuum at the edge, and with ξ(edge) = 0. ### Arguments - `intr`: Read for its mode space and singular surfaces. - `propagators`, `chunks`, `axis_state`: From `riccati_eulerlagrange_integration`. - - `wv`: Singfac-scaled vacuum response for the edge condition `wp + wv = 0`; `nothing` puts a conducting wall there. + - `wv`: Singfac-scaled vacuum response for the edge condition `wp + wv = 0`. With `nothing` only the ξ(edge) = 0 + problem is solved, and no Δ_EF. - `wp`: The run's plasma response, used only as a check: a warning is issued when the edge momentum of the Δ_EF solve differs from it by more than `DELTA_PRIME_RESPONSE_MISMATCH`. - `psio`: Poloidal flux normalization. - `extended_precision`: Solve in `Complex{Double64}`. + - `error_field_response`: Also solve for Δ_EF. ### Returns - - `delta_prime`: A [`DeltaPrimeData`](@ref) whose `coil` is Δ_EF (empty without `wv`). - - `coefficients`: The BVP's solution vectors, one column per solution: the 2·msing Δ' solves, side-major, then the - N of Δ_EF. Input of `outer_solution_basis`; `nothing` without `wv`. + - `delta_prime`: A [`DeltaPrimeData`](@ref). + - `coefficients`: The solution vectors of the ξ(edge) = 0 problem, one column per solution: the 2·msing Δ' solves, + side-major, then the N of Δ_EF. Input of `outer_solution_basis`; `nothing` without Δ_EF. Both are `nothing` when no surface is crossed or, with a warning, when a surface carries more than one resonant mode. """ @@ -57,7 +60,8 @@ function compute_delta_prime_matrix( wv::Union{Nothing,Matrix{ComplexF64}}=nothing, wp::Union{Nothing,Matrix{ComplexF64}}=nothing, psio::Float64=0.0, - extended_precision::Bool=false + extended_precision::Bool=false, + error_field_response::Bool=true ) intr.msing == 0 && return nothing, nothing _has_unsupported_multi_resonance(intr) && return nothing, nothing @@ -71,26 +75,29 @@ function compute_delta_prime_matrix( uAxis = Matrix(qr(axis_state).Q)[:, 1:N] M, col_edge = _assemble_bvp(uShootR, uShootL, uAxis, ipert_all, msing, N, wv, psio) - # Δ_EF: needs a vacuum edge in the assembled matrix. - delta_ef = Matrix{ComplexF64}(undef, 0, 0) - delta_ef_solutions = nothing - if wv !== nothing - delta_ef, delta_ef_solutions = _solve_bvp_delta_ef(M, col_edge, msing, N, ipert_all) - if wp !== nothing - # Unit edge displacement, so the edge U₂ is the plasma response times ψ₀². - wp_bvp = uShootR[msing][(N+1):(2N), :] * delta_ef_solutions[_col_right(msing, N), :] ./ psio^2 - mismatch = norm(wp_bvp - wp) / norm(wp) - if mismatch > DELTA_PRIME_RESPONSE_MISMATCH - @warn "Riccati: the plasma response from the Δ' system differs from the axis-to-edge one by $(@sprintf("%.1e", mismatch)) " * - "(relative), so the chunk propagators have lost accuracy. Raise [Riccati] nchunks (now $(length(chunks)) chunks); " * - "beyond about 150 poloidal harmonics also set extended_precision_bvp." - end + none = Matrix{ComplexF64}(undef, 0, 0) + if wv === nothing + # Assembled with the conducting-wall edge, so this is the ξ(edge) = 0 problem. + raw_fixedboundary, edge_response, _ = _solve_bvp_raw(M, msing, N, ipert_all, col_edge, extended_precision) + return DeltaPrimeData(none, raw_fixedboundary, none, edge_response), nothing + end + raw_freeboundary, _, _ = _solve_bvp_raw(M, msing, N, ipert_all, col_edge, extended_precision) + Mc = _fixed_edge_bvp(M, msing, N, col_edge) + raw_fixedboundary, edge_response, delta_prime_solutions = _solve_bvp_raw(Mc, msing, N, ipert_all, col_edge, extended_precision) + error_field_response || return DeltaPrimeData(raw_freeboundary, raw_fixedboundary, none, edge_response), nothing + + delta_ef, delta_ef_solutions = _solve_bvp_delta_ef(Mc, msing, N, ipert_all) + if wp !== nothing + # Unit edge displacement, so the edge unknowns U₂(edge) are the plasma response times ψ₀². + wp_bvp = delta_ef_solutions[col_edge, :] ./ psio^2 + mismatch = norm(wp_bvp - wp) / norm(wp) + if mismatch > DELTA_PRIME_RESPONSE_MISMATCH + @warn "Riccati: the plasma response from the Δ' system differs from the axis-to-edge one by $(@sprintf("%.1e", mismatch)) " * + "(relative), so the chunk propagators have lost accuracy. Raise [Riccati] nchunks (now $(length(chunks)) chunks); " * + "beyond about 150 poloidal harmonics also set extended_precision_bvp." end end - # The raw side-major D' (Fortran gal_write_delta layout) feeds `pest3_decompose`; Riccati leaves the blocks unfilled. - delta_prime, delta_prime_raw, delta_prime_solutions = _solve_bvp_and_combine_pest3(M, msing, N, ipert_all, extended_precision) - coefficients = wv === nothing ? nothing : [delta_prime_solutions delta_ef_solutions] - return DeltaPrimeData(delta_prime, delta_prime_raw, delta_ef, nothing, nothing, nothing), coefficients + return DeltaPrimeData(raw_freeboundary, raw_fixedboundary, delta_ef, edge_response), [delta_prime_solutions delta_ef_solutions] end # Column index helpers for the BVP matrix. j is the 1-based singular-surface index, @@ -230,16 +237,25 @@ function _assemble_bvp(uShootR::Vector{Matrix{ComplexF64}}, return M, col_edge end -# Δ_EF (2·msing × N): the small-solution coefficient at each surface side per unit displacement of each edge mode, -# from the BVP with its edge fixed. Also returns the N solution vectors. -function _solve_bvp_delta_ef(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int, ipert_all::Vector{Int}) +# The BVP matrix `M` with its Eq. (38) vacuum-edge rows [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502] 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) # Eq. (38) bottom rows, carrying the W_V block + edge_rows = (nMat-2msing-2N+1):(nMat-2msing) Mc = copy(M) - Mc[bot, :] .= 0 - Mc[bot, col_edge] .= I(N) # Dirichlet edge: the edge coefficients equal the source + Mc[edge_rows, col_edge] .= 0 + Mc[edge_rows[(N+1):end], 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. Also returns the N solution vectors. +function _solve_bvp_delta_ef(Mc::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}) + nMat = size(Mc, 1) + u1_rows = (nMat-2msing-2N+1):(nMat-2msing-N) B = zeros(ComplexF64, nMat, N) - B[bot, :] .= I(N) # unit displacement, 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 @@ -251,9 +267,9 @@ function _solve_bvp_delta_ef(M::Matrix{ComplexF64}, col_edge, msing::Int, N::Int return delta_ef, X end -# Solve the BVP and apply the PEST3 four-term combination, in Complex{Double64} when `extended_precision`. Returns -# Δ', the raw side-major D' and the 2·msing solution vectors. -function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}, extended_precision::Bool) +# Solve the BVP for the raw side-major D' (2·msing × 2·msing), in Complex{Double64} when `extended_precision`. Also +# returns the edge unknowns of each solve (N × 2·msing) and the 2·msing solution vectors. +function _solve_bvp_raw(M::Matrix{ComplexF64}, msing::Int, N::Int, ipert_all::Vector{Int}, col_edge, extended_precision::Bool) nMat = size(M, 1) s2 = 2 * msing Tc = extended_precision ? Complex{Double64} : ComplexF64 @@ -280,67 +296,5 @@ function _solve_bvp_and_combine_pest3(M::Matrix{ComplexF64}, msing::Int, N::Int, dp_raw[dRow, 2ksing] = x[_col_right(ksing, N)[ipert_k+N]] end end - - # PEST3 four-term combination [Chance PPPL-2527]: Δ'[i,j] = (NW − NE − SW + SE) on each 2×2 block of dp_raw. - deltap = zeros(Tc, msing, msing) - for i in 1:msing, j in 1:msing - deltap[i, j] = dp_raw[2i, 2j] - dp_raw[2i, 2j-1] - dp_raw[2i-1, 2j] + dp_raw[2i-1, 2j-1] - end - return ComplexF64.(deltap), ComplexF64.(dp_raw), solutions -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 `DeltaPrimeData.matrix`. - -# Arguments - - - `dp_raw` — 2m×2m complex matrix (typically `DeltaPrimeData.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) + return ComplexF64.(dp_raw), solutions[col_edge, :], solutions end diff --git a/src/ForceFreeStates/Riccati/Driver.jl b/src/ForceFreeStates/Riccati/Driver.jl index 57b892408..a4b653839 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/Run.jl b/src/ForceFreeStates/Run.jl index 00b4df2ce..ce4ef0042 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 @@ -71,6 +71,9 @@ function run_force_free_states( gal_data, delta_prime, basis = galerkin_solve(ctrl, equil, mats, intr; wv=wv, cut_solution=cut_solution) gal_dt = time() - gal_start @info "Galerkin solve completed in $(@sprintf("%.3f", gal_dt)) s" + if ctrl.vac_flag && basis !== 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" @@ -85,7 +88,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 @@ -104,7 +107,8 @@ function run_force_free_states( end warn_unresolved_surfaces(riccati.bases, intr.sing[1:intr.msing], ctrl.algorithm.eulerlagrange_tolerance) delta_prime, coefficients = compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; - wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp) + wv=free_energies.wv, wp=free_energies.wp, psio=equil.psio, extended_precision=ctrl.algorithm.extended_precision_bvp, + error_field_response=ctrl.algorithm.error_field_response) if coefficients !== nothing basis = outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, ModeIndices(intr), crossing_fill_fractions(ctrl)) diff --git a/src/ForceFreeStates/Surfaces/Types.jl b/src/ForceFreeStates/Surfaces/Types.jl index 333a93ca6..3777b09b9 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 0c4364d2c..3274b1e68 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibrium.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibrium.jl @@ -50,10 +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. 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. +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 @@ -62,24 +62,20 @@ 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 + 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 - # Ξ′ / Ξ_s stores. A matched solution's stored Ξ′ is used as is downstream. + # Ξ′ / Ξ_s stores. A unit-edge solution's stored Ξ′ is used as is downstream. solution = ffs.solution 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_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 3de1ac75c..32756ba71 100644 --- a/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl +++ b/src/PerturbedEquilibrium/PerturbedEquilibriumStructs.jl @@ -48,7 +48,7 @@ spectra. - `ffs::ForceFreeStatesResult` - The result the operators were built from. - `m_modes`, `n_modes` - Poloidal and toroidal mode number of each entry of a spectrum [numpert_total]. - - `unit_edge_basis::Bool` - The solution is a `MatchProblem` one (`basis = :unit_edge`); the singular coupling + - `unit_edge_basis::Bool` - The solution is a Galerkin or `MatchProblem` one (`basis = :unit_edge`); the singular coupling then takes Ξ′ from its `du_store`. - `compute_singular_coupling::Bool`, `compute_torque_response::Bool` - The [`plasma_response`](@ref) options it was built with. - `flux_matrix::Matrix{ComplexF64}` - Control-surface flux of the free-boundary eigenmodes [mode × eigenmode]. @@ -76,9 +76,15 @@ 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) - - `coupling_flux::NamedTuple` - The same five matrices acting on the physical flux Φ_x (keys without the + - `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. + 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: @@ -124,7 +130,11 @@ 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) + 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) @@ -175,13 +185,16 @@ 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 + - `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 @@ -229,12 +242,18 @@ 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[] + 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 4ba63adbe..05f73ae92 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 d7e6f53cb..d2b33d99a 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,15 +216,20 @@ 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. +Δ_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. 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 - 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. @@ -276,23 +281,36 @@ 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_prime = 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 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 + 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) + 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] @@ -335,58 +353,64 @@ 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) + # 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 - 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 + # Δ_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]. 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 - - # 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 + 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 - - # Δ' is the ∂b^ψ/∂ψ jump over 2π·χ₁ [Glasser 2016]; 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_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 + if have_ef + # 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 + resp.C_island_width_sq_asymptotic[row, :] = rows.island_width_sq end resp.rational_psi[row] = sing_surf.psifac @@ -396,9 +420,9 @@ 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_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))" + 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 finally @@ -408,13 +432,23 @@ 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, + 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_prime = resp.C_delta_prime * flux_conform - have_inner_bpen && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * 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_penetrated && (resp.C_penetrated_area_weighted_field = resp.C_penetrated_area_weighted_field * flux_conform) return resp end @@ -424,7 +458,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 @@ -438,20 +472,29 @@ 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_prime = C.delta_prime * 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 + 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) - 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 1185379dd..524116712 100644 --- a/src/PerturbedEquilibrium/Utils.jl +++ b/src/PerturbedEquilibrium/Utils.jl @@ -125,19 +125,35 @@ 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) !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) @@ -281,8 +297,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 +312,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",), @@ -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/src/Precompile.jl b/src/Precompile.jl index 0e41e3fb4..7f6bbe9ea 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 diff --git a/src/Tearing/Dispersion/CoupledFullMatch.jl b/src/Tearing/Dispersion/CoupledFullMatch.jl index 578f1bcd9..320ecd9d7 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' (`DeltaPrimeData.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,8 +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 `DeltaPrimeData.raw` -field of a Riccati solve). Surface k's inner layer is evaluated at `Q·ratio_k` Doppler-shifted by its +2m × 2m matrix in side-major ordering (a raw D' of `DeltaPrimeData`). Surface k's inner layer is evaluated at `Q·ratio_k` Doppler-shifted by its E×B offset `q_shift_k`, exactly as in the reduced `multi_surface_coupling`: added to Q for a SLAYER surface, and as `i·q_shift_k` to the growth rate s for a GGJ surface (see `SurfaceCoupling`). diff --git a/src/Tearing/GGJTearing.jl b/src/Tearing/GGJTearing.jl index e13b39d74..5ede142f6 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("Toroidal-layer 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("Toroidal-layer tearing needs distinct surfaces ordered core to edge; got ψ = $psi")) dp = ffs.delta_prime - dp === nothing && throw(ArgumentError("Toroidal-layer 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("Toroidal-layer 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("Toroidal-layer tearing: the raw Δ′ matrix has non-finite entries")) - return dp.raw + dp === nothing && throw(ArgumentError("Toroidal-layer 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( + "Toroidal-layer 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("Toroidal-layer 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. @@ -71,7 +78,7 @@ function CommonSolve.solve(prob::TearingProblem, model::ToroidalLayerModel; conf 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) InnerLayer.check_layer_inputs(model, count) eta, rho = _ggj_layer_inputs(prob) @@ -120,7 +127,8 @@ function CommonSolve.solve(prob::TearingProblem, model::ToroidalLayerModel; conf 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 fab575ccb..f470eb45c 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 ToroidalLayerModel && 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 72056d8dd..7699dcb31 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, model; config)` for a toroidal layer model (`GGJModel()`, `CCCModel()`) or `SLAYERModel()`. -A toroidal layer model needs the raw Δ′ matrix (Riccati with `vac_flag=true`, or Galerkin with `rpec_flag=true`). +All 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 a66f2c86f..1ab1d13ae 100644 --- a/src/Utilities/HDF5Schema.jl +++ b/src/Utilities/HDF5Schema.jl @@ -193,12 +193,24 @@ const MAIN_H5_ANNOTATIONS = [ attach=(3 => "ForceFreeStates/Solutions/ForwardIntegration/psi",)), "ForceFreeStates/Solutions/ForwardIntegration/crit" => (; long_name="DCON zero-crossing criterion at saved snapshots", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/ForwardIntegration/psi",)), + # --- ForceFreeStates/Solutions/GalerkinIntegration/ (the ideal solution of a Galerkin solve, on its own grid) --- + "ForceFreeStates/Solutions/GalerkinIntegration/psi" => (; long_name="normalized poloidal flux ψ_N grid of the closed Galerkin solution", scale="psi_gal"), + "ForceFreeStates/Solutions/GalerkinIntegration/q" => + (; long_name="safety factor q on the Galerkin solution grid", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), + "ForceFreeStates/Solutions/GalerkinIntegration/xi_psi" => + (; long_name="closed axis-to-edge ξ^ψ profiles (ideal closure; identity-at-edge basis)", dims=("mode", "solution", "psi"), + attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), + "ForceFreeStates/Solutions/GalerkinIntegration/dxi_psidpsi" => + (; long_name="ψ_N derivative of the closed ξ^ψ profiles", dims=("mode", "solution", "psi"), attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), + "ForceFreeStates/Solutions/GalerkinIntegration/xi_s" => + (; long_name="surface displacement ξ_s from the outer ideal-MHD relation", dims=("mode", "solution", "psi"), + attach=(3 => "ForceFreeStates/Solutions/GalerkinIntegration/psi",)), # --- ForceFreeStates/Solutions/Match/ (the solution a MatchProblem closes, on the grid of its outer basis) --- "ForceFreeStates/Solutions/Match/psi" => (; long_name="normalized poloidal flux ψ_N grid of the matched solution", scale="psi_match"), "ForceFreeStates/Solutions/Match/q" => (; long_name="safety factor q on the matched-solution grid", dims=("psi",), attach=(1 => "ForceFreeStates/Solutions/Match/psi",)), "ForceFreeStates/Solutions/Match/xi_psi" => - (; long_name="closed axis-to-edge ξ^ψ profiles (ideal or inner-layer closure; identity-at-edge basis)", dims=("mode", "solution", "psi"), + (; long_name="closed axis-to-edge ξ^ψ profiles (inner-layer closure; identity-at-edge basis)", dims=("mode", "solution", "psi"), attach=(3 => "ForceFreeStates/Solutions/Match/psi",)), "ForceFreeStates/Solutions/Match/dxi_psidpsi" => (; long_name="ψ_N derivative of the closed ξ^ψ profiles", dims=("mode", "solution", "psi"), attach=(3 => "ForceFreeStates/Solutions/Match/psi",)), @@ -227,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")), @@ -256,14 +271,25 @@ 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/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")), + "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_analysis_plots.jl b/test/runtests_analysis_plots.jl index b0640a3b8..039fc68d4 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"; @@ -152,7 +183,7 @@ using TOML @test A.ForceFreeStates.plot_ffs_summary(ret.ffs) isa Figure # The Δ′ family draws any part of its complex entries and refuses others. @test A.ForceFreeStates.plot_delta_prime(ret.ffs; part=:abs) isa Figure - @test A.ForceFreeStates.plot_delta_coil(h5; part=:imag) isa Figure + @test A.ForceFreeStates.plot_delta_ef(h5; part=:imag) isa Figure @test_throws ArgumentError A.ForceFreeStates.plot_delta_prime(ret.ffs; part=:phase) end end diff --git a/test/runtests_dominant_coupling.jl b/test/runtests_dominant_coupling.jl index 9a4b0fad1..8977dd94c 100644 --- a/test/runtests_dominant_coupling.jl +++ b/test/runtests_dominant_coupling.jl @@ -145,6 +145,59 @@ 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 depends on the width and departs from the asymptotic one. + mktempdir() do dir + 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 end diff --git a/test/runtests_galerkin_cholesky.jl b/test/runtests_galerkin_cholesky.jl index 11a38764f..e1fff1e8f 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 60bcf1d9d..54204652e 100644 --- a/test/runtests_parallel_integration.jl +++ b/test/runtests_parallel_integration.jl @@ -30,11 +30,10 @@ 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 - extended = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], true)[1:2] - ordinary = FFS._solve_bvp_and_combine_pest3(M, 1, 1, [1], false)[1:2] + extended = FFS._solve_bvp_raw(M, 1, 1, [1], 6:6, true)[1] + ordinary = FFS._solve_bvp_raw(M, 1, 1, [1], 6:6, false)[1] @test extended == reference @test ordinary != reference @test all(isapprox.(ordinary, reference; rtol=1e-8)) @@ -205,7 +204,7 @@ end function run_solovev(integrator) ctrl, intr, equil, metric, mats = _prepared_solovev(integrator) odet = first(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 9f1ae2d92..afc63fd7e 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,18 +105,24 @@ 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 - @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 size(dp.edge_response) == (ffs.numpert_total, 2 * length(ffs.surfaces)) && !iszero(dp.edge_response) @test ffs.free_boundary !== nothing foreach(_check_display, (ffs, ffs.delta_prime)) @@ -134,35 +140,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_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 + @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 @@ -179,9 +183,9 @@ include("display_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 @@ -191,7 +195,7 @@ include("display_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 @@ -201,44 +205,41 @@ include("display_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) + @test dp.edge_response == ffs.galerkin.edge_response[:, 1:(2msing)] _check_main_display(ret) foreach(_check_display, (ffs, ffs.galerkin, ffs.solution)) - # 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 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) - # The ideal δW does not describe the matched plasma. - @test ffs.wp === nothing && ffs.free_boundary === nothing + @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 @@ -249,22 +250,27 @@ include("display_check.jl") @test ffs.galerkin.solver in ("cholesky", "LU") @test read(f["$gal/solver"]) == ffs.galerkin.solver @test haskey(attrs(f["$gal/solver"]), "long_name") - @test read(f["$matched/psi"]) == sol.psi_store - @test read(f["$matched/xi_psi"]) == sol.u_store[:, :, 1, :] - @test read(f["$matched/dxi_psidpsi"]) == sol.du_store - @test read(f["$matched/xi_s"]) == sol.xi_s_store - @test isempty(_collect_metadata_violations(f["ForceFreeStates/Solutions/Match"])) - @test !haskey(f, "$gal/psi") + # The ideal Galerkin solution sits in the Galerkin group, a matched one in Match. + group = ideal ? gal : matched + @test read(f["$group/psi"]) == sol.psi_store + @test read(f["$group/xi_psi"]) == sol.u_store[:, :, 1, :] + @test read(f["$group/dxi_psidpsi"]) == sol.du_store + @test read(f["$group/xi_s"]) == sol.xi_s_store + @test isempty(_collect_metadata_violations(f[group])) + @test haskey(f, "$gal/psi") == ideal && haskey(f, "$matched/psi") == !ideal + @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["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 @test !haskey(f, "$gal/Basis") @test !haskey(f, "$gal/Solution") end diff --git a/test/runtests_riccati.jl b/test/runtests_riccati.jl index cfe9e8685..65e0ce632 100644 --- a/test/runtests_riccati.jl +++ b/test/runtests_riccati.jl @@ -2,6 +2,9 @@ using LinearAlgebra, Logging, TOML const FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates +# Plasma energy matrix of an integration's edge state. +edge_wp(odet, equil) = (odet.u[:, :, 2] / odet.u[:, :, 1]) ./ equil.psio^2 + # A fixture (Solovev by default) prepared as solve prepares it, up to the integration. Each integration mutates its # intr (sing[s].delta_prime etc.), so every run takes a freshly prepared one. function prepared_solovev(; fixture="regression_solovev_ideal_example", integrator="Riccati", singfac_min=nothing, nchunks=0, over=Dict{String,Any}()) @@ -26,7 +29,7 @@ end function solovev_energies(integrator, singfac_min; fixture="regression_solovev_ideal_example") ctrl, intr, equil, _, mats = prepared_solovev(; fixture, integrator, singfac_min) odet = first(FFS.eulerlagrange_integration(ctrl, equil, mats, intr)) - return FFS.free_run(odet, ctrl, equil, mats, intr).et + return FFS.free_run(edge_wp(odet, equil), ctrl, equil, mats, intr).et end @testset "Riccati Integration Tests" begin @@ -166,9 +169,9 @@ end function delta_prime(nchunks) ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example", nchunks) odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) - wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv + wv = FFS.free_run(edge_wp(odet, equil), ctrl, equil, mats, intr).wv result, _ = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) - return result.matrix, riccati.chunks + return result.freeboundary.Delta, riccati.chunks end dp_auto, chunks_auto = delta_prime(0) dp_few, chunks_few = delta_prime(1) @@ -190,7 +193,7 @@ end @testset "the Δ′ solutions on the stored grid" begin ctrl, intr, equil, _, mats = prepared_solovev(; fixture="regression_tj_ideal_example") odet, riccati = FFS.riccati_eulerlagrange_integration(ctrl, equil, mats, intr) - wv = FFS.free_run(odet, ctrl, equil, mats, intr).wv + wv = FFS.free_run(edge_wp(odet, equil), ctrl, equil, mats, intr).wv delta_prime, coefficients = FFS.compute_delta_prime_matrix(intr, riccati.propagators, riccati.chunks, riccati.columns.axis_state; wv, psio=equil.psio) basis = FFS.outer_solution_basis(coefficients, riccati.propagators, riccati.chunks, riccati.columns, riccati.bases, intr.sing, equil, mats, FFS.ModeIndices(intr), FFS.crossing_fill_fractions(ctrl)) @@ -225,13 +228,14 @@ end @test intr.psilim == odet.psi_store[end] == chunks[end].psi_end @test length(propagators) == length(chunks) && count(c -> c.needs_crossing, chunks) == intr.msing @test odet.u_store[:, :, :, end] ≈ odet.u - free = FFS.free_run(odet, ctrl, equil, mats, intr) + free = FFS.free_run(edge_wp(odet, equil), ctrl, equil, mats, intr) @test isfinite(free.et[1]) # The Δ′ system reproduces the plasma response of the axis-to-edge products, and says so when it does not. delta_prime, coefficients = @test_logs min_level = Logging.Warn FFS.compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=free.wv, wp=free.wp, psio=equil.psio) - @test size(delta_prime.matrix) == (intr.msing, intr.msing) && all(isfinite, delta_prime.matrix) - @test size(delta_prime.coil) == (2 * intr.msing, intr.numpert_total) + @test size(delta_prime.freeboundary.Delta) == size(delta_prime.fixedboundary.Delta) == (intr.msing, intr.msing) + @test all(isfinite, delta_prime.raw_freeboundary) && all(isfinite, delta_prime.raw_fixedboundary) + @test size(delta_prime.ef) == (2 * intr.msing, intr.numpert_total) basis = FFS.outer_solution_basis( coefficients, propagators, diff --git a/test/runtests_slayer_runner.jl b/test/runtests_slayer_runner.jl index e577e24da..ff30ce209 100644 --- a/test/runtests_slayer_runner.jl +++ b/test/runtests_slayer_runner.jl @@ -139,7 +139,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 @@ -158,7 +158,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 a9632065d..fb4212bf1 100644 --- a/test/runtests_solve_api.jl +++ b/test/runtests_solve_api.jl @@ -79,18 +79,18 @@ include("display_check.jl") @test api.solution !== nothing && api.solution.basis === :el_axis @test api.delta_prime !== nothing msing = length(api.surfaces) - @test size(api.delta_prime.matrix) == (msing, msing) - @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 @@ -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 @@ -196,13 +196,13 @@ include("display_check.jl") @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([ @@ -210,10 +210,13 @@ include("display_check.jl") 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 @@ -241,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. @@ -388,14 +391,14 @@ include("display_check.jl") @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) 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 @@ -403,7 +406,7 @@ include("display_check.jl") 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) @@ -429,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) @@ -442,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()) @@ -500,13 +503,13 @@ include("display_check.jl") @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 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 @@ -521,24 +524,41 @@ include("display_check.jl") 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.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 - @test matched.wp === nothing && matched.free_boundary === nothing + @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 @test matched.solution.u_store[:, :, 1, :] == permutedims(matched.match.xi, (1, 3, 2)) # A Riccati basis always carries its cut solution, so the composite inner profiles need no option. @test length(solve(MatchProblem(ric; eta=1e-7, rho=1e-7, rotation=1.0), GGJModel(; real_profiles=true)).match.inner_xi) == length(ric.surfaces) - # It carries no ideal δW, so no plasma response can be built from it. - @test_throws ErrorException plasma_response(matched) + # 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 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; ideal=true) + @test_throws ErrorException MatchProblem(matched; eta=1e-7, rho=1e-7, rotation=1.0) end end @@ -546,24 +566,65 @@ include("display_check.jl") 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 === :unit_edge + 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 === :unit_edge + @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 + @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 + @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) + # 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 @@ -650,20 +711,20 @@ include("display_check.jl") "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 @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) - 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 @@ -674,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 @@ -691,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 @@ -717,8 +778,8 @@ include("display_check.jl") # 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))) - @test_throws "[Match] needs Δ′" GPEC.parse_deck(TOML.parsefile(joinpath(deck_dir, "gpec.toml")), deck_dir) + 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 Δ_EF" GPEC.parse_deck(TOML.parsefile(joinpath(deck_dir, "gpec.toml")), deck_dir) end # A perturbed equilibrium with a wall stops at parse time. diff --git a/test/test_data/regression_solovev_ideal_example/gpec.toml b/test/test_data/regression_solovev_ideal_example/gpec.toml index 72493fecd..783341891 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 4caa2594f..22f20886b 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 53a79dc80..96c6b0bf1 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 6d915442f..64701222a 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 162eac801..f8fa35560 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 7dae5f9a8..3bc88d565 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