Skip to content

ForceFreeStates/Tearing - API! - Pose inner-layer matching and tearing as problems solved on the published result - #507

Open
matt-pharr wants to merge 17 commits into
developfrom
refactor/post-solve-matching
Open

matt-pharr wants to merge 17 commits into
developfrom
refactor/post-solve-matching

Conversation

@matt-pharr

@matt-pharr matt-pharr commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Release note

  • Audience: users
  • Numerical impact: matched outputs move ≤ 1.2e-10 (round-off) (harness @ 289f6ea)
  • Migration: see below

Matching and tearing are now problems solved on a finished force-free-states result.

using GeneralizedPerturbedEquilibrium

# Equilibrium, then the kinetic profiles the inner layer reads η, ρ and rotation from
eq = PlasmaEquilibrium("TkMkr_D3Dlike_Hmode.geqdsk"; jac_type="hamada", grid_type="ldp",
    psilow=1e-4, psihigh=0.993, mpsi=128, mtheta=256)
attach_kinetic_profiles!(eq, "TkMkr_D3Dlike_Hmode_kinetic.h5")

# Force-free states; matching needs the coil-response block (rpec_flag)
prob = EulerLagrangeProblem(eq; nn=1, delta_mlow=8, delta_mhigh=4, qlow=1.02, set_psilim_via_dmlim=false)
ffs = solve(prob, Galerkin(; pfac=0.03, rpec_flag=true, cut_solution=true))

# Driven matching with the GGJ inner layer (ray backend by default)
matched = solve(MatchProblem(ffs), GGJModel())
matched.bpen                      # penetrated resonant field, surface × coil

# A rotation scan reuses the one outer solve
nsurf = size(matched.bpen, 1)
bpens = [solve(MatchProblem(ffs; rotation=fill(f, nsurf)), GGJModel()).bpen for f in (1.0, 4.0, 16.0)]

# Tearing growth rates with the SLAYER slab layer
tear = solve(TearingProblem(ffs), SLAYERModel())
tear.gamma_Hz
  • Runs as written on examples/DIIID-like_ideal_example/ files (~1.5 min).
  • SLAYER does tearing only: slab, tearing parity.
  • Riccati also matches: add vac_flag=true; no matched ξ.
  • TearingProblem with GGJModel() runs; its γ are placeholders.

What changed

  • MatchProblem + GGJModel(): matching after the solve.
  • TearingProblem + SLAYERModel()/GGJModel(): growth rates.
  • Scans reuse one outer solve.
  • Kinetic profiles live on the equilibrium.
  • One GGJ-parameter builder, from stored surface geometry.
  • result.match holds the match, any formalism.
  • Matched results drop ideal δW; PE skips them.
  • InnerLayer model types are the solve argument.

Migration

  • ResistiveMatch(...) → MatchProblem(ffs; ...) + GGJModel().
  • Runner.run_slayer → TearingProblem + SLAYERModel().
  • build_ggj_inputs → layer_parameters + ggj_parameters.
  • Profiles: attach_kinetic_profiles!(eq, file).
  • result.galerkin.match → result.match.
  • gpec.h5: GalerkinIntegration/Match/ → SingularSurfaces/Match/.
  • Decks unchanged; [SLAYER] gains inner_model = "ggj_ray".
  • Decks with gal_inner_solver = "galerkin": set gal_inner_xfac=10, nx=1280, nq=5 for the old grid.
  • Matching rejects multi-n and already-matched results.

New defaults

  • GGJ backend: :ray everywhere, tearing included.
  • η: Sauter neoclassical.
  • Galerkin inner grid: backend's 512/4/1.
  • 512/4/1 is ~20× closer to ray than 1280/5/10.

Regression report

  • 7 cases touched by this PR, develop 6fc89d021 vs 289f6ea83.
  • gal_resistive_diiid: 3 match quantities N/A on develop (path rename).
  • diiid_slayer_n1: γ 0.02% (known root-finder scatter).
  • gal_resistive_pe: N/A on both refs (Galerkin PE gap).
  • Everything else unchanged, incl. diiid_error_field.
Full report
================================================================
Case: gal_resistive_diiid — DIII-D-like, n=1, RDCON outer-region Galerkin Δ′ with rpec coil columns (delta_coil)
================================================================

Regression Report: gal_resistive_diiid
======================================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
--------------------------------------------------------------------------------------
Quantity                 origin/develop  refactor/post-solve-matching  Diff     Status
--------------------------------------------------------------------------------------
gal # singular surfaces  4               4                             0.0e+00  OK    
gal singular q values    [4 elem]        [4 elem]                      0.0e+00  OK    
gal PEST3 Δ diagonal     [4 elem]        [4 elem]                      0.0e+00  OK    
||gal Δ′ matrix||        1.244813e+04    1.244813e+04                  0.0e+00  OK    
||gal Δ_coil block||     2.461812e+02    2.461812e+02                  0.0e+00  OK    
gal D_I per surface      [4 elem]        [4 elem]                      0.0e+00  OK    
gal α per surface        [4 elem]        [4 elem]                      0.0e+00  OK    
||gal inner-layer Δ||    N/A             1.474533e+06                  N/A      N/A   
||gal match cout||       N/A             3.061856e-02                  N/A      N/A   
gal match residual       N/A             2.304361e-16                  N/A      N/A   
Runtime (s)              157.0s          128.9s                                 --    
======================================================================================
Summary: 7 unchanged, 3 missing/N/A


================================================================
Case: gal_resistive_pe — DIII-D-like, n=1, DRIVEN/RPEC: gal-matched resistive ξ → PerturbedEquilibrium (coil-driven singular coupling)
================================================================

Regression Report: gal_resistive_pe
==================================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
----------------------------------------------------------------------------------
Quantity                origin/develop  refactor/post-solve-matching  Diff  Status
----------------------------------------------------------------------------------
rational q values       N/A             N/A                           N/A   N/A   
island half-widths      N/A             N/A                           N/A   N/A   
Chirikov parameter      N/A             N/A                           N/A   N/A   
||resonant b field||    N/A             N/A                           N/A   N/A   
resonant b field (all)  N/A             N/A                           N/A   N/A   
penetrated b field      N/A             N/A                           N/A   N/A   
PE Δ' per surface       N/A             N/A                           N/A   N/A   
||C resonant b field||  N/A             N/A                           N/A   N/A   
Runtime (s)             155.3s          141.6s                              --    
==================================================================================
Summary: 8 missing/N/A


================================================================
Case: ggj_reference — GGJ inner-layer Galerkin solver, Glasser & Wang 2020 Eq. 55, γ = 1+i
================================================================

Regression Report: ggj_reference
==========================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
--------------------------------------------------------------------------
Quantity     origin/develop  refactor/post-solve-matching  Diff     Status
--------------------------------------------------------------------------
Re(Δ_odd)    -1.901769e-01   -1.901769e-01                 0.0e+00  OK    
Im(Δ_odd)    -4.159478e-01   -4.159478e-01                 0.0e+00  OK    
Re(Δ_even)   -3.892003e-01   -3.892003e-01                 0.0e+00  OK    
Im(Δ_even)   -3.606845e-01   -3.606845e-01                 0.0e+00  OK    
Runtime (s)  6.2s            7.0s                                   --    
==========================================================================
Summary: 4 unchanged


================================================================
Case: ggj_ray_q500i — GGJ inner-layer :ray backend, q=4 surface, Q = 500i (beyond :galerkin)
================================================================

Regression Report: ggj_ray_q500i
==========================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
--------------------------------------------------------------------------
Quantity     origin/develop  refactor/post-solve-matching  Diff     Status
--------------------------------------------------------------------------
Re(Δ_odd)    2.472008e+00    2.472008e+00                  0.0e+00  OK    
Im(Δ_odd)    1.335402e+01    1.335402e+01                  0.0e+00  OK    
Re(Δ_even)   1.374966e-01    1.374966e-01                  0.0e+00  OK    
Im(Δ_even)   7.427542e-01    7.427542e-01                  0.0e+00  OK    
Runtime (s)  14.6s           14.7s                                  --    
==========================================================================
Summary: 4 unchanged


================================================================
Case: diiid_slayer_n1 — DIII-D-like H-mode equilibrium, n=1, SLAYER tearing-mode analysis (uncoupled per-surface, AMR, validity-gated)
================================================================

Regression Report: diiid_slayer_n1
==================================================================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
------------------------------------------------------------------------------------------------------------------
Quantity                            origin/develop  refactor/post-solve-matching  Diff               Status       
------------------------------------------------------------------------------------------------------------------
SLAYER surface indices              [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER poloidal m                   [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER toroidal n                   [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER minor radius rs              [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER r-based shear                [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER Lundquist S                  [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER D_norm                       [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER P_perp                       [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER tauk                         [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER iota_e                       [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER Q_e                          [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER Q_i                          [6 elem]        [6 elem]                      0.0e+00            OK           
SLAYER Q_root [2/1,3/1,4/1]         [3 elem]        [3 elem]                      1.4e-05            OK           
SLAYER ω_Hz [2/1,3/1,4/1]           [3 elem]        [3 elem]                      2.2e-06            OK           
SLAYER γ_Hz [2/1,3/1,4/1]           [3 elem]        [3 elem]                      2.132e-01 (0.02%)  ** CHANGED **
SLAYER no_root flags [2/1,3/1,4/1]  [3 elem]        [3 elem]                      0.0e+00            OK           
SLAYER enabled flag                 1               1                             0.0e+00            OK           
Runtime (s)                         193.7s          172.0s                                           --           
==================================================================================================================
Summary: 1 changed, 16 unchanged


================================================================
Case: solovev_kinetic_ntv — Solovev analytical equilibrium, n=1, ideal + PE + NTV torque quadrature
================================================================

Regression Report: solovev_kinetic_ntv
========================================================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
--------------------------------------------------------------------------------------------------------
Quantity                                   origin/develop  refactor/post-solve-matching  Diff     Status
--------------------------------------------------------------------------------------------------------
NTV torque fgar [Re, Im]                   [1 elem]        [1 elem]                      0.0e+00  OK    
NTV ψ quadrature evaluations               840             840                           0.0e+00  OK    
root-area-weighted total energy Re(et[1])  4.425941e-01    4.425941e-01                  0.0e+00  OK    
# singular surfaces                        2               2                             0.0e+00  OK    
singular psi locations                     [2 elem]        [2 elem]                      0.0e+00  OK    
q0                                         1.900006e+00    1.900006e+00                  0.0e+00  OK    
Runtime (s)                                202.1s          168.3s                                 --    
========================================================================================================
Summary: 6 unchanged


================================================================
Case: diiid_error_field — DIII-D-like error-field assessment, n=1: ErrorFields stage with the NTV-limited correction couplings
================================================================

Regression Report: diiid_error_field
==============================================================================================================
Ref 1: origin/develop  @ 6fc89d021 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
Ref 2: refactor/post-solve-matching  @ 289f6ea83 (2026-10-09)
       env: julia 1.12.6, arm64-apple-darwin24.0.0, manifest 3ec0d96d (pinned), 6 threads/6 BLAS, jit build
--------------------------------------------------------------------------------------------------------------
Quantity                                         origin/develop  refactor/post-solve-matching  Diff     Status
--------------------------------------------------------------------------------------------------------------
EFC overlap per kAt                              [1 elem]        [1 elem]                      0.0e+00  OK    
EFC whole-field NTV torque per kAt² [N·m]        [1 elem]        [1 elem]                      0.0e+00  OK    
EFC residual-field NTV torque per kAt² [N·m]     [1 elem]        [1 elem]                      0.0e+00  OK    
EFC reference rotation ω_ref [rad/s]             [1 elem]        [1 elem]                      0.0e+00  OK    
EFC rotation-scan shifts [rad/s]                 [9 elem]        [9 elem]                      0.0e+00  OK    
EFC residual torque against rotation [N·m/kAt²]  [9 elem]        [9 elem]                      0.0e+00  OK    
dominant-coupling singular values                [3 elem]        [3 elem]                      0.0e+00  OK    
|delta_nominal| of coil set 1                    1.414087e-06    1.414087e-06                  0.0e+00  OK    
|Σ δ_as_designed| of the error-field coils       3.323139e-18    3.323139e-18                  0.0e+00  OK    
Monte Carlo mean |δ| of the error-field coils    4.701976e-05    4.701976e-05                  0.0e+00  OK    
Runtime (s)                                      561.1s          529.0s                                 --    
==============================================================================================================
Summary: 10 unchanged

Reviewing this PR

  • Review the full diff, not commit by commit.
  • Turn on "Hide whitespace": _compute_match re-indents a block.
  • Moved (check only the listed edits):
    • gal_match_rpec → _compute_match: ctrl.gal_* → prob.*, the backend if → solve_inner_profile(model, …).
    • Its 4·msing system → _match_system, verbatim; a dead duplicate in resonant_match_rpec is deleted.
    • GalMatchResult → MatchResult, plus reconnected_flux.
    • write_galerkin!'s Match/ block → write_match!, verbatim.
    • run_slayer → solve(::TearingProblem) + _tearing_params; only the profile source changed.
    • build_ggj_inputs η/ρ → layer_parameters; τ_A/τ_R → ggj_parameters.
    • resist_eval deleted: a second port of resist_geometry.
    • kinetic_profiles argument → equil.kinetic, in 6 driver functions.
  • New (where attention belongs):
    • MatchProblem, _matched_result/_with, the δW drop.
    • TearingProblem, _profiles_from_equilibrium, _tearing_params(::GGJModel).
    • GGJModel options and their forwarding (InnerLayer/GGJ/GGJ.jl).
    • attach_kinetic_profiles!, equil.kinetic.
    • Deck match block in run_force_free_states; new defaults.
    • Tests: runtests_matching_models.jl, new runtests_solve_api.jl testsets.

Notes for reviewers

  • src/ is −185 lines net vs develop.
  • Deck outputs byte-identical commit to commit, except:
  • matching moves ≤ 1.2e-10 (geometry ports agree to 2.4e-14).
  • SLAYER roots scatter run to run (known).
  • GGJ tearing γ extraction is future work.
  • Matched PE needs resistive δW: future physics work.
  • Fortran gpec does the same: drops ideal solutions.
  • Riccati vs Galerkin bpen differ near the edge.
  • Galerkin Δ′/Δ_coil edge instability: validate vs Fortran.
  • |bpen| rising at low rotation is known GGJ behavior.
  • Develop merged twice; one trivial conflict (CoreTypes.jl).
  • REFACTOR_PLAN.md leaves the repo (−1117 lines).

🤖 Generated with Claude Code

https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf

@matt-pharr matt-pharr self-assigned this Oct 6, 2026
@matt-pharr
matt-pharr requested a review from d-burg October 6, 2026 12:41
@github-actions github-actions Bot added api Config key, output dataset or exported name changed changed-results Results move or an interface breaks - read before upgrading labels Oct 6, 2026
@matt-pharr

Copy link
Copy Markdown
Collaborator Author

CC @jhalpern30 since you were party to the earlier steps of this refactoring

@matt-pharr matt-pharr changed the title ForceFreeStates/Tearing - API! - Pose inner-layer matching and tearing as problems solved on the published result ForceFreeStates/Tearing - API - Pose inner-layer matching and tearing as problems solved on the published result Oct 6, 2026
@github-actions github-actions Bot removed the changed-results Results move or an interface breaks - read before upgrading label Oct 6, 2026
@matt-pharr matt-pharr added this to the GPEC v2.0.0 milestone Oct 6, 2026
matt-pharr and others added 3 commits October 6, 2026 16:29
…d model config's way

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…e surface geometry in one place

resist_eval re-integrated the same six flux-surface averages that resist_geometry
already stores on every surface's restype, and build_ggj_inputs repeated
layer_parameters' resistivity and mass-density closure. Both are replaced by one
ggj_parameters(sing, equil; eta, rho, gamma) on top of restype, shared by the
driven match and the GGJ tearing solve; layer_parameters takes the profile source
as a keyword so both callers derive eta/rho through it.

The two geometry ports agree to <= 2.4e-14 relative on every surface of the LAR,
DIIID Galerkin-resistive and DIIID SLAYER decks (the residue tracks
q - q_spline at the rational root). Matched outputs move at round-off only
(<= 1.2e-10); ideal, Galerkin-ideal and tearing outputs are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…er argument of solve

ForceFreeStates.GGJ/SLAYER duplicated InnerLayer's GGJModel/SLAYERModel as
configuration wrappers, with forwarding methods and a translation step in the
tearing solve. The InnerLayer types are now the inner-layer argument of
solve(MatchProblem, ·) and solve(TearingProblem, ·) directly: GGJModel carries
its backend keywords as options, forwarded to every solve under call-site
keywords; SLAYER's chi fallbacks are read from the SLAYERControl that already
held them. Removes Matching/Models.jl and the exported GGJ name that collided
with the InnerLayer.GGJ submodule.

Deck outputs are byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@matt-pharr matt-pharr changed the title ForceFreeStates/Tearing - API - Pose inner-layer matching and tearing as problems solved on the published result ForceFreeStates/Tearing - API! - Pose inner-layer matching and tearing as problems solved on the published result Oct 7, 2026
@github-actions github-actions Bot added the changed-results Results move or an interface breaks - read before upgrading label Oct 7, 2026
matt-pharr and others added 7 commits October 7, 2026 12:50
…sistivity the inner-layer defaults everywhere

One set of inner-layer defaults, held in one place:

- The deck's gal_inner_* keys no longer carry their own grid values
  (1280/5/10, the Fortran deltac reference); unset keys keep the Galerkin
  backend's defaults (512/4/1), which agree with the certified ray Δ about 20x
  more closely on the DIIID matched surfaces at a fraction of the cost.
- The ray backend is the default GGJ backend in tearing as well as matching:
  TearingProblem accepts GGJModel(), and the [SLAYER] deck gains
  inner_model = "ggj_ray".
- layer_parameters and MatchProblem derive the Sauter neoclassical η by default,
  matching the tearing solve; SpitzerModel() stays selectable.

No example deck sets these keys or derives η, so deck outputs are byte-identical
to the previous commit; API calls relying on the old defaults move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ttach kinetic profiles in one way

_matched_result rebuilt ForceFreeStatesResult and GalerkinResult from every
field positionally; a field-name copy replaces both and no longer breaks when a
field is added. attach_kinetic_profiles! forwards its keywords to
load_kinetic_profiles instead of restating them, and becomes the one way to
attach profiles: the kinetic_file keyword on PlasmaEquilibrium, which restated
the same eight keywords again and had no callers, is removed.

Deck outputs are byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf
…seded by MatchProblem

scan_resistivity_m2.jl and scan_rotation_m2.jl plotted per-point deck runs that
each re-solved the outer region; MatchProblem reuses one outer solve, and the scan
is a short loop (docs/api.md). scan_match_m2.jl, added earlier in this branch for
that comparison, goes with them. REFACTOR_PLAN.md records the cut-down series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf
… to what a reader needs

User-facing docstrings (MatchProblem, TearingProblem, layer_parameters, MatchResult,
attach_kinetic_profiles!) say what is computed, in what units, and how to call it;
developer-only file headers, helper docstrings and inline comments shrink to a line
or two. Design rationale and history move out of the source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf
…deal δW from matched results

The match product lived inside GalerkinResult, so a Riccati-fed match had nowhere
to go and kept only bpen. It now sits on ForceFreeStatesResult beside delta_prime
and bpen, for every formalism, and is written under SingularSurfaces/Match/ next to
the Δ′ it was solved from. A :matched result drops wp and free_boundary: the ideal
δW does not describe the matched plasma, so PerturbedEquilibrium warns and skips
instead of mixing ideal and matched physics (as Fortran gpec deallocates its ideal
solutions under gal_flag). The ideal reference keeps its δW.

Matched-deck datasets are identical apart from the Match/ path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf
…ofile errors, test that solves leave inputs untouched

MatchProblem rejects multi-n results, since the forced eigenvalue and field scale use a
single n. Missing-profile errors name the deck keys on the deck path and say to attach
before solving (or to ffs.equil) on the API path. New tests check that a solve leaves the
equilibrium untouched and that repeated MatchProblem solves leave the outer result
untouched. api.md notes that Riccati matching needs vac_flag=true and that GGJ tearing γ
are placeholders; stale run_slayer references fixed. REFACTOR_PLAN.md leaves the
repository; §7D is to be re-planned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VkufdJ1x3rjhWKMz9FzaMf
@matt-pharr

Copy link
Copy Markdown
Collaborator Author

Also CC @StuartBenjamin for the new syntax which will be particularly useful for tearing suite

@matt-pharr
matt-pharr marked this pull request as draft October 8, 2026 21:00
@matt-pharr
matt-pharr marked this pull request as ready for review October 9, 2026 15:16
@matt-pharr

Copy link
Copy Markdown
Collaborator Author

@d-burg please prioritize this as I want the shape of this to be final before I go through and refactor GeneralizedPerturbedEquilibrium.jl and this is desired to be in for v2.0.0

@d-burg d-burg left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, the direction is right overall and the moved matching logic is equivalent to the deleted code (signs, transposes, parity and the bpen formula all match by my eye). Before the shape is frozen for v2 it'd be great to have these settled:

  1. The inner layer run must be included in the result. The model is now the solve argument, but SLAYERControl still carries inner_model and the result records the control, so the two can disagree. MatchResult also records no model, backend or options.
  2. Regarding GGJ tearing: either the GGJ γ are marked unmistakably as unvalidated on the object and in the file, or solve(TearingProblem, GGJModel()) should error until extraction is implemented. I have local scripts for this that work robustly, but need to be cleaned up and probably need their own PR.
  3. From claude: '"Profiles live on the equilibrium” currently means the NTV container (SI units, 101 points, and no χ). The tearing layer needs eV, the file’s own grid and χ. The bridge is where the unit and χ differences below come from.'
  4. “Round-off” probably needs qualifying -- the harness shows the three match quantities as N/A on develop, and decks on the Galerkin inner backend change grid.
  5. #463 and #501 change code in the two run_slayer methods this PR deletes, so git cannot carry their hunks. I’d prefer those two land first and this rebases onto them.

Claude also raised some lower priority questions:

  • Attaching profiles before an auto-grid solve now changes the ψ grid on the API path.
  • A deck with [KineticForces] and [SLAYER] but no profile_file used to fail the SLAYER stage and now runs.
  • gamma_Hz/omega_Hz versus the HDF5 units (1/s and rad/s) for the same arrays.
  • TearingProblem accepts multi-n results; MatchProblem rejects them.
  • The default rotation is ω_E from one profile container and toroidal rotation from the other.
  • Riccati matching is effectively new in this PR and is known to differ from Galerkin near the edge (is this correct?)

Comment on lines +15 to +18
Fields: `ffs`, `control::SLAYERControl`.
"""
# `ffs` is duck-typed (equil, surfaces, delta_prime, dir_path) so tests can use stand-ins.
struct TearingProblem{R}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment on line 17 separates the docstring from the struct, and Julia then drops it (checked in a scratch module on 1.11.6: no doc is registered). Folding the note into the docstring fixes it.

Suggested change
Fields: `ffs`, `control::SLAYERControl`.
"""
# `ffs` is duck-typed (equil, surfaces, delta_prime, dir_path) so tests can use stand-ins.
struct TearingProblem{R}
Fields: `ffs` (duck-typed on `equil`, `surfaces`, `delta_prime`, `dir_path`, so tests can use stand-ins), `control::SLAYERControl`.
"""
struct TearingProblem{R}

Comment on lines +99 to +100
error("TearingProblem: no kinetic profiles — set profile_file, or attach profiles " *
"to the equilibrium with attach_kinetic_profiles!(equil, file)")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From claude: after an auto-grid solve ffs.equil is a re-formed copy, so attaching to the equilibrium I passed in has no effect and this error then tells me to do what I just did. Please name ffs.equil, as layer_parameters does.

Suggested change
error("TearingProblem: no kinetic profiles — set profile_file, or attach profiles " *
"to the equilibrium with attach_kinetic_profiles!(equil, file)")
error("TearingProblem: no kinetic profiles on ffs.equil — set profile_file, or attach them with " *
"attach_kinetic_profiles!(ffs.equil, file) (after an auto-grid solve ffs.equil is a re-formed copy, not the equilibrium passed to solve)")

Comment thread docs/src/api.md
Comment on lines +120 to +121
tear = solve(TearingProblem(ffs; coupling_mode=:coupled), SLAYERModel())
tear.gamma_Hz, tear.rational_q # root-found rates per surface

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In coupled mode the result holds one global root, so tear.gamma_Hz and tear.rational_q do not line up and the comment is wrong.

Suggested change
tear = solve(TearingProblem(ffs; coupling_mode=:coupled), SLAYERModel())
tear.gamma_Hz, tear.rational_q # root-found rates per surface
tear = solve(TearingProblem(ffs), SLAYERModel()) # coupling_mode=:coupled returns one global root instead
tear.gamma_Hz, tear.rational_q # root-found rate at each rational surface

@test r_off.enabled == false
end

@testset "the default :ray backend drives the tearing solve" begin

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From claude: this test returns at the empty-surface short-circuit, so it does not show that the :ray backend drives anything. Nothing in the suite runs _tearing_params or _profiles_from_equilibrium. Could you add one small case that solves via profile_file and via attached profiles and compares the per-surface parameters?

Suggested change
@testset "the default :ray backend drives the tearing solve" begin
@testset "TearingProblem accepts a GGJModel and short-circuits on an empty surface list" begin

Comment on lines 63 to 64
- `bpen::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated resonant field from the
inner layer, per surface and driving mode; all zeros under `:ideal` closure.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the move, result.match and SingularSurfaces/Match/* are indexed by the matched subset, but nothing says which surfaces those are, and result.surfaces beside them has a different length whenever the Galerkin domain or m-band drops a rational. Please carry the matched surface list on MatchResult and write it to the group

Suggested change
- `bpen::Matrix{ComplexF64}` - `(msing × numpert_total)` penetrated resonant field from the
inner layer, per surface and driving mode; all zeros under `:ideal` closure.
- `bpen::Matrix{ComplexF64}` - Penetrated resonant field from the inner layer, per surface and
driving mode. `(msing × numpert_total)` zeros under `:ideal` closure; under `:matched` the rows
follow the matched surfaces, which for Galerkin is the in-domain in-band subset of `surfaces`.

gal_inner_cutoff::Int = 5 # cells carrying the large solution as driving term
gal_inner_kmax::Int = 8 # large-x asymptotic series order (↔ order_pow)
# --- Inner-layer "galerkin" backend overrides (gal_inner_solver = "galerkin"; unset keeps the backend default) ---
gal_inner_xfac::Union{Nothing,Float64} = nothing # asymptotic-matching radius multiplier

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From claude: for a deck with gal_inner_solver = "galerkin" and the knobs unset, this silently changes xfac 10→1, nx 1280→512 and nq 5→4. Please qualify the numerical-impact line and replace “Decks unchanged”. I’d also like the numbers behind “~20× closer to ray”, and a harness quantity on the Galerkin inner backend.

rotation::Union{Nothing,AbstractVector{<:Real}}=nothing,
mu_i::Real=2.0,
zeff::Real=1.0,
resistivity_model::NeoResistivityModel=SauterNeoModel(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making Sauter the default routes every non overridden η through restype.f_trap, which is the trapped fraction defect tracked in #497. Should we keep SpitzerModel() as the default until #497 is fixed, or stack?

end

# n_e in m⁻³, T_e in eV, and the E×B frequency at ψ from either profile container.
_layer_profile(kp::Equilibrium.KineticProfileSplines, ψ) = (kp.ne_spline(ψ), kp.Te_spline(ψ) / E_CHG, kp.omegaE_spline(ψ))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The attached profiles carry zeff_spline, loglam_spline and ni_spline, but this reads only n_e, T_e and ω_E and then uses zeff=1.0 and a recomputed lnΛ. The default should take Zeff from equil.kinetic and treat the keywords as overrides

ffs::ForceFreeStatesResult;
eta::Union{Nothing,AbstractVector{<:Real}}=nothing,
rho::Union{Nothing,AbstractVector{<:Real}}=nothing,
rotation::Union{Nothing,AbstractVector{<:Real}}=nothing,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From claude: for the advertised rotation scan the user must know the matched-surface count before posing the problem; today that takes a first solve or a dummy MatchProblem(ffs; ideal=true). I’d accept a scalar for each of eta/rho/rotation and export an accessor for the matched surfaces.

return cof[1:2msing, :], cof[(2msing+1):4msing, :], residual
end

# Write `m` under SingularSurfaces/Match/ (debug-only: exempt from the metadata contract).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From claude: with δW dropped and PerturbedEquilibrium skipped, this group is where a matched run’s results live, so “debug-only, exempt from metadata” no longer fits. Please annotate the datasets, write reconnected_flux, and record the inner model, backend and options.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Config key, output dataset or exported name changed changed-results Results move or an interface breaks - read before upgrading

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants