This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
GPEC (Generalized Perturbed Equilibrium Code, Julia implementation) is a comprehensive Julia reimplementation of the GPEC suite for MHD analysis of fusion plasmas. The code performs equilibrium reconstruction, ideal MHD stability analysis, and perturbed equilibrium calculations including plasma response and singular surface coupling diagnostics.
Relationship to Fortran GPEC: This Julia GPEC is an evolution of the Fortran GPEC code suite, available at https://github.com/PrincetonUniversity/GPEC. When users reference "the Fortran code", "the original GPEC", or "Fortran GPEC", they are referring to that Fortran codebase. This Julia implementation reimplements and extends GPEC's functionality with improved performance and maintainability.
Local GPEC Repository: For code conversion or comparison with the original Fortran implementation, check for a local GPEC repository at ~/Code/gpec. If not found at this location, ask the user for the correct path.
This codebase is implemented in Julia. References to “Fortran GPEC” or “legacy VACUUM” refer to the original upstream Fortran codebase, not a runtime dependency of this Julia implementation.
Current Development Focus: The perturbed_equilibrium branch is implementing full GPEC-style perturbed equilibrium functionality, including singular coupling analysis, island formation diagnostics, and mode-space field reconstruction.
IMPORTANT: The papers in docs/resources/ provide the theoretical foundation for GPEC's algorithms and should be referenced to understand what the code is doing. Citing equations from these papers in code comments and annotations is strongly encouraged to maintain traceability between theory and implementation.
The Vacuum module implements the methods described in:
-
Chance et al. (1997): "Vacuum calculations in azimuthally symmetric geometry"
- Location:
docs/resources/1997-Chance-Vacuum_calculations_in_azimuthally_symmetric_geometry.pdf - Published: Physics of Plasmas 4, 2161 (1997)
- Link: https://pubs.aip.org/aip/pop/article-abstract/4/6/2161/263192
- Describes: Fundamental vacuum response calculation method for tokamak geometry
- Location:
-
Chance et al. (2007): "Calculation of the vacuum Green's function valid even for high toroidal mode numbers in tokamaks"
- Location:
docs/resources/2007-Chance-Calculation of the vacuum Greens function valid even for high toroidal mode numbers in tokamaks.pdf - Published: Physics of Plasmas 14, 052506 (2007)
- Describes: Improved Green's function calculation for high-n modes
- Location:
The ForceFreeStates module (ideal MHD stability analysis) implements methods from:
-
Glasser (2016): "The direct criterion of Newcomb for the ideal MHD stability of an axisymmetric toroidal plasma"
- Location:
docs/resources/2016-Glasser-The_direct_criterion_of_Newcomb_for_the_ideal_MHD_stability_of_an_axisymmetric_toroidal_plasma.pdf - Published: Physics of Plasmas 23, 112506 (2016)
- Describes: FUNDAMENTAL PAPER - Newcomb's criterion for ideal MHD stability (current implementation)
- Location:
-
Glasser (2018): "A Riccati solution for the ideal MHD plasma response with applications to real-time stability control"
- Location:
docs/resources/2018-Glasser-A Riccati solution for the ideal MHD plasma response with applications to real-time stability control.pdf - Published: Physics of Plasmas 25, 032507 (2018)
- Describes: Riccati method for ideal MHD eigenvalue problem
- Location:
The PerturbedEquilibrium module implements GPEC-style perturbed equilibrium calculations from:
-
Park et al. (2007a): "Computation of three-dimensional tokamak and spherical torus equilibria"
- Location:
docs/resources/2007-Park-Computation_of_three-dimensional_tokamak_and_spherical_torus_equilibria-compressed.pdf - Published: Physics of Plasmas 14, 052110 (2007)
- Describes: 3D equilibrium perturbations in toroidal geometry
- Location:
-
Park et al. (2007b): "Control of Asymmetric Magnetic Perturbations in Tokamaks"
- Location:
docs/resources/2007-Park-Control_of_Asymmetric_Magnetic_Perturbations_in_Tokamaks.pdf - Published: Physical Review Letters 99, 195003 (2007)
- Describes: Plasma response to resonant magnetic perturbations (RMP)
- Location:
-
Park et al. (2008): "Spectral asymmetry due to magnetic coordinates"
- Location:
docs/resources/2008-Park-Spectral_asymmetry_due_to_magnetic_coordinates.pdf - Published: Physics of Plasmas 15, 064501 (2008)
- Describes: Coordinate-dependence of the perturbed-field Fourier spectrum, motivating area-normalization of the resonant harmonic to obtain the coordinate-invariant resonant field
- Location:
-
Park et al. (2009): "Importance of plasma response to nonaxisymmetric perturbations in tokamaks"
- Location:
docs/resources/2009-Park-Importance_of_plasma_response_to_nonaxisymmetric_perturbations_in_tokamaks-compressed.pdf - Published: Physics of Plasmas 16, 056115 (2009)
- Describes: Self-consistent plasma response calculation
- Location:
-
Park et al. (2011): "Kinetic energy principle and neoclassical toroidal torque in tokamaks"
- Location:
docs/resources/2011-Park-Physics_of_Plasmas_Kinetic_energy_principle_and_neoclassical_toroidal_torque_in_tokamaks.pdf - Published: Physics of Plasmas 18, 110702 (2011)
- Describes: Energy principle for perturbed equilibria
- Location:
-
Park et al. (2017): "Self-consistent perturbed equilibrium with neoclassical toroidal torque in tokamaks"
- Location:
docs/resources/2017-Park-Self_consistent_perturbed_equilibrium_with_neoclassical_toroidal_torque_in_toka.pdf - Published: Physics of Plasmas 24, 032505 (2017)
- Describes: Self-consistent coupling with neoclassical effects
- Location:
GPEC will eventually implement resistive MHD stability analysis based on:
-
Glasser (2016): "Computation of resistive instabilities by matched asymptotic expansions"
- Location:
docs/resources/2016-Glasser-Computation_of_resistive_instabilities_by_matched_asymptotic_expansions-compressed.pdf - Published: Physics of Plasmas 23, 072505 (2016)
- Describes: Resistive stability analysis and Δ' calculation via matched asymptotic expansions
- Location:
-
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)
- Describes: Fast computation of Δ' matrix for resistive stability
- Location:
-
Wang et al. (2020): "Modeling of resistive plasma response in toroidal geometry using an asymptotic matching approach"
- Location:
docs/resources/2020-Wang-Modeling of resistive plasma response in toroidal geometry using an asymptotic matching approach.pdf - Published: Physics of Plasmas 27, 122509 (2020)
- Describes: Asymptotic matching for resistive plasma response
- Location:
The KineticForces module (formerly PENTRC) implements neoclassical toroidal viscosity calculations. Based on:
-
Logan & Park (2013): "Neoclassical toroidal viscosity in perturbed equilibria with general tokamak geometry"
- Location:
docs/resources/2013-Logan-Neoclassical_toroidal_viscosity_in_perturbed_equilibria_with_general_tokamak_geometry.pdf - Published: Physics of Plasmas 20, 122507 (2013)
- Describes: Neoclassical toroidal viscosity (NTV) in perturbed equilibria
- Location:
-
Logan (2015): "Electromagnetic Torque in Tokamaks with Toroidal Asymmetries"
- Location:
docs/resources/2015-Logan-Electromagnetic_Torque_in_Tokamaks_with_Toroidal_Asymmetries-compressed.pdf - Published: PhD Thesis, Princeton University (2015)
- Describes: Complete NTV theory and implementation. Chapter 7 details the hybrid drift-kinetic MHD eigenfunction calculation: 6 kinetic matrices Ak,Bk,Ck,Dk,Ek,Hk (Eqs 7.30-7.35) as energy-space integrals of perturbed action operators WX,WY,WZ; hybrid Euler-Lagrange equations; resonance splitting/suppression where Fh=(Q-P†)F̄(Q-P)+... shifts singularities away from rational surfaces (Eq 7.46); convergence to ideal limit. Appendix C derives the DCON matrix form of the perturbed action (Eqs C.1-C.11) used to compute the kinetic coefficient matrices. Appendix D details numerical treatment of integrable singularities in bounce averages.
- Location:
- Park et al. (2009): "Nonambipolar Transport by Trapped Particles in Tokamaks"
- Location:
docs/resources/2009-Park-Nonambipolar_Transport_by_Trapped_Particles_in_Tokamaks.pdf - Published: Physical Review Letters 102, 065002 (2009)
- Link: https://doi.org/10.1103/PhysRevLett.102.065002
- Describes: Trapped-particle nonambipolar transport theory underpinning the NTV calculation
- Location:
# Run all tests
julia --project=. -e 'using Pkg; Pkg.activate("."); Pkg.instantiate(); include("test/runtests.jl")'
# Run specific test file
julia --project=. test/runtests.jl test/runtests_solovev.jl
# Available test files:
# - test/runtests_vacuum_julia.jl # Julia vacuum module
# - test/runtests_solovev.jl # Analytical equilibrium
# - test/runtests_ode.jl # ODE integration
# - test/runtests_sing.jl # Singular surface handling
# - test/runtests_fullruns.jl # End-to-end tests# Build documentation locally
julia --project=. build_docs_local.jl
# Documentation hosted at: https://openfusiontoolkit.github.io/GPEC/dev/For faster recompilation during development, use Revise.jl (installed in global environment, not in Project.toml):
using Revise
using GeneralizedPerturbedEquilibriumUse the generic benchmarking tool at benchmarks/benchmark_git_branches.jl to compare performance between branches or commits.
Tool usage:
# Compare feature branch against develop
julia benchmarks/benchmark_git_branches.jl \
--example examples/DIIID-like_ideal_example \
--branch1 develop \
--branch2 feature-branch
# Compare specific commits
julia benchmarks/benchmark_git_branches.jl \
--example examples/DIIID-like_ideal_example \
--commit1 abc123 \
--commit2 def456
# Compare current develop vs develop from 1 month ago
julia benchmarks/benchmark_git_branches.jl \
--example examples/DIIID-like_ideal_example \
--branch1 develop \
--commit1 HEAD~10 \
--branch2 developDefault benchmark case: examples/DIIID-like_ideal_example
Reported metrics:
- Eigenmode energy (
et[1]) - First eigenvalue; verifies calculation correctness - Integration steps - Total ODE solver steps
- Runtime (warmed) - Wall-clock time averaged over multiple warm runs (JIT warmup handled automatically)
- Commit hash - Git commit of code tested
The tool automatically:
- Handles JIT warmup (runs example 3 times, averages last 2)
- Switches between branches/commits
- Stashes uncommitted changes if necessary
- Restores original branch when done
- Reports comparison with percentage differences
Important notes:
- Working directory should be clean or changes will be stashed during branch switching
- Tool requires HDF5.jl for reading euler.h5 output
- Each benchmark run takes several minutes per branch (includes compilation + warm runs)
Benchmark script conventions:
- Benchmark scripts must reference input data from
examples/(e.g.,joinpath(@__DIR__, "..", "examples", "DIIID-like_ideal_example")). Never duplicate example inputs intobenchmarks/. - If a benchmark needs modified TOML settings or a parameter scan, copy inputs to a temporary local directory at runtime — do not commit these copies.
- All outputs (figures, CSVs, HDF5 files) must be saved into
benchmarks/itself (or a self-described subdirectory within it, e.g.,benchmarks/coil_scan_results/). Output files are not committed.
This should be used at least once every single pull request before merging into develop. This test harness is what tracks values as they evolve across changes to the code, and must be both kept up to date and used consistently. Do not forget this and make sure to suggest any new regression cases or updates to existing ones as needed. Remind the user of its existence and report back the output regression report you get when modifying the code significantly. This is extremely important, do not forget this tidbit.
Set up an alias for convenience (optional):
alias regress='julia --project=regression-harness regression-harness/regress.jl'List available cases:
regress --list-casesAvailable regression cases:
----------------------------------------------------------------
diiid_n1 DIII-D-like equilibrium, n=1, ideal + perturbed equilibrium
dir: examples/DIIID-like_ideal_example (24 quantities)
solovev_multi_n Solovev analytical equilibrium, multi-n, ideal stability
dir: examples/Solovev_ideal_example_multi_n (12 quantities)
solovev_n1 Solovev analytical equilibrium, n=1, ideal stability
dir: examples/Solovev_ideal_example (18 quantities)
Compare two branches/commits:
regress --cases diiid_n1 --refs develop,feature/kinetic-damping================================================================
Case: diiid_n1 — DIII-D-like equilibrium, n=1, ideal + perturbed equilibrium
================================================================
[ Info: Cached: diiid_n1 @ 0a905a7d (2026-04-06T23:41:50+09:00)
[ Info: Cached: diiid_n1 @ 44b2494f (2026-04-08T18:30:46+09:00)
Regression Report: diiid_n1
==================================================================================================================
Ref 1: develop @ 0a905a7d (2026-04-06)
Ref 2: feature/kinetic-damping @ 44b2494f (2026-04-08)
------------------------------------------------------------------------------------------------------------------
Quantity develop feature/kinetic-damping Diff Status
------------------------------------------------------------------------------------------------------------------
beta_n -1.376214e+00 -1.376214e+00 0.0e+00 OK
beta_t 1.322850e-02 1.322850e-02 0.0e+00 OK
Chirikov parameter [4 elements] [4 elements] 0.0e+00 OK
delta prime [4 elements] [4 elements] 0.0e+00 OK
plasma energy Re(ep[1]) -8.809610e-01 -8.809610e-01 0.0e+00 OK
total energy Im(et[1]) 6.175834e-05 6.175834e-05 0.0e+00 OK
total energy Re(et[1]) 1.199597e+00 1.199597e+00 0.0e+00 OK
vacuum energy Re(ev[1]) 2.080558e+00 2.080558e+00 0.0e+00 OK
island half-widths [4 elements] [4 elements] 0.0e+00 OK
mpert 34 34 0.0e+00 OK
# singular surfaces 4 4 0.0e+00 OK
npert 1 1 0.0e+00 OK
ODE steps (saved) 740 740 0.0e+00 OK
ODE steps (total) 1348 1348 0.0e+00 OK
PE plasma energy 0.000000e+00 0.000000e+00 0.0e+00 OK
PE total energy 0.000000e+00 0.000000e+00 0.0e+00 OK
pressure profile (checksum) 657ad2329d7b... 657ad2329d7b... identical OK
q0 1.209710e+00 1.209710e+00 0.0e+00 OK
q95 4.505007e+00 4.505007e+00 0.0e+00 OK
q profile (checksum) 75912afcc351... 75912afcc351... identical OK
||resonant flux|| 4.523707e+02 4.523707e+02 0.0e+00 OK
Runtime (s) 50.9s 52.0s --
singular psi locations [4 elements] [4 elements] 0.0e+00 OK
singular q values [4 elements] [4 elements] 0.0e+00 OK
==================================================================================================================
Summary: 23 unchanged, 3 missing/N/A
Compare your uncommitted working tree against develop:
regress --cases solovev_n1 --refs develop,localTrack a specific quantity across cached commits:
regress --show et_real --case solovev_n1History: et_real — solovev_n1
================================================================================
Commit Date Value Δ from prev Status
--------------------------------------------------------------------------------
edff6e86 2026-04-02 -4.624928e-01 -- --
0a905a7d 2026-04-06 -4.624928e-01 0.0e+00 OK
================================================================================
Scan across a range of commits (git-bisect style):
regress --cases solovev_n1 --ref-range develop~10..developOther useful flags:
--force— re-run even if cached--verbose— print GPEC subprocess output--no-instantiate— skipPkg.instantiate()(faster if deps are already resolved)
GPEC follows a three-stage analysis pipeline:
- Equilibrium → Solve Grad-Shafranov equation, compute flux surfaces, safety factor q-profile
- Stability Analysis → Solve ideal MHD eigenvalue problem (DCON-style), identify singular surfaces
- Perturbed Equilibrium → Compute plasma response to external fields, analyze singular coupling and island formation
This workflow is reflected in the modular structure and data flow.
GPEC consists of seven main modules organized in src/:
-
Splines (
src/Splines/) - Numerical interpolation libraryCubicSpline.jl- 1D cubic spline interpolationBicubicSpline.jl- 2D bicubic spline interpolationFourierSpline.jl- Fourier-based spline interpolation- Status: Mature, pure Julia implementation
-
Utilities (
src/Utilities/) - Shared computational toolsFourierTransforms.jl- Efficient Fourier transform utilities with pre-computed basis functions- Provides type-stable functor pattern for repeated transforms
- Used by Vacuum and PerturbedEquilibrium modules
-
Equilibrium (
src/Equilibrium/) - MHD equilibrium solvers- Main entry point:
setup_equilibrium(path)orsetup_equilibrium(config) - Supports multiple equilibrium types:
efit- EFIT g-file formatchease,chease2- CHEASE equilibrium code formatslar- Large Aspect Ratio analytical modelsol- Solovev analytical equilibrium
- Key files:
EquilibriumTypes.jl- Core data structuresReadEquilibrium.jl- Parsing equilibrium filesDirectEquilibrium.jl- Direct Grad-Shafranov solverInverseEquilibrium.jl- Inverse equilibrium solverAnalyticEquilibrium.jl- Analytical solutions
- Status: Stable and feature-complete
- Main entry point:
-
Vacuum (
src/Vacuum/) - Vacuum field calculations and Green's functions- Computes vacuum response matrices for ideal MHD analysis
- Calculates both interior (grri) and exterior (grre) Green's functions
- Main functions:
compute_vacuum_response()- Pure Julia implementation
- Key files:
VacuumStructs.jl- Data structuresVacuumInternals.jl- Core algorithmsVacuumFromEquilibrium.jl- Integration with equilibrium data
- Status: Pure Julia implementation complete and available
-
ForceFreeStates (
src/ForceFreeStates/) - Ideal MHD stability analysis (DCON-style)- Solves ideal MHD eigenvalue problem with force-free boundary conditions
- Identifies singular surfaces where ξ·∇ψ = 0
- Key files:
ForceFreeStatesStructs.jl- Core data structuresOde.jl- ODE solver for Euler-Lagrange equationsSing.jl- Singular point handling and layer analysisFourfit.jl- Fourier fitting routinesFixedBoundaryStability.jl- Fixed boundary analysisFree.jl- Free boundary stabilityBallooning.jl- Local stability scan: Mercier D_I, resistive interchange D_R, and high-n ballooning Δ' (s–α). Replaces the former standaloneMercier.jl.
- Status: Stable, core DCON functionality implemented
-
ForcingTerms (
src/ForcingTerms/) - External field specification- Handles external magnetic field perturbations (coils, RMP, etc.)
- Supports ASCII and HDF5 forcing data formats
ForcingModedata structure specifies amplitude and phase for each (m,n) component- Status: Complete and functional
-
PerturbedEquilibrium (
src/PerturbedEquilibrium/) - GPEC-style plasma response- Computes plasma response to external forcing
- Calculates singular coupling metrics at rational surfaces
- Key files:
PerturbedEquilibrium.jl- Main entry pointPerturbedEquilibriumStructs.jl- Data structuresResponseMatrices.jl- Permeability matrix calculationFieldReconstruction.jl- Mode-space field reconstructionResponse.jl- Plasma response computationSingularCoupling.jl- Singular surface analysis including:- Delta prime (Δ') tearing stability parameter
- Resonant flux and currents at rational surfaces
- Island half-widths and Chirikov parameters
- Green's functions at interior flux surfaces
- Surface inductance for singular surfaces
Utils.jl- Helper functions
- Status: Active development on
perturbed_equilibriumbranch
Unified Configuration File: gpec.toml
All GPEC modules are configured via a single TOML file with the following sections:
[Equilibrium]- Equilibrium solver settings[Wall]- Wall geometry and vacuum region[ForceFreeStates]- Stability analysis parameters[PerturbedEquilibrium]- Perturbed equilibrium settings[ForcingTerms]- External field specification
Key parameters:
force_termination- Set totrueto exit after equilibrium/stability (skip perturbed equilibrium)output_file- Output filename (default:gpec.h5)
Example configuration files are provided in:
examples/Solovev_ideal_example/gpec.tomlexamples/DIIID-like_ideal_example/gpec.toml
Note: Legacy configuration files (equil.toml, vac.in) are deprecated.
The complete GPEC analysis pipeline:
-
Equilibrium Setup:
setup_equilibrium(config)reads configuration fromgpec.toml- Parses equilibrium data (EFIT, CHEASE, or analytical)
- Runs Grad-Shafranov solver (direct or inverse)
- Computes global parameters: q-profile, pressure, current density, β
- Creates bicubic splines for (ψ, θ, φ) → (R, Z, Φ) mapping
- Outputs:
PlasmaEquilibriumobject
-
Vacuum Response:
- Initialize plasma and wall surfaces from equilibrium
- Compute vacuum response matrices (wv, grri, grre)
- Calculate both interior and exterior Green's functions
- Pure Julia implementation
-
Stability Analysis (ForceFreeStates):
- Solve ideal MHD Euler-Lagrange equations via ODE integration
- Identify singular surfaces where q = m/n
- Compute Δ' at each singular surface
- Calculate potential and kinetic energies
- Check Mercier and ballooning stability criteria
- Outputs: Eigenmode structure ξ(ψ,θ)
-
Perturbed Equilibrium (GPEC-style):
- Load external forcing data (coil fields, RMP configuration)
- Compute plasma response using permeability matrices
- Reconstruct mode-space fields (ξ_modes, b_modes)
- Calculate singular coupling metrics at rational surfaces:
- Δ' (tearing stability parameter)
- Island half-widths
- Chirikov overlap parameter
- Resonant flux and currents
- Outputs:
PerturbedEquilibriumStatewith response fields and diagnostics
-
Output:
- All results saved to single HDF5 file (default:
gpec.h5) - HDF5 groups:
input/,info/,equil/,splines/,locstab/,integration/,singular/,vacuum/, and perturbed equilibrium data
- All results saved to single HDF5 file (default:
PlasmaEquilibrium- Main equilibrium container with bicubic splines (rzphi), 1D profiles (sq), and global parametersEquilibriumConfig- Configuration loaded from TOML files
VacuumInput- Input parameters for vacuum calculationsWallShapeSettings- Wall geometry configuration
SingType- Singular surface data including:- Rational surface location (ψ, q = m/n)
- Δ' (tearing stability parameter)
- Eigenmode structure at singular surface
- NEW: Green's functions (grri, grre) at interior singular surfaces
- Surface inductance
PerturbedEquilibriumControl- User-facing TOML configuration parametersPerturbedEquilibriumInternal- Internal state with mode arraysPerturbedEquilibriumState- Results including:- Response fields (ξ_modes, b_modes) in mode space
- Singular coupling matrices [msing × numpert_total]
- Island diagnostics (half-widths, Chirikov parameters)
ForcingMode- External forcing specification (m, n, amplitude, phase)
GeneralizedPerturbedEquilibrium
├── Splines (foundation)
├── Utilities (shared tools)
│ └── FourierTransforms
├── Equilibrium (uses Splines)
├── Vacuum (uses Splines, Equilibrium, Utilities)
├── ForcingTerms (data I/O)
├── ForceFreeStates (uses Equilibrium, Vacuum, Splines)
└── PerturbedEquilibrium (uses ForceFreeStates, Vacuum, ForcingTerms, Utilities)
This project uses GitFlow (http://nvie.com/posts/a-successful-git-branching-model):
- Two permanent branches:
mainanddevelop mainis updated only at release-ready stages via pull request fromdevelopdevelopis the integration branch — all feature branches merge here
IMPORTANT: All development must be done on feature branches. No commits should be made directly to develop or main. Always create a branch from develop, do all work there, and open a pull request back into develop.
Branches use a typed prefix and a lowercase hyphen-separated description:
| Prefix | Purpose | Branches from | Merges into |
|---|---|---|---|
feature/ |
New functionality | develop |
develop |
bugfix/ |
Non-critical bug fixes | develop |
develop |
hotfix/ |
Critical production fix | main |
main + develop |
performance/ |
Performance improvements | develop |
develop |
refactor/ |
Refactoring without behavior change | develop |
develop |
docs/ |
Documentation only | develop |
develop |
test/ |
Test additions/improvements | develop |
develop |
experiment/ |
Exploratory work, may not merge | develop |
— |
Examples: bugfix/sing-lim-bounds-error, feature/kinetic-damping, performance/green-function-prefactor
Author-named branches (e.g. jmh/, nlogan/) are not used — git history already records authorship on every commit.
Hotfixes address critical bugs in production (main) that cannot wait for the next release cycle:
- Branch
hotfix/descriptionfrom the current taggedmaincommit - Fix the bug with one or more commits
- Merge into
mainvia pull request; tag the merge commit with a new patch version (e.g.v0.1.1) - Merge the same branch into
developso the fix is not lost in the next release
This project uses semantic versioning: v{major}.{minor}.{patch}
- major: breaking API or file-format changes
- minor: new features, backward-compatible
- patch: bug fixes (typically via hotfix branches)
Tags are applied to merge commits on main.
Current Development:
- Active branch:
perturbed_equilibrium- Major feature implementing GPEC-style perturbed equilibrium calculations - Previous work:
vacuum_juliabranch (merged) - Pure Julia vacuum implementation
CODE - TAG - Detailed message
Where:
- CODE: Module name (EQUIL, VAC, VACUUM, ForceFreeStates, PERTURBED EQUILIBRIUM, etc.)
- TAG: Type descriptor (WIP, MINOR, IMPROVEMENT, BUG FIX, NEW FEATURE, REFACTOR, CLEANUP, etc.)
Examples:
PERTURBED EQUILIBRIUM - NEW FEATURE - Implement singular coupling diagnosticsVAC - IMPROVEMENT - Add dual Green's function computationEQUIL - BUG FIX - Fixed separatrix finding for high kappaForceFreeStates - REFACTOR - Unified singular surface data structure
This format is used for compiling release notes, so tags should be human-readable and descriptive.
This repo ships a small team of specialized Claude Code subagents in .claude/agents/. They are stateless reviewers: each runs in its own context, is handed a specific deliverable, and returns its findings to the main session — they do not talk to each other. The main session is the integrator. You drive them; you do not delegate the whole task and walk away.
Invoke an agent by name for the matching job — e.g. "review this with the fortran-physics-reviewer" or "run the regression-guardian against develop". Do not "consult all the agents" reflexively: that burns the token budget and produces noise. Pick the agent whose job matches the change.
| Agent | Model | Role — invoke when… |
|---|---|---|
fortran-physics-reviewer |
opus | A physics kernel, numerical method, derivative, integral, or quadrature was written/changed. Audits fidelity to the reference papers and the Fortran GPEC source. Carries project memory (correspondence map + per-domain audit checklists for KineticForces and InnerLayer), so its reviews compound — let it record findings. |
clean-code-reviewer |
opus | A logical chunk of code is ready and you want readability/maintainability review for a fusion physicist audience (naming, magic numbers, docstrings, structure). |
julia-performance-optimizer |
opus | A specific function/hotspot is slow or perf-sensitive (type stability, allocations, hot-loop work in ODE/kinetic/resistive-layer paths). |
fast-interpolations-optimizer |
opus | Code uses FastInterpolations.jl and you want allocation-free / optimal-search-type review. |
regression-guardian |
sonnet | Before merging any substantive change (mandatory per the Regression Harness policy above), or when you need to know whether a tracked numerical quantity moved. Runs the harness, reports the table, flags non-OK rows, proposes new cases. |
Run sequentially, reading each agent's findings before launching the next:
fortran-physics-reviewer— physics fidelity first; a fast-but-wrong result is worthless.clean-code-reviewer— readability and maintainability.julia-performance-optimizerand/orfast-interpolations-optimizer— only if the change is performance-relevant.regression-guardian— always, last, before merge. Confirms the numbers didn't silently move.
Not every change needs all four. A docs-only change needs none; a pure perf refactor still needs the physics reviewer (to confirm no numerical change) and the regression-guardian.
Every consultation is bounded — see Subagent Consultations under Important Notes below (≤30 tool uses, ≤10 min, one concrete deliverable, never re-launch a runaway). The agent bodies now self-enforce this, but state the budget in your prompt anyway and always hand the agent the specific file paths to act on.
- Julia version: 1.11 is the target version
- Never remove packages from Project.toml - If a package fails to load or resolve, run
Pkg.add(...)orPkg.instantiate()to fix the local environment. Do NOT remove the package fromProject.toml. The developer works across multiple branches and machines, so environment drift is expected — the right fix is always to update the environment to satisfy the toml, not to trim the toml to match the current environment state. - Indexing: The codebase uses 0-based indexing in many places to match Fortran conventions, then converts to 1-based Julia indexing
- No step numbering in code comments - Avoid annotations like "Step 1: do this" followed by "Step 2: do that". These get out of sync as code changes. Just describe the action without numbering.
- Documentation coverage - When adding a new module or submodule with public docstrings, add a corresponding
@autodocsblock indocs/src/. Documenter CI will fail with amissing_docserror if any exported docstring is not covered. The analysis submodule docs live indocs/src/analysis.md. - Docstrings are rendered as Markdown - Documenter parses docstrings as CommonMark, so
[text](...)patterns become hyperlinks and will fail CI withinvalid local link/imageif the target doesn't exist. Common pitfall: unit annotations like[degrees] (or [m] if ...)parse as[degrees](or [m] if ...)— a broken link. Use plain words (in degrees) or backticks (`[m]`) for unit labels inside docstrings. Same rule for bracketed array-shape hints ([ncoil]) followed by parentheses. When in doubt, preview withjulia --project=docs docs/make.jlbefore pushing. - Keep code comments concise - A comment should be one line where possible. Do not write multi-line block comments explaining the current session's investigation, what was tried, what was wrong before, or why a specific file/path behaves differently. State what the code does and why at a general level. Example of too much detail: a 6-line block explaining that efit_by_inversion uses psilow>0 while CHEASE starts at 0, that the old code was removed, and that spline spikes result. Preferred:
# Replicate Fortran inverse.f: overwrite deta at axis (r²=0) by extrapolating from innermost surfaces. - No PR/issue references in source - Do not cite specific GitHub PR or issue numbers (e.g.
#171,#202) in source or test comments/docstrings. During dynamic development these references quickly go stale and pollute the code. Just concisely state the objective or what the code does; the git history and PR threads track the provenance. - Document struct fields in the docstring, not inline - When adding a field to a struct, put its description in the struct's
## Fieldsdocstring rather than (or in addition to) a trailing inline comment, and document any non-obvious contract (e.g. which keys aDict/ingest carries per variant). Do not annotate outer constructors with positional-argument counts ("passes 11 positional args") — those rot when a field is added; describe the intent instead.
- Reuse native ops and existing utilities before writing new ones. FastInterpolations splines integrate and differentiate natively (
integrate,cumulative_integrate,deriv1); the Equilibrium module already has flux-surface integration/average patterns. Do not reimplement spline integration, quadrature, or differentiation — grep for the existing idiom first. - Size the change to the problem. A small numerical correction (e.g. a ~1% fix) should be a handful of lines, not new general-purpose machinery. Resist faithfully porting Fortran scaffolding (custom integrators, power-law spline bases) when a native call plus a one-line correction gives the same numbers — verify equivalence instead of assuming the elaborate version is needed.
- Don't commit throwaway artifacts for minor fixes. No in-repo benchmark scripts/outputs or agent-memory churn for a small change — these accumulate and outsize
src. Verify with a scratch script (e.g. under/tmp) and the regression harness; the regression harness is the durable record of numerical behavior.
- Default output:
gpec.h5(previouslyeuler.h5in older versions) - Legacy diagnostic files: When modifying equilibrium code, remember that older versions output
gsec.h5,gse.h5,gsei.h5- these are now consolidated intogpec.h5
- Perturbed equilibrium module: Active development of GPEC-style singular coupling analysis
- Configuration: All settings now in unified
gpec.tomlfile
- Spectrum plots (any plot with discrete mode numbers m or n on the x-axis) must use
seriestype=:stepprewith astep_serieshelper that pads zeros on both ends. Pattern frombenchmarks/benchmark_coil_ForcingTerms_against_fortran.jl:function step_series(m_vals, amps) m_ext = [m_vals[1] - 1; m_vals; m_vals[end] + 1] amp_ext = [0.0; amps; 0.0] return m_ext, amp_ext end # Usage: m_ext, a_ext = step_series(m_vals, amplitudes) plot!(p, m_ext, a_ext; seriestype=:steppre, lw=2, label="...")
When delegating to specialized agents (julia-performance-optimizer, fast-interpolations-optimizer, fortran-physics-reviewer, clean-code-reviewer, etc.), every prompt must include an explicit budget because runaway agents silently consume the user's daily token quota. A single consultation that explores instead of editing has been measured at 167 tool calls / 55 minutes / no return — that is a session-killer. Defaults:
- Hard cap: ≤ 30 tool uses and ≤ 10 minutes wall time per consultation. State both numbers in the prompt verbatim ("Budget: ≤30 tool uses, ≤10 min").
- Single concrete deliverable. One file, one function, or one named hotspot list. Not "audit the module."
- No exploration phase. The prompt must hand the agent the file paths and line numbers; the agent's job is to edit, not to map the codebase.
- Require an interim status if the work might exceed budget. Tell the agent: "If you cannot finish within budget, stop and report what was changed and what remains."
- Prefer two short focused agents over one open-ended one. If an investigation needs both performance and interpolation review, run them sequentially with separate ≤30-tool budgets — don't chain them in one long prompt.
- Never re-launch a runaway agent. If an agent hits the API rate limit before returning, do not retry; report the partial state to the user and switch to hand-implementation.
These rules apply to every Agent tool invocation, not just performance work.
Pre-commit hooks enforce formatting via JuliaFormatter (v1.0.62) and general file hygiene. All code you write or modify must already conform to these standards before committing, so the hooks have nothing to fix. Failing to do this creates noisy diffs in PRs where formatting changes leak into unrelated files.
The project's .JuliaFormatter.toml settings:
- Line width: 180 characters max (
margin = 180) forloops: always usein(not=or∈)- Keyword arguments: no spaces around
=in kwargs (f(x; a=1)notf(x; a = 1)) - Keyword separator: use semicolons to separate kwargs (
f(x; a=1, b=2)) - No trailing commas in argument lists
- Docstrings: formatted according to JuliaFormatter rules
- No extra blank line removal:
remove_extra_newlines = false - Join short lines:
join_lines_based_on_source = true— don't arbitrarily split lines that fit within the margin
Additional file hygiene (enforced by pre-commit hooks):
- No trailing whitespace on any line
- Files must end with exactly one newline
- LF line endings only (no CRLF)
Config-style TOML files (examples/*/gpec.toml, examples/*/sol.toml, the
test/test_data/* fixtures, and regression-harness/cases/*.toml) follow one shared
annotation style so they stay consistent and self-documenting for users who copy and
modify them. Do not invent a new convention — match what the existing example files do.
- File header (2–10 lines). Begin each config-style TOML with a plain
#comment block stating the example's purpose/context and calling out key settings (wall choice, forcing, n-range, ideal vs kinetic). No ASCII-art separators or decorative dividers. - Inline annotation on every variable line. Every
key = valuegets a trailing# description. Source the wording from the matching config struct's docstring (EquilibriumConfig,WallShapeSettings,ForceFreeStatesControl,ForcingTermsControl,PerturbedEquilibriumControl,SolovevConfig,TJAnalyticConfig,KineticForcesControl) and keep it to one terse line. Use the same description for the same variable across all files —examples/DIIID-like_ideal_example/gpec.tomlis the canonical reference for the common sections. - Section comments only when informative. No comment is required above a section. Keep a
block comment only when it carries real information (e.g. the Solovev
[Wall]note on why a conformal wall is needed). Never add decorative section dividers. - No Fortran references — annotations must be self-contained and Julia-centric. The Julia
code is the production workhorse; a new user must not need to know the legacy Fortran GPEC
code to read an example. Headers explain the scenario and its unique aspect; inline comments
explain the variable. Do not cite Fortran namelist files (
dcon.in/equil.in/pentrc.in), Fortran flag names (kin_flag,sas_flag,electron_flag, …), or legacy code names (DCON/STRIDE/PENTRC) as things the reader must know. Non-Fortran external-model citations (e.g. the analytic TJ model behindtj_analytic) are acceptable provenance. (This applies to the user-facingexamples/*andtest/test_data/*TOMLs;regression-harness/cases/*may retain algorithm names as developer metadata.) - Only active, meaningful variables in examples. Do not set deprecated or "not yet
implemented" variables just to mirror defaults — they add clutter and imply false relevance
(e.g. the
truncate_at_dW_peakedge-peak truncation,thmax0). Omit them so examples show only knobs that do something on that run. Project.toml-family files are exempt.Project.toml,docs/Project.toml,regression-harness/Project.toml, and.JuliaFormatter.tomlare machine-managed; do not inline-annotate dependency UUIDs or[compat]entries.
- Pure Julia implementations are available for all major components and offer comparable or better performance than Fortran
- Benchmarks available in
benchmark/directory for Fourier transforms and vacuum calculations - Pre-commit hooks are configured for notebook cleaning and Julia formatting (see
docs/src/set_up.mdfor developer setup)
- Always print the full absolute path of any figure or plot file you save, so the user can open it directly without searching the filesystem.
- Always check that axis labels are not clipped. In Plots.jl there is no
tight_layout()equivalent; use explicit margins instead:left_margin=12Plots.mm,bottom_margin=4Plots.mm, etc. When in doubt, add a generousleft_marginto prevent y-axis label cutoff.
- When resolving git conflicts, do not simply accept one side.
- Analyze what each side changed and WHY before producing a resolution.
- Produce a merged version incorporating both sets of changes.
- If both sides renamed the same symbol differently, prefer the current (ours) branch convention.
- When a rename on one side conflicts with a logic change on the other, apply the logic change using the renamed symbol.
- If a conflict involves changes to numerical parameters (tolerances, boundary conditions, grid sizes), flag for human review rather than guessing.
- Flag any conflicts where the combination is ambiguous for human review.