diff --git a/benchmarks/benchmark_against_fortran_run.jl b/benchmarks/benchmark_against_fortran_run.jl index 87464dc8b5..7e76b03d1c 100644 --- a/benchmarks/benchmark_against_fortran_run.jl +++ b/benchmarks/benchmark_against_fortran_run.jl @@ -426,7 +426,6 @@ function write_gpec_toml_coil( println(io, "save_interval = $(p.euler_stride)") println(io) println(io, "[ForcingTerms]") - println(io, "forcing_data_format = \"coil\"") println(io, "mtheta_coil = $(p.mtheta_coil)") println(io, "nzeta_coil = $(p.nzeta_coil)") for (name, currents) in zip(p.coil_names, p.coil_currents) diff --git a/benchmarks/benchmark_diiid_ideal_ntv_torque.jl b/benchmarks/benchmark_diiid_ideal_ntv_torque.jl index 3b2ae96fe4..c3724c3035 100644 --- a/benchmarks/benchmark_diiid_ideal_ntv_torque.jl +++ b/benchmarks/benchmark_diiid_ideal_ntv_torque.jl @@ -145,7 +145,6 @@ singfac_min = 1e-4 [Riccati] eulerlagrange_tolerance = 1e-7 save_interval = 3 -renorm_threshold = 1e4 """ ) end diff --git a/benchmarks/benchmark_riccati_der.jl b/benchmarks/benchmark_riccati_der.jl deleted file mode 100644 index 9a1d6411b5..0000000000 --- a/benchmarks/benchmark_riccati_der.jl +++ /dev/null @@ -1,117 +0,0 @@ -# Sanity check: riccati_der! correctly evaluates the explicit Riccati ODE. -# -# riccati_der! implements [Glasser 2018 Phys. Plasmas 25, 032507, Eq. 19]: -# dS/dψ = w†·F̄⁻¹·w - S·Ḡ·S, w = Q - K̄·S -# -# where Q = diag(1/(m - n·q)), F̄ = L·L† (Cholesky), K̄ and Ḡ are the MHD -# metric matrices evaluated at ψ. -# -# NOTE: The identity between this Riccati ODE and the EL chain rule -# dS/dψ = dU₁·U₂⁻¹ - S·dU₂·U₂⁻¹ -# holds ONLY for Hermitian S (physical states evolved from the axis, where -# S†=S is preserved by the EL symmetry). For arbitrary non-Hermitian (U₁, U₂), -# the two expressions differ — so this script compares riccati_der! against the -# explicit formula rather than against sing_der!. -# -# Usage (from the repository root): -# julia --project=. benchmarks/benchmark_riccati_der.jl - -using LinearAlgebra, Random, Printf, TOML -using GeneralizedPerturbedEquilibrium - -const FFS = GeneralizedPerturbedEquilibrium.ForceFreeStates - -function setup_solovev() - GPEC = GeneralizedPerturbedEquilibrium - ex = joinpath(@__DIR__, "..", "test", "test_data", "regression_solovev_ideal_example") - inputs = TOML.parsefile(joinpath(ex, "gpec.toml")) - equil = GPEC.Equilibrium.PlasmaEquilibrium(GPEC.equilibrium_config(inputs, ex), GPEC.analytic_config(inputs)) - prob = GPEC.ForceBalanceProblem(equil; GPEC.force_balance_keywords(inputs, ex)...) - ctrl, intr, equil, _, mats = GPEC._prepare_solve(prob, GPEC.force_balance_algorithm(inputs)) - return ctrl, equil, mats, intr -end - -# Evaluate the Riccati RHS explicitly from splines: dS = w†·F̄⁻¹·w - S·Ḡ·S -function riccati_rhs_manual(S, psi, equil, mats, intr) - N = intr.numpert_total - L = zeros(ComplexF64, N, N) - Kmat = zeros(ComplexF64, N, N) - Gmat = zeros(ComplexF64, N, N) - mats.ideal.F_spline_lower(vec(L), psi; hint=mats._hint) - mats.ideal.K_spline(vec(Kmat), psi; hint=mats._hint) - mats.ideal.G_spline(vec(Gmat), psi; hint=mats._hint) - - q = equil.profiles.q_spline(psi) - singfac = vec(1.0 ./ ((intr.mlow:intr.mhigh) .- q .* (intr.nlow:intr.nhigh)')) - - # w = Q - K̄·S (Q is diagonal; add only the diagonal entries) - w = -Kmat * S - for i in 1:N - w[i, i] += singfac[i] - end - - # v = F̄⁻¹·w via stored Cholesky factor L (L·L† = F̄) - v = copy(w) - ldiv!(LowerTriangular(L), v) - ldiv!(UpperTriangular(L'), v) - - return adjoint(w) * v - S * Gmat * S -end - -println("\n=== riccati_der! formula verification ===") -println("Verifies riccati_der! output matches manual evaluation of Glasser 2018 Eq. 19.") -println("Test state: Hermitian S (physical constraint). Expected error: ~machine epsilon.\n") - -ctrl, equil, mats, intr = setup_solovev() -N = intr.numpert_total - -odet = FFS.OdeState(N, ctrl.algorithm.numsteps_init, ctrl.algorithm.numunorms_init, intr.msing) -FFS.initialize_el_at_axis!(odet, ctrl, mats, equil.profiles, intr) -chunks = FFS.chunk_el_integration_bounds(odet, ctrl, intr) - -# 30% into each chunk: well inside the interval, away from singularities at psi_end -test_psis = [c.psi_start + 0.3 * (c.psi_end - c.psi_start) for c in chunks] - -println(" N=$N modes, $(length(test_psis)) test ψ points (30% into each chunk)\n") -@printf(" %8s %14s %14s %12s\n", "ψ", "‖dS_manual‖", "‖dS_ric‖", "rel error") -println(" " * "-"^54) - -rng = Random.MersenneTwister(42) -threshold = 1e-10 - -max_err = let max_err = 0.0 - for psi in test_psis - # Hermitian S: physical Riccati matrix is Hermitian (preserved by EL symmetry) - A = randn(rng, ComplexF64, N, N) - S = (A + A') / 2 # Hermitian by construction - - # Manual RHS - dS_manual = riccati_rhs_manual(S, psi, equil, mats, intr) - - # riccati_der! RHS - u_ric = zeros(ComplexF64, N, N, 2) - du_ric = zeros(ComplexF64, N, N, 2) - u_ric[:, :, 1] .= S - u_ric[:, :, 2] .= Matrix{ComplexF64}(I, N, N) - dummy_chunk = FFS.IntegrationChunk(psi, psi, false, 0, 1) - params = (ctrl, equil, mats, intr, odet, dummy_chunk) - FFS.riccati_der!(du_ric, u_ric, params, psi) - dS_ric = du_ric[:, :, 1] - - ref = max(norm(dS_manual), 1e-10) - err = norm(dS_ric - dS_manual) / ref - max_err = max(max_err, err) - status = err < threshold ? "" : " ← FAIL" - @printf(" %8.4f %14.4e %14.4e %12.4e%s\n", psi, norm(dS_manual), norm(dS_ric), err, status) - end - max_err -end - -println() -if max_err < threshold - @printf("PASSED — max rel error = %.2e (threshold %.0e)\n", max_err, threshold) -else - @printf("FAILED — max rel error = %.2e exceeds threshold %.0e\n", max_err, threshold) - exit(1) -end -println() diff --git a/docs/development/architecture.md b/docs/development/architecture.md index 5c5a4a356a..7f17417fba 100644 --- a/docs/development/architecture.md +++ b/docs/development/architecture.md @@ -127,7 +127,7 @@ Splines are provided by the external `FastInterpolations` package rather than by - Reads kinetic profiles configured under `[KineticForces]` 11. **ErrorFields** (`src/ErrorFields/`) - Error-field sensitivity to coil misalignment - - `Sensitivity.jl` - central-difference linearization of every coil set's control-surface spectrum with respect to its rigid shifts and tilts, on one shared boundary grid + - `Sensitivity.jl` - exact linearization of every coil set's control-surface spectrum with respect to its rigid shifts and tilts, from the Biot–Savart field and its gradient on one shared boundary grid - `sensitivity_table` projects that linearization onto any windowed dominant mode post hoc (in memory or from `gpec.h5`); consumes `PerturbedEquilibrium.ResonantCoupling` and `ForcingTerms.coil_forcing_modes` - Configured under `[ErrorFields]`; writes `ErrorFields/CoilSensitivities/` @@ -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 403fb7ffc5..944df0f9f7 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/`. @@ -40,10 +40,10 @@ Top level (11 groups): | `Info/` | Run metadata: `git_version`, mode-number ranges (`mpert`, `mlow`, …, `mn_index`), `psilim`, `qlim`, `Runtimes/` (per-stage wall-clock seconds) | | `Input/` | Rerun snapshot: `gpec_toml_raw`, `RawInputs/{Equilibrium, ForcingTerms, Coils/, Kinetic, Wall, ErrorFields}` | | `Equilibrium/` | Scalars (`beta_N`, `q_axis`, `q_95`, `I_p`, …) plus `Profiles/` (1-D on `psi`: 2piF, mu0p, dVdpsi, q) and `Geometry/` (2-D on `psi`×`theta`: rcoords, offset, nu, jac) | -| `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (closed ξ profiles in the shared layout, the gal surface list, `gal_basis_output`-gated `Basis/`), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | +| `ForceFreeStates/` | `Solutions/ForwardIntegration/` (u-solutions), `Solutions/GalerkinIntegration/` (the gal surface list, `gal_basis_output`-gated `Basis/`), `Solutions/Match/` (closed ξ profiles of a `[Match]` in the shared layout, on the grid of the Galerkin or Riccati outer solutions), `write_el_matrices`-gated `EulerLagrangeMatrices/{Ideal,Kinetic}`, `FreeBoundaryStability/`, `EdgeScan/` | | `LocalStability/` | Mercier `D_I`, resistive interchange `D_R`, `ballooning_Delta_prime` on `psi`; the ballooning α boundary on `ballooning_psi` | -| `SingularSurfaces/` | Per-rational-surface data: `rational_psi`/`rational_q`/`rational_m`/`rational_n`, GGJ coefficients, `Delta_prime_matrix`/`Delta_prime_raw`/`Delta_coil`/`pest3_A`/`pest3_B`/`pest3_Gamma` (Riccati or Galerkin alike), the inner-layer `Match/` results, `Kinetic/` | -| `PerturbedEquilibrium/` | `ForcingModes/`, `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | +| `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/`, `ForcingSources/` (each forcing source's b̃ and dominant-mode overlap, summing to the totals), `Response/`, `ResponseMatrices/`, `SingularCoupling/`, `Energies/`, `TorqueResponse/` (kinetic forward solves: ψ-resolved `T_xe`, `T_source`), control-surface spectra | | `KineticForces/` | `/` (torque/energy profiles, `dTdpsi_ell` resolved by bounce harmonic on the `ell` scale, `KineticMatrices/`); multi-ion runs add `PerSpecies///` with the same per-method layout, summing to the top-level total | | `ErrorFields/` | `CoilSensitivities/` (per-coil-set control-surface spectra and their rigid shift/tilt derivatives, `DominantMode/` full-window projection); `MonteCarlo/` (intrinsic and corrected `\|δ\|` histograms over the sampled tolerances, per batch and averaged); `Risk/` (threshold density, `P(lock\|δ)`, locking probabilities, `ToleranceScan/`); `NTV/` (correction-coil overlap and NTV torque couplings per kAt) | | `Tearing/` | `PerSurface/` (+ `DpMatrix/`), `Roots/`, `LayerWidths/`, `Diagnostics/{ValidRoots,Poles,FilteredRoots}` (+ `*Winding` with `root_classification = winding`), `Scan/Surface_/`, `CriticalResonantField/` (+ `Scan/Surface_/`) | diff --git a/docs/development/references.md b/docs/development/references.md index 9dbb3c4112..e1ca1cda8e 100644 --- a/docs/development/references.md +++ b/docs/development/references.md @@ -112,7 +112,7 @@ GPEC will eventually implement resistive MHD stability analysis based on: - **Glasser (2018)**: "A robust solution for the resistive MHD toroidal Δ′ matrix in near real-time" - Location: `docs/resources/2018-Glasser-A robust solution for the resistive MHD toroidal Delta-prime matrix in near real-time.pdf` - - Published: Physics of Plasmas **25**, 032501 (2018) + - Published: Physics of Plasmas **25**, 082502 (2018) - Describes: Fast computation of Δ' matrix for resistive stability - **Wang et al. (2020)**: "Modeling of resistive plasma response in toroidal geometry using an asymptotic matching approach" diff --git a/docs/development/regression-harness.md b/docs/development/regression-harness.md index c6da88b19a..22a715e67f 100644 --- a/docs/development/regression-harness.md +++ b/docs/development/regression-harness.md @@ -115,7 +115,7 @@ regress --cases solovev_n1 --ref-range develop~10..develop - `--jobs N` — run N cases at a time (see *Parallel lanes* above) - `--isolate` — run each case in its own fresh subprocess instead of a warm worker -GPEC workers run with `-t auto` (all cores) so GPEC's threaded kernels are active; set `GPEC_REGRESS_THREADS=1` to force single-threaded runs. Tracked quantities are not bit-identical across thread counts. Most move only in the last few bits, inside their noise floors; the parallel Riccati integrator splits its domain by thread count, so its energies move by ~5e-9 and its step counts by ~2 between 1 and 16 threads, and the Riccati cases' floors are set above that spread. The count each run actually used is recorded in its environment fingerprint (shown in the report's `env:` lines), and the report flags two compared runs with different counts. Thread count is not part of the cache key; a `CHANGED` row in a comparison across thread counts that sits just above its floor is worth re-checking at a matched `GPEC_REGRESS_THREADS`. +GPEC workers run with `-t auto` (all cores) so GPEC's threaded kernels are active; set `GPEC_REGRESS_THREADS=1` to force single-threaded runs. Tracked quantities are not bit-identical across thread counts. Most move only in the last few bits, inside their noise floors; the Riccati integrator's chunking does not depend on the thread count. The count each run actually used is recorded in its environment fingerprint (shown in the report's `env:` lines), and the report flags two compared runs with different counts. Thread count is not part of the cache key; a `CHANGED` row in a comparison across thread counts that sits just above its floor is worth re-checking at a matched `GPEC_REGRESS_THREADS`. On a machine you share with other people or with your own parallel sessions, `-t auto` is antisocial: set `GPEC_REGRESS_THREADS` to a bounded count, and `JULIA_NUM_PRECOMPILE_TASKS` alongside it, since `Pkg.instantiate()` otherwise fans out to `Sys.CPU_THREADS + 1` precompile workers at the start of every ref. If the machine has a batch scheduler, submit the run through it and pin both variables to the allocation, with `--jobs` × `GPEC_REGRESS_THREADS` equal to the CPUs requested. diff --git a/docs/src/api.md b/docs/src/api.md index 4cb8938ddc..efb7c19987 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -10,7 +10,7 @@ eq = PlasmaEquilibrium("input.geqdsk"; jac_type="hamada", kinetic_file="kineti ffs = solve(eq, Forward(); nn=1, delta_mlow=8, delta_mhigh=8, vac_flag=true) # [ForceFreeStates]: Forward, no wall, for the response below ls = solve(LocalStabilityProblem(eq; alpha_boundary_scan=true), Ballooning()) # [LocalStability] resp = plasma_response(ffs; compute_singular_coupling=true) # [PerturbedEquilibrium] -pe = perturbed_equilibrium(resp, RMPField("coils.dat")) # with the [ForcingTerms] drive +pe = perturbed_equilibrium(resp, ForcingField("coils.dat")) # with the [ForcingTerms] drive kf = kinetic_torque(pe, KineticForcesControl()) # [KineticForces] ef = error_fields(resp, pe.coil_sets, ForcingTerms.CoilConfig(ft_ctrl); # [ErrorFields]; ft_ctrl: the [ForcingTerms] control tolerances=ErrorFields.read_tolerance_toml("tolerances.toml")) @@ -29,8 +29,8 @@ foreach(r -> save_to_hdf5("gpec.h5", r), (pe, kf, ef, tear)) | ForceFreeStates | `[ForceFreeStates]` + `[Forward]`, `[Riccati]` or `[Galerkin]` | `solve(ForceBalanceProblem(eq; ...), Forward() \| Riccati() \| Galerkin())` | `ForceFreeStatesResult` | | LocalStability | `[LocalStability]` + `[Ballooning]` | `solve(LocalStabilityProblem(eq; ...), Ballooning(; ...))` | `LocalStabilityResult` | | Match | `[Match]` + `[GGJ]` | `solve(MatchProblem(ffs; ...), GGJModel())` | `ForceFreeStatesResult` with `closure == :matched` | -| Drive | `[ForcingTerms]` | `RMPField(ft_ctrl)` (a `ForcingTermsControl`), `RMPField(file)`, `RMPField(modes)` | `RMPField` | -| PerturbedEquilibrium | `[PerturbedEquilibrium]` | `plasma_response(ffs; ...)`, then `perturbed_equilibrium(resp, rmp; ...)` | `PlasmaResponse`, `PerturbedEquilibriumState` | +| Drive | `[ForcingTerms]` | `ForcingField(ft_ctrl)` (a `ForcingTermsControl`), `ForcingField(file)`, `ForcingField(modes)` | `ForcingField` | +| PerturbedEquilibrium | `[PerturbedEquilibrium]` | `plasma_response(ffs; ...)`, then `perturbed_equilibrium(resp, field; ...)` | `PlasmaResponse`, `PerturbedEquilibriumState` | | KineticForces | `[KineticForces]` | `kinetic_torque(pe, KineticForcesControl(; ...))` | `KineticForcesResult` | | ErrorFields | `[ErrorFields]` | `error_fields(resp, pe.coil_sets, CoilConfig(...); ...)` | `ErrorFieldsResult` | | Tearing | `[Tearing]` + `[SLAYER]` or `[GGJ]` | `solve(TearingProblem(ffs; ...), SLAYERModel() \| GGJModel(); config=TearingConfig(...))` | `TearingResult` | @@ -48,12 +48,12 @@ ForceFreeStatesResult Riccati, ideal closure Modes n = 1, m = -4:3 (8 total) Domain ψ ∈ [0.0001, 0.9995], q_lim = 3.262 Surfaces 2: 2/1 @ ψ = 0.1221, 3/1 @ ψ = 0.8804 - Fixed boundary not reported (the Riccati (S, I) history cannot show crossings) + Fixed boundary 8 crit sign changes (unvalidated, not a stability verdict) Free boundary stable: et₁ = 16.4, ep₁ = 14.04, ev₁ = 2.365, vacuum λ = 2.315 - Δ′_ii (ψ_N) 2/1: 0.1781, 3/1: -215.7 - Solution not computed (Riccati stores no ξ profiles) + Δ′_ii (ψ_N) 2/1: 0.1781, 3/1: -317.9 + Solution ξ profiles stored (448 ψ nodes, el_axis basis) Wall ConformalWall, standoff = 0.2415 a - Plots 13 of 15 available (see available_plots) + Plots 14 of 15 available (see available_plots) ``` The fields themselves are documented in each type's docstring. @@ -64,13 +64,14 @@ Every plot in [`Analysis`](analysis.md) takes the result in memory or the path o ```julia-repl julia> available_plots(ffs) -Plots for ForceFreeStatesResult (riccati): 13 of 15 available +Plots for ForceFreeStatesResult (riccati): 14 of 15 available ForceFreeStates ✓ plot_ffs_summary the stability panels the run supplies - ✗ plot_mode_displacement needs stored ξ profiles: use the Forward integrator or a matched Galerkin solve (Riccati and unmatched Galerkin store none) ✓ plot_critical_determinant critical determinant against ψ_N ⋮ + ✗ plot_cond_fbar needs the kinetic singular-surface scan: run with a kinetic source and singfac_min > 0 + ⋮ ``` A plot the source cannot draw throws an `ArgumentError` with the same reason, and a summary leaves out the panels it cannot draw: @@ -107,16 +108,16 @@ The `kinetic_file` (and, for HDF5, `kinetic_group`) keyword reads the kinetic pr ## Combining forcing sources -`RMPField`s form a vector space: `+`, `-` and scalar `*` build lazy linear combinations that compute nothing until `perturbed_equilibrium` materializes them, and because the response is linear in the forcing, driving with a combination equals combining the materialized fields; a complex scalar phase-rotates a source. +`ForcingField`s form a vector space: `+`, `-` and scalar `*` build lazy linear combinations that compute nothing until `perturbed_equilibrium` materializes them, and because the response is linear in the forcing, driving with a combination equals combining the materialized fields; a complex scalar phase-rotates a source. ```julia -nominal = RMPField("nominal_efc.dat") -weld_field = RMPField("weld_fields.h5") +nominal = ForcingField("nominal_efc.dat") +weld_field = ForcingField("weld_fields.h5") pe = perturbed_equilibrium(resp, 2.0 * nominal + 0.5 * weld_field) ``` This is the substrate for error-field workflows: build per-unit sources (a coil set per ampere, a displacement field per millimetre), then assemble physical cases by weighting and summing, with one `plasma_response` serving every combination. -`RMPField(modes)` wraps a control-surface spectrum computed elsewhere, in the unit-norm ``\Phi_x`` convention, as a leaf. +`ForcingField(modes)` wraps a control-surface spectrum computed elsewhere, in the unit-norm ``\Phi_x`` convention, as a leaf. The weights are linear-combination coefficients, not physical amplitudes: a coil set with a failed conductor is `nominal - failed_coil`, not `0.9 * nominal`. ## Choosing an integrator @@ -124,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 @@ -137,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; a Riccati-fed match fills `bpen` and the resonant data but keeps `solution === nothing`. +The problem needs a Δ′ payload with error-field (EF) columns, so it accepts Galerkin and Riccati results with `error_field_response=true` (the default; Riccati also needs `vac_flag=true`). 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/error_fields.md b/docs/src/error_fields.md index 1cd5c3b47c..0ae79df08e 100644 --- a/docs/src/error_fields.md +++ b/docs/src/error_fields.md @@ -11,7 +11,7 @@ Once one plasma solve exists the resonant drive is linear in each coil's motion, 4. **Locking risk** (`[ErrorFields.scenario]`, `[ErrorFields.Risk]`, `ErrorFields/Risk/`): the overlap distribution against the empirical penetration-threshold scaling, giving the locking probability and its scan against tolerance scale, from which the allowable tolerance follows. 5. **Correction limits** (`[ErrorFields.NTV]`, `ErrorFields/NTV/`): how much correction current each array may carry before the NTV torque of its non-resonant field spends the rotation budget, and how much it needs. -For every named coil set of a coil-forced run the stage evaluates the root-area-weighted control-surface spectrum ``\tilde b`` of the set as built and its central-difference derivatives with respect to the six rigid-body degrees of freedom, the shifts ``(\Delta x, \Delta y, \Delta z)`` in metres and the rotations ``(\theta_x, \theta_y, \theta_z)`` about the machine axes in degrees, placed on the run's (m, n) ordering so that they are exactly the vectors the resonant coupling matrix and its singular vectors act on (see [Dominant resonant-coupling mode](perturbed_equilibrium.md#Dominant-resonant-coupling-mode)). +For every named coil set of a coil-forced run the stage evaluates the root-area-weighted control-surface spectrum ``\tilde b`` of the set as built and its exact derivatives with respect to the six rigid-body degrees of freedom, the shifts ``(\Delta x, \Delta y, \Delta z)`` in metres and the rotations ``(\theta_x, \theta_y, \theta_z)`` right-handed about the machine ``+x``, ``-y`` and ``+z`` axes in degrees, placed on the run's (m, n) ordering so that they are exactly the vectors the resonant coupling matrix and its singular vectors act on (see [Dominant resonant-coupling mode](perturbed_equilibrium.md#Dominant-resonant-coupling-mode)). The stored primitive is the linearization of the spectrum, not a scalar, so the resonant surfaces retained, the singular mode and the normalization are post-hoc choices, and every later step can be re-evaluated from `gpec.h5` without a new plasma solve. In the snippets below `EF` is `GeneralizedPerturbedEquilibrium.ErrorFields` and `AEF` is `GeneralizedPerturbedEquilibrium.Analysis.ErrorFields`. @@ -47,13 +47,11 @@ It holds only while the plasma still rotates, so the current is capped at ``I_\m ## Running it -The stage needs a `[PerturbedEquilibrium]` run with `forcing_data_format = "coil"` and the singular coupling computed; `examples/DIIID-like_error_field_example` is the complete case, with the DIII-D C-coil as the n = 1 source and the eighteen F coils as single-filament hoops whose error-field content is entirely their sensitivity to misalignment. +The stage needs a `[PerturbedEquilibrium]` run with `[ForcingTerms]` coil sets and the singular coupling computed; `examples/DIIID-like_error_field_example` is the complete case, with the DIII-D C-coil as the n = 1 source and the eighteen F coils as single-filament hoops whose error-field content is entirely their sensitivity to misalignment. From its deck: ```toml [ErrorFields] -fd_step_shift_m = 1e-3 # central-difference step of the rigid shifts [m] -fd_step_tilt_deg = 0.1 # central-difference step of the rigid tilts [degrees] rotation_center = "conductor" # tilt pivot: each conductor's own centre, or "set" for the whole set's exclude_coils = [] # coil sets that are not error-field sources (the NTV efc_coils are excluded automatically) tolerance_file = "tolerances.toml" # manufacturing tolerances, relative to the deck directory @@ -154,7 +152,7 @@ AEF.plot_error_field_summary("gpec.h5"; save_path="error_field_summary.png") | Dataset | Meaning | |---|---| -| `ErrorFields/CoilSensitivities/field_as_designed`, `shift_sensitivity_per_m`, `tilt_sensitivity_per_deg` | the control-surface spectrum of each coil set as built and its derivatives with respect to the rigid shifts and tilts, with the current pattern they were evaluated at and the finite-difference linearity residual per tap | +| `ErrorFields/CoilSensitivities/field_as_designed`, `shift_sensitivity_per_m`, `tilt_sensitivity_per_deg` | the control-surface spectrum of each coil set as built and its derivatives with respect to the rigid shifts and tilts, with the current pattern they were evaluated at | | `ErrorFields/CoilSensitivities/DominantMode/delta_as_designed`, … | the overlaps and sensitivities projected onto the run's full-window dominant mode, their direction-averaged in-plane magnitudes, and the shift and tilt that would cancel the as-designed overlap | | `ErrorFields/MonteCarlo/abs_delta_pdf`, `abs_delta_efc_pdf`, `abs_delta_bin_edges` | the intrinsic and corrected ``\lvert\delta\rvert`` histograms over the sampled tolerances, per batch and averaged | | `ErrorFields/MonteCarlo/abs_delta_total_as_designed`, `abs_delta_worst_case` | the overlap of the design as built and the worst-case bound with every term at its tolerance edge and in phase | @@ -167,7 +165,8 @@ Every dataset name follows one grammar, `[_][_efc][_/vertices`, `triangles`, `element_offsets`; see `read_magnetic_material_h5`). +Every element is saturated along the equilibrium field at its centroid, ``M = f\,\mu_0 M_s\,\hat B_0/\mu_0``, and its field is the exact field of a uniformly magnetized polyhedron: a surface charge ``M\cdot\hat n`` on each face, each triangle integrated in closed form (Van Oosterom & Strackee, IEEE Trans. Biomed. Eng. 30, 125 (1983)). +That field is sampled on the same `mtheta_coil × nzeta_coil` boundary grid as the coils. +The equilibrium must carry its flux map outside the plasma (a g-file or IMAS), every vertex must lie inside that map's grid and outside the separatrix, and no control-surface point may lie inside an element. + +```toml +[[ForcingTerms.magnetic_material]] +name = "iter_inserts" # set to read from the geometry file +h5_file = "iter_inserts.h5" # magnetic_material// geometry +saturation_field = 1.7 # μ₀M_s, in tesla +fill_fraction = 1.0 # magnetic fraction of each element's volume +``` + +## Forcing sources + +Each coil set, forcing file, spectrum and magnetic material set is one forcing source, and the run records each source's contribution beside the total. +Give several `[[ForcingTerms.coil_set]]` or `[[ForcingTerms.magnetic_material]]` blocks the same `group = "