GeneralizedGradients.jl API Reference

Complete reference for every exported function and type, generated automatically from the package docstrings.

For installation, tutorials, and background theory, see the main documentation.

Index

Public API

GeneralizedGradients.FieldGridTable — Type
mutable struct FieldGridTable{T}

Holds an electric and/or magnetic field sampled on a 3D grid.

magnetic and electric are 3D OffsetArrays whose elements are field 3-vectors: magnetic[ix,iy,iz] == [Bx, By, Bz] (and likewise [Ex, Ey, Ez]). The grid indices (ix, iy, iz) need not start at 0 or 1; a grid point is at position r0 + dr .* (ix, iy, iz) relative to the anchor.

Fields:

  • magnetic — magnetic field 3-vectors [Bx, By, Bz] [T].
  • electric — electric field 3-vectors [Ex, Ey, Ez] [V/m].
  • r0 — grid origin offset (x0, y0, z0) [m].
  • dr — grid spacing (dx, dy, dz) [m].
  • g_ref — curvilinear-coordinate bending strength 1/bending_radius, in 1/m (0 for a straight reference curve).
  • scale — overall field scale factor.
  • RF_frequency — RF frequency in Hz (0 for a static field).
  • RF_phase — RF phase [rad].
  • anchor_pt — grid anchor point, a GridAnchorPt.T (Beginning, Center, or End).
  • geometry — grid geometry, a GridGeometry.T (XYZ).

FieldGridTable() builds an empty table with T = Float64; read one from a file with read_field_grid_hdf5.

source
GeneralizedGradients.GGCoefs — Type
mutable struct GGCoefs

Holds the result of a gg_fit fit: the fitted generalized-gradient (GG) coefficient functions sampled at the base planes plus per-plane diagnostics. Returned by gg_fit and consumed by gg_fit_show_results and write_gg_fit.

Fields:

  • z_base — z position of each base plane [m].
  • params — list of fitted unknowns as (type, n, m) tuples, where type is one of :a, :b, :bs (bs uses n = 0).
  • a — fitted a(n,m) functions, Dict (n,m) => values_over_planes.
  • b — fitted b(n,m) functions, Dict (n,m) => values_over_planes.
  • bs — fitted bs(m) functions, Dict m => values_over_planes.
  • rms_plane — weighted RMS fit residual at each base plane.
  • m_max — highest derivative order resolved (2 * n_planes_add).
  • g_ref — reference-frame bending strength = 1/bending_radius [1/m] (0 for a straight reference frame).
  • origin — (x, y) line about which the GG coefficients are computed.
  • dz_grid — spacing between base planes [m].
  • eval_plan — internal cache: the compiled GGEvalPlan used by field_and_potential_evaluate_at, built lazily on first evaluation. Not part of the fit data (not serialized); assumes the other fields are not mutated afterward.
source
GeneralizedGradients.field_and_potential_evaluate — Method
field_and_potential_evaluate(fit, ip::Integer, x::Real, y::Real) -> (B, A, dA)

Main entry point. Evaluate the field, vector potential and the Jacobian of A at grid plane ip and transverse position (x, y).

  • fit — the GGCoefs struct returned by read_gg_fit.
  • ip — 1-based plane index into fit.z_base.
  • x, y — absolute transverse coordinates. fit.origin is subtracted internally to obtain the position relative to the GG expansion axis (the coordinate the expansion is written in). Pass an origin of (0,0) — or use the default — for axis-relative input.

Returns (B, A, dA) where

B  = [Bx, By, Bs]
A  = [Ax, Ay, As]
dA = 3x3 matrix, dA[i,j] = ∂A_i/∂u_j  with  (A_1,A_2,A_3) = (Ax,Ay,As)
     and (u_1,u_2,u_3) = (x,y,s).
source
GeneralizedGradients.field_and_potential_evaluate_at — Method
field_and_potential_evaluate_at(fit::GGCoefs, x::Real, y::Real, s::Real) -> (B, A, dA)

Evaluate at an arbitrary (x, y, s) point.

The GG coefficients are stored only at the grid planes fit.z_base, but the fit gives, at each plane, the whole derivative tower of every GG function: a(n,0..N), b(n,0..N), bs(0..N) with a(n,m) = dᵐaₙ/dsᵐ and N the maximum order. So for an s between two planes z_L, z_R we have, for each function f, the value and its first N s-derivatives at both ends — 2(N+1) data — which fix a unique two-point Hermite polynomial H(s) of degree 2N+1. Each interpolated derivative is taken from the SAME polynomial, a(n,m)(s) = H_aₙ⁽ᵐ⁾(s), so the tower stays self-consistent: the interpolated a(n,1) is exactly d/ds of the interpolated a(n,0), etc.

This is more accurate than independent per-order interpolation (error O(h^{2N+2}) for the base coefficient, using only the two straddling planes) and, because the orders are mutually consistent, the ∂A/∂s that field_and_potential_evaluate forms by bumping a(n,m) → a(n,m+1) equals the true s-derivative of the interpolated field. The curl identity B = ∇×A holds at s as before.

  • fit — the GGCoefs struct from read_gg_fit.
  • x, y — absolute transverse coordinates (fit.origin subtracted internally).
  • s — absolute longitudinal coordinate.

Returns (B, A, dA) with the same values as field_and_potential_evaluate, but as stack-allocated StaticArrays: B, A are SVector{3,Float64} and dA is an SMatrix{3,3,Float64} (so evaluation allocates only the internal scratch, not the returned data). They index like ordinary vectors/matrices (A[1], dA[1,3]).

Uses a type-stable evaluation plan compiled once per fit and cached by object identity (see lowlevel.jl); this is what makes it fast enough for tracking. The plan assumes fit is not mutated after its first evaluation — changing fit.a/fit.b/fit.bs/`fit.gref` afterward leaves the cached plan stale.

source
GeneralizedGradients.field_coefficients_at_plane — Method
field_coefficients_at_plane(fit, ip::Integer) -> (CBx, CBy, CBs)

Field-expansion coefficients at a grid plane.

  • fit — the GGCoefs struct from read_gg_fit.
  • ip — 1-based plane index into fit.z_base.

Returns (CBx, CBy, CBs); each is a matrix with CB[i+1, j+1] = CB_{c,i,j}, the coefficient of xⁱ yʲ in that field component at the plane.

source
GeneralizedGradients.field_coefficients_at_s — Method
field_coefficients_at_s(fit, s::Real) -> (CBx, CBy, CBs)

Field-expansion coefficients at an arbitrary s, via the same Hermite interpolation of the GG quantities used by field_and_potential_evaluate_at. Returns (CBx, CBy, CBs) where each CB is a matrix with CB[i+1, j+1] = CB_{c,i,j}, the coefficient of xⁱ yʲ in that field component at the plane.

source
GeneralizedGradients.field_evaluate_at — Method
field_evaluate_at(fit::GGCoefs, x::Real, y::Real, s::Real) -> B

Like field_and_potential_evaluate_at but returns only the magnetic field B = [Bx, By, Bs] as an SVector{3,Float64}, skipping the vector potential A and its Jacobian. B is identical to that of the full evaluator. See field_and_potential_evaluate_at for the (x, y, s) conventions.

source
GeneralizedGradients.gg_coefficients_at_plane — Method
gg_coefficients_at_plane(fit, ip::Integer) -> (a, b, bs)

Generalized-gradient coefficients at a grid plane.

  • fit — the GGCoefs struct from read_gg_fit.
  • ip — 1-based plane index into fit.z_base.

Returns the three GG-function dicts of scalar values at the plane: a and b keyed by (n,m) with a(n,m) = dᵐaₙ/dsᵐ, b(n,m) = dᵐbₙ/dsᵐ; and bs keyed by m with bs(m) = dᵐ⁺¹a_0/dsᵐ⁺¹ = dᵐb_s/dsᵐ.

source
GeneralizedGradients.gg_coefficients_at_s — Method
gg_coefficients_at_s(fit, s::Real) -> (a, b, bs)

Generalized-gradient coefficients at an arbitrary s, Hermite-interpolated from the straddling grid planes (the same interpolation used by field_and_potential_evaluate_at). Returns the three GG-function dicts of scalar values, as in gg_coefficients_at_plane.

source
GeneralizedGradients.gg_fit — Method
gg_fit(field::FieldGridTable, params::GGFitInputParams) -> GGCoefs

Fit a 3D magnetic field grid to generalized-gradient (GG) coefficients a_n(z), b_n(z), b_s(z) and their z-derivatives, plane by plane.

The returned GGCoefs holds the fitted coefficients and per-plane diagnostics. Use gg_fit_show_results to print a summary and write_gg_fit to save the result to an HDF5 file (readable by read_gg_fit).

See examples/run_gg_fit.jl for a complete, runnable example.

Arguments

  • field — a FieldGridTable. field.magnetic[ix,iy,iz] is the [Bx,By,Bz] 3-vector at the grid point, whose (x, y, z) position is field.r0 + field.dr .* (ix, iy, iz).
  • params — a GGFitInputParams holding the fit parameters (origin, n_planes_add, core_weight, outer_plane_weight, output_file).

How the fit works

The GG coefficients are computed at the equally spaced z-positions of the field-table planes. The fit is done plane by plane: the coefficients of a given plane (the "base plane") are computed independently of every other plane, and all coefficients of a base plane are solved for simultaneously by minimizing a merit function

Merit = Σ  weight · (field_from_table - field_from_GG_coefs)^2

The sum runs over all field points lying in a plane within n_planes_add of the base plane. For example, n_planes_add = 2 adds two planes on either side, so five planes are used in total. Near the ends of the table the count is reduced — a base plane at the very end of the table uses only three planes when n_planes_add = 2.

The field expansion (tables/gg_coef_table.jl) is linear in the GG functions and their s-derivatives:

B_c(x,y,z) = Σ_{(n,m)}  CS_c,b(n,m; x,y) · b(n,m)(z)
           + Σ_{(n,m)}  CS_c,a(n,m; x,y) · a(n,m)(z)
           + Σ_{m}      CS_c,bs(m; x,y)  · bs(m)(z)

for each field component c ∈ {Bx, By, Bs}, where

CS_c,f(n,m; x,y) = Σ (coeff · g_ref^k · x^p · y^q)

is the sum of the table entries c_f[(n,m)] = [(coeff,p,q,k), ...], and b(n,m) = dᵐb_n/dzᵐ, a(n,m) = dᵐa_n/dzᵐ, bs(m) = dᵐ⁺¹a_0/dzᵐ⁺¹.

The unknowns at a base plane z0 are the function values and their derivatives f(n,m)(z0), m = 0 … m_max. The field on a neighbouring plane at offset dz = z - z0 is obtained by Taylor-extrapolating each derivative:

f(n,m)(z0+dz) = Σ_{j≥m} dz^(j-m)/(j-m)! · f(n,j)(z0)

where f is either a, b, or bs. Substituting makes the model linear in the base-plane unknowns f(n,j)(z0):

design entry for unknown f(n,j) = Σ_{m=0}^{j} CS_c,f(n,m; x,y) · dz^(j-m)/(j-m)!

Each base plane is then solved by weighted linear least squares over all field points lying within n_planes_add planes of the base plane.

Adding extra planes smooths the computed values, but the approximation that the GG curve is well represented by the base-plane Taylor polynomial becomes less accurate as more planes are added. Past some limit, using more planes makes the fit less accurate.

Weighting

The weight of a field point at (x, y) and plane offset dz (relative to the base plane) is the product of a transverse and a longitudinal factor:

weight(x,y,dz) = w_core(x,y) · w_plane(dz)

The transverse factor is

w_core(x,y) = core_weight · rmax^2 / (rmax^2 + r^2 · (core_weight - 1))

where r^2 = x^2 + y^2 and rmax is the maximum r over all points. core_weight = 1 (the default) makes w_core constant; core_weight > 1 favors the core (low-r) points at the expense of points farther out. A better core fit is usually desired since beam particles spend most of their time near the core.

The longitudinal factor is

w_plane(dz) = 1 + (outer_plane_weight - 1) · |dz| / dz_max

where dz_max is the largest |dz| at the ends of the fit region. If n_planes_add = 0 (so dz_max = 0 and the expression is singular) w_plane is set to 1. outer_plane_weight = 1 (the default) makes w_plane constant; a value between 0 and 1 weights planes nearer the base plane more than the outer planes.

Fit input parameters (GGFitInputParams)

  • origin = [x0, y0] — (x, y) line about which the GG coefficients are computed. If field.g_ref is non-zero, origin must be [0, 0]. Default [0.0, 0.0].
  • n_planes_add — number of z-planes added to either side of the base plane used to resolve derivatives (m_max = 2*n_planes_add).
  • core_weight — merit-function weight for "core" (near-axis) points. Default 1 (uniform).
  • outer_plane_weight — merit-function weight for the outer z-planes. Default 1.
  • output_file — name of the output HDF5 file written by write_gg_fit. Default "gg_fit_results.h5".

Side note

In theory, the fitting does not require that the field table be a rectangular grid of equally spaced points. In fact, a set of randomly spaced field points would work. Also there is no fundamental requirement that the fit planes be evenly spaced. It is only for convenience that the gg_fit function require a regularly spaced field table and that the output is at evenly spaced planes.

source
GeneralizedGradients.gg_fit_show_results — Method
gg_fit_show_results(results::GGCoefs, field::FieldGridTable, params::GGFitInputParams)

Print a human-readable summary of a gg_fit results: the fit settings, the per-plane weighted RMS residuals, and the leading multipoles at the central plane as a quick sanity check.

source
GeneralizedGradients.potential_evaluate_at — Method
potential_evaluate_at(fit::GGCoefs, x::Real, y::Real, s::Real) -> (A, dA)

Like field_and_potential_evaluate_at but returns only the vector potential A and its Jacobian dA, skipping the magnetic field B.

For tracking, only A and dA are needed. The B field is the majority of the per-call work (its monomial expansion has more terms than A's), so skipping it is roughly 1.8x faster than the full evaluator while returning identical A, dA. A is an SVector{3,Float64} and dA an SMatrix{3,3,Float64}. See field_and_potential_evaluate_at for the (x, y, s) conventions.

source
GeneralizedGradients.read_field_grid_hdf5 — Method
read_field_grid_hdf5(path; index = 1) -> FieldGridTable

Read a Bmad/openPMD field_grid HDF5 file (as written by write_field_grid_hdf5, or by Bmad itself) into a FieldGridTable. The magnetic/electric OffsetArrays are indexed (ix_lo:ix_hi, …) with each element a [Bx,By,Bz] 3-vector; the grid index ranges come from gridLowerBound/gridSize (the grid is not assumed to start at zero). r0 is gridOriginOffset (so a point (ix,iy,iz) is at dr .* (ix,iy,iz) + r0 relative to the anchor). An absent field type is left at the struct default. index selects which grid under /ExternalFieldMesh/ to read (default 1).

source
GeneralizedGradients.read_gg_fit — Method
read_gg_fit(path::AbstractString) -> (fit::GGCoefs, meta::NamedTuple)

Load a gg_fit result HDF5 file (written by write_gg_fit). Returns a two-tuple whose first component is a GGCoefs struct holding the GG coefficient dictionaries a, b, bs (and z_base, m_max, rms_plane, g_ref, origin, dz_grid), and whose second component is a NamedTuple of the associated fit-control metadata (n_planes_add, core_weight, outer_plane_weight). The params field of the returned struct is empty (the unknown list is not stored in the file).

fit, meta = read_gg_fit(path)
fit.a            # Dict{(n,m) => values_over_planes}
fit.g_ref        # reference curvature
source
GeneralizedGradients.write_bmad_field_grid_element — Method
write_bmad_field_grid_element(field::Union{AbstractString,FieldGridTable};
                           ele_name::AbstractString = "fieldmap_ele",
                           output_base::AbstractString = ele_name,
                           field_scale::Real = 1.0,
                           hdf5::Bool = true) -> (ele_file, grid_file)

Create a file with a single Bmad lattice element that uses the field grid table for Runge-Kutta tracking. Also write the field grid to a file in HDF5 or ASCII format.

Two files are written: <output_base>.bmad (the lattice element) and the field grid (<output_base>_grid.h5 or _grid.bmad). The reference-curve bending strength is taken from the field grid's g_ref (= 1/bend_radius): if non-zero the element is written as an sbend, otherwise an em_field. The grid is anchored at the entrance of the element (ele_anchor_pt = beginning) with length L = dz*(nz-1); the field-grid r0 keeps the transverse offset (x0, y0) of the input grid and shifts z so the first grid plane sits at the element entrance.

Input:

  • field - Field table or name of an HDF5 field table file.
  • ele_name — name of the Bmad lattice element. Default "fieldmap_ele".
  • output_base — base path for the two output files. Default ele_name.
  • field_scale — overall field scale factor written to the field grid. Default 1.
  • hdf5 — if true (the default), write the field grid as an openPMD HDF5 file (<output_base>_grid.h5) instead of a plain-text block.

Output

  • (ele_file, grid_file) - Tuple of file names.
source
GeneralizedGradients.write_bmad_gg_fit — Method
write_bmad_gg_fit(fit::GGCoefs; ele_name, output_base, cutoff) -> lattice_file_path
write_bmad_gg_fit(input::AbstractString; output_base, cutoff) -> lattice_file_path

Convert generalized-gradient (GG) coefficients produced by gg_fit into Bmad gen_grad_map format, producing a Bmad lattice element with the GG map attached. Returns the path of the lattice-element file.

The GG fit is supplied either as a loaded GGCoefs struct (fit, as returned by read_gg_fit) or as the path to a ggfit HDF5 file (output of `writeggfit), which is read withreadgg_fit`.

Usage

using GeneralizedGradients
write_bmad_gg_fit("gg_fit_result.h5")

From the shell (see programs/run_write_bmad_gg_fit.jl):

julia programs/run_write_bmad_gg_fit.jl <gg_fit_result.h5> [output_base] [cutoff]

Keyword arguments:

  • ele_name — name of the Bmad lattice element. Default "gen_grad_ele" (or, for a file input, the output_base basename).
  • output_base — base name for the two output files: <output_base>.bmad (the lattice element) and <output_base>_gg.bmad (the attached gen_grad_map). Defaults to the input file name without extension, or ele_name for an in-memory fit.
  • cutoff — relative magnitude cutoff for pruning negligible multipole curves. A curve is dropped if its peak |GG| is below cutoff * (largest peak |GG| of any curve). Default 0 (keep every non-zero curve).

The reference-coordinates bending "strength" 1/bend_radius [1/m] is taken from fit.g_ref; non-zero => the element is an sbend with curved_ref_frame = T, otherwise an em_field.

Background: the two GG conventions

This project (Van der Schueren / Sagan) characterizes the field by midplane- derivative generalized gradients a_n(s), b_n(s), b_s(s):

B_x(x,0,s) = Σ_{n≥1} a_n(s) x^{n-1}/(n-1)!     (skew / "cos" family)
B_y(x,0,s) = Σ_{n≥1} b_n(s) x^{n-1}/(n-1)!     (normal / "sin" family)
B_s(0,0,s) = b_s(s)                            (solenoidal, m = 0)

Bmad's gen_grad_map (Venturini-Dragt) instead uses azimuthal-harmonic gradients C_{m,α}(z), α ∈ {sin, cos}, where the field is (Sagan, IPAC23 Eq. 4)

B_ρ = Σ_{m≥1,n} f(m,n)(2n+m) ρ^{2n+m-1}[C^{[2n]}_{m,s} sin mθ + C^{[2n]}_{m,c} cos mθ]
      + Σ_{n≥1} f(0,n)(2n) ρ^{2n-1} C^{[2n]}_{0,c}
B_θ = Σ_{m≥1,n} f(m,n) m ρ^{2n+m-1}[C^{[2n]}_{m,s} cos mθ - C^{[2n]}_{m,c} sin mθ]
B_z = Σ_{m≥0,n} f(m,n) ρ^{2n+m}[C^{[2n+1]}_{m,s} sin mθ + C^{[2n+1]}_{m,c} cos mθ]

with f(m,n) = (-1)^n m!/(4^n n!(n+m)!), sin = normal, cos = skew.

Equating the two on the midplane gives the exact relations used here. For each azimuthal m and derivative order j (with k ≡ m):

C^{[j]}_{m,s} = (1/m!)[ b^{[j]}_m - (m-1)! Σ_{n≥1, m-2n≥1} Wn(m,n) C^{[j+2n]}_{m-2n,s} ]
C^{[j]}_{m,c} = (1/m!)[ a^{[j]}_m - (m-1)! Σ_{n≥1, m-2n≥1} Wc(m,n) C^{[j+2n]}_{m-2n,c}
                                 - (m even) (m-1)! Us(m) b_s^{[m+j-1]} ]
C^{[j]}_{0,c} = b_s^{[j-1]}                                            (j ≥ 1)

Wn(m,n) = (-1)^n (m-2n)!(m-2n)/(4^n n!(m-n)!)     (normal radial mixing)
Wc(m,n) = (-1)^n (m-2n)! m   /(4^n n!(m-n)!)       (skew radial mixing)
Us(m)   = (-1)^{m/2} m /(4^{m/2} ((m/2)!)^2)        (skew↔solenoid coupling)

where x^{[j]} ≡ dʲx/dsʲ is supplied directly by the fit (a[(n,j)], b[(n,j)], bs[j]). These recursions are solved in order of increasing m, reusing the lower-m towers. Truncation at the fit's maximum derivative order m_max bounds the radial-correction sums exactly as the fit itself is bounded, so the resulting gen_grad_map reproduces the project field to machine precision.

Output

A Bmad gen_grad_map (field_type = magnetic) attached to a lattice element. As with grid fields, the map is anchored at the entrance of the element (ele_anchor_pt = beginning), z-positions run 0, dz, 2dz, … and the element length is L = (n_planes - 1) * dz. The transverse anchor r0 is the GG expansion axis (origin). For a curved reference (g_ref ≠ 0) the element is an sbend with g = g_ref and curved_ref_frame = T; otherwise it is an em_field.

source
GeneralizedGradients.write_field_grid — Method
write_field_grid(output_file::AbstractString, fg::FieldGridTable)

Write a FieldGridTable. If output_file ends in .h5/.hdf5 it is written as a Bmad openPMD field_grid HDF5 file (write_field_grid_hdf5, readable by Bmad); otherwise it is written as a Julia source file (like ags-snakes/wsnk_fieldmap.jl) that defines fg when included.

source
GeneralizedGradients.write_field_grid_hdf5 — Method
write_field_grid_hdf5(hdf5_output_file::AbstractString, fg::FieldGridTable)

Write a FieldGridTable as an openPMD HDF5 field_grid file matching Bmad's hdf5_write_grid_field with geometry = xyz.

Input

  • hdf5_output_file – Output file name.
  • fg – Field grid table.
source
GeneralizedGradients.write_gg_fit — Method
write_gg_fit(results::GGCoefs, field::FieldGridTable, params::GGFitInputParams) -> output_file_path

Write a gg_fit results to an HDF5 file (readable by read_gg_fit).

Stores the fitted GG coefficients plus enough metadata to reproduce and interpret the fit later. The (large) input field table is NOT stored. The file is written to params.output_file and its path is returned.

HDF5 schema

root datasets   : z_base, rms_plane, origin            (Float64[])
root attributes : g_ref, dz_grid (Float64); m_max, n_planes_add (Int);
                  core_weight, outer_plane_weight (Float64)
groups a, b     : n (Int[]), m (Int[]), values (Float64[nkeys, nplanes])
                  -- reconstruct Dict{(n,m) => values[i,:]}
group  bs       : m (Int[]), values (Float64[nkeys, nplanes])
                  -- reconstruct Dict{m => values[i,:]}
source

Internal

These functions are not exported but are documented for reference.

GeneralizedGradients.GGEvalPlan — Type
GGEvalPlan

Compiled, type-stable evaluation plan built once per fit (see low_level.jl). Holds the interpolation towers and the per-component monomial term lists comps (order Bx By Bs Ax Ay As dAx dAy dAs), together with the sizing constants used to allocate per-call scratch (ngvals, maxdeg, pmax, qmax).

source
GeneralizedGradients._CompTerms — Type
_CompTerms

One output component's monomial terms. Evaluating the component accumulates value += Σ w[t] * gvals[slot[t]] * x^p[t] * y^q[t] over all terms t.

source
GeneralizedGradients._Tower — Type
_Tower

One GG derivative tower (a fixed multipole n, or the single bs tower). poly[d+1, pair] is the coefficient of u^d (with u = s - zref[pair]) of the interpolant on plane-pair pair; interpolating gives H⁽ᵐ⁾(s) for the tower's orders m = 0..N, scattered into gvals at slots[m+1]. Non-contiguous orders (m > N) are taken from the nearest (left) plane via extra_planevals.

source
GeneralizedGradients._accum — Method
_accum(tdict, valfun, g_ref) -> K

Coefficient-array builder. K[p+1,q+1] = coefficient of xᵖ yᵠ. valfun(key) returns the GG function value multiplying that table entry.

source
GeneralizedGradients._build_comp — Method
_build_comp(Ta, Tb, Tbs, bump, g_ref, slot_a, slot_b, slot_bs) -> _CompTerms

Flatten one output component's (a, b, bs) monomial tables into a flat term list, folding g_ref^k into each weight and resolving every (n,m)/m key to a gvals slot. bump shifts the GG derivative order by one (used for ∂A/∂s). Terms whose GG value is structurally zero (missing key) are dropped.

source
GeneralizedGradients._build_eval_plan — Method
_build_eval_plan(fit::GGCoefs) -> GGEvalPlan

Compile fit into a GGEvalPlan: assign a dense gvals slot to every GG value, build the interpolation towers, and flatten the nine output components' monomial tables into term lists. Called once per fit and cached by _get_eval_plan.

source
GeneralizedGradients._build_towers_nm! — Method
_build_towers_nm!(towers, z, d, slotmap, next) -> next

Assign gvals slots for the keys of an (n,m)-keyed dict d (a or b), build one _Tower per multipole n, and append them to towers. Returns the next free slot index.

source
GeneralizedGradients._coefsum — Method
_coefsum(terms, x::Float64, y::Float64, g_ref)

CB coefficient sum: Σ coeff·g_ref^k·x^p·y^q over the table entries for one (component, function) — one entry of the CB grids built in gg_fit.

source
GeneralizedGradients._comp_array — Method
_comp_array(Ta, Tb, Tbs, aval, bval, bsval, g_ref) -> K

Combined coefficient array of a component: sum of its a, b and bs parts. Ta/Tb are keyed by (n,m) and Tbs by m.

source
GeneralizedGradients._comp_value — Method
_comp_value(ct, gvals, xp, yq) -> val

Evaluate a component's value Σ w * gvals[slot] * x^p * y^q, where xp[i+1] = x^i and yq[j+1] = y^j are precomputed power tables.

source
GeneralizedGradients._component_dataset — Method
_component_dataset(field, c)

Lay component c of a (ix, iy, iz) OffsetArray of 3-vectors out as a 1-based (nx, ny, nz) complex array. HDF5.jl reverses dims on write, so the dataset lands on disk exactly like Bmad's own Fortran writer (H5Screate_simple_f with Fortran dims [nx,ny,nz]): Bmad's reader gets data_dim = (nx,ny,nz) and, with data_order "F", reads the column-major buffer back into pt[ix,iy,iz] correctly.

source
GeneralizedGradients._eval_scratch — Method
_eval_scratch(plan, x, y, s) -> (gvals, xp, yq)

Prepare the per-call scratch for evaluating plan at (x, y, s): interpolate every GG tower onto s (gvals) and build the x/y power tables (xp[i+1] = x^i, yq[j+1] = y^j, with fit.origin already subtracted). All three returned arrays are views into a single backing allocation, so a call allocates once. Shared by field_and_potential_evaluate_at and potential_evaluate_at.

source
GeneralizedGradients._field_CB — Method
_field_CB(fit, ip::Integer) -> (CBx, CBy, CBs)

Field-expansion coefficients B_c(x,y,s) = Σ_{i,j} CB_{c,i,j}(s) xⁱ yʲ. Returns full _NMAX×_NMAX arrays summed over the a, b, bs parts.

source
GeneralizedGradients._fill_gvals! — Method
_fill_gvals!(gvals, upow, plan, s) -> gvals

Interpolate every tower onto s, scattering the results into the dense value vector gvals. upow is a caller-provided scratch buffer of length plan.maxdeg + 1 for the powers of u = s - zref.

source
GeneralizedGradients._get_eval_plan — Method
_get_eval_plan(fit::GGCoefs) -> GGEvalPlan

Return fit's compiled GGEvalPlan, building it and storing it in fit.eval_plan on first use. Assumes fit is not mutated after the first evaluation (a stale plan is not detected).

source
GeneralizedGradients._gg_num — Method
_gg_num(x::Real) -> String

Lossless, compact Float64 text: repr emits the shortest string that parses back to the identical Float64 (Bmad's Fortran reader accepts the e-notation). Without this, cancellation in B_s (which is a small difference of larger terms) magnifies the rounding of a fixed-precision format.

source
GeneralizedGradients._hermite_derivs — Method
_hermite_derivs(zL, zR, fL, fR, sq) -> Vector

Two-point Hermite tower: fL[j+1] = f⁽ʲ⁾(zL), fR[j+1] = f⁽ʲ⁾(zR), j = 0..N. Returns [H⁽ᵐ⁾(sq) for m=0..N] where H is the degree-(2N+1) Hermite interpolant. Built via confluent Newton divided differences in the local coordinate u = s - zL (nodes: 0 with multiplicity N+1, hstep with multiplicity N+1).

source
GeneralizedGradients._hermite_poly — Method
_hermite_poly(zL, zR, fL, fR) -> Vector{Float64}

Monomial coefficients (in u = s - zL) of the degree-(2N+1) two-point Hermite interpolant with fL[j+1] = f⁽ʲ⁾(zL), fR[j+1] = f⁽ʲ⁾(zR), j = 0..N. Same confluent-Newton construction as _hermite_derivs, but returns the polynomial rather than evaluating it.

source
GeneralizedGradients._interp_gg_fit — Method
_interp_gg_fit(fit, s::Real) -> fit::GGCoefs

Take GG fit results fit which give the GG functions at a set of planes and return a similar GGCoefs but with one plane: the GG coefficients for that plane are the interpolated GG coefficients at the given s-position.

  • fit — GG coefficients for all planes.

Builds a single virtual plane at s by Hermite-interpolating every GG derivative tower from the two straddling grid planes (one-plane Taylor if only one plane).

source
GeneralizedGradients._make_dA — Method
_make_dA(Axx, Axy, dAxv, Ayx, Ayy, dAyv, Asx, Asy, dAsv) -> SMatrix{3,3,Float64}

Assemble the 3x3 Jacobian dA[i,j] = ∂A_i/∂u_j (rows Ax,Ay,As; columns x,y,s) as a stack-allocated SMatrix (no heap allocation). Arguments are given row-major; the SMatrix constructor takes them column-major.

source
GeneralizedGradients._make_tower — Method
_make_tower(z, Fn, slots, extra_slots, extra_planevals) -> _Tower

Build one tower from a per-n value matrix Fn[j+1, plane] = f⁽ʲ⁾ at that plane, its slots, and any extras. z are the base planes. Precomputes the interpolant's monomial coefficients on every straddling plane-pair (or the single-plane Taylor series when there is one plane).

source
GeneralizedGradients._read_field_group — Method
_read_field_group(g1, name, lb, nx, ny, nz)

Read a field group ("magneticField"/"electricField") into an (ix, iy, iz) OffsetArray of [Bx,By,Bz] 3-vectors indexed from lb, or nothing if absent.

In a Bmad field_grid file each component dataset is written Fortran-order (logical dims [nx,ny,nz]; on-disk C-dims (nz,ny,nx)). HDF5.jl reverses dims on read, so it hands back a 1-based (nx, ny, nz) array that is already the field – no transpose needed.

source
GeneralizedGradients._taylor_derivs — Method
_taylor_derivs(z0, f0, sq) -> Vector

Single-point Taylor tower: from f and its derivatives at z0, return [P⁽ᵐ⁾(sq) for m=0..N] with P the Taylor series, i.e. f extrapolated to sq.

source
GeneralizedGradients._taylor_poly — Method
_taylor_poly(f0) -> Vector{Float64}

Monomial coefficients (in u = s - z0) of the single-plane Taylor series: poly[d+1] = f0[d+1] / d!, so that P⁽ᵐ⁾(u) matches _taylor_derivs.

source
GeneralizedGradients._trim3 — Method
_trim3(CBx, CBy, CBs) -> (CBx, CBy, CBs)

Trim three coefficient arrays to the smallest (x,y) extent holding every nonzero entry, so the returned matrices are indexed CB[i+1, j+1] = CB_{c,i,j}.

source
GeneralizedGradients._write_field_grid_text — Method
_write_field_grid_text(path, mag, r0, dr, is_bend, field_scale)

Write the plain-text field-grid block from an (ix, iy, iz) OffsetArray of [Bx,By,Bz] 3-vectors, using the grid's own indices (origin r0, spacing dr, anchor = beginning).

source
GeneralizedGradients._write_fixed_str_array — Method
_write_fixed_str_array(parent, name, strs::AbstractVector{<:AbstractString})

Write a fixed-length (null-terminated, ASCII) string-array attribute, matching Bmad's hdf5_write_attribute_string rank-1. HDF5.jl writes String arrays as variable-length strings by default, which Bmad's reader cannot convert into its fixed character buffers (it aborts on axisLabels).

source
GeneralizedGradients.gg_to_bmad_curves — Method
gg_to_bmad_curves(fit) -> (cs, cc, c0c, nplanes, m_max, kmax)

Compute the Bmad azimuthal-harmonic GG derivative towers from a loaded gg_fit result (fit, the GGCoefs struct returned by read_gg_fit). Returns

cs[(m,j)]  :: Vector  -- C^{[j]}_{m,sin}(plane)  (normal multipole m)
cc[(m,j)]  :: Vector  -- C^{[j]}_{m,cos}(plane)  (skew multipole m)
c0c[j]     :: Vector  -- C^{[j]}_{0,cos}(plane)  (solenoid, j ≥ 1)

each a per-plane vector, for j = 0 … m_max.

source