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
GeneralizedGradients.FieldGridTableGeneralizedGradients.GGCoefsGeneralizedGradients.GGEvalPlanGeneralizedGradients._CompTermsGeneralizedGradients._TowerGeneralizedGradients._accumGeneralizedGradients._anchor_from_strGeneralizedGradients._anchor_to_strGeneralizedGradients._attrGeneralizedGradients._build_compGeneralizedGradients._build_eval_planGeneralizedGradients._build_towers_m!GeneralizedGradients._build_towers_nm!GeneralizedGradients._coefsumGeneralizedGradients._comp_arrayGeneralizedGradients._comp_fullGeneralizedGradients._comp_valueGeneralizedGradients._component_datasetGeneralizedGradients._contiguous_orderGeneralizedGradients._eval_scratchGeneralizedGradients._field_CBGeneralizedGradients._fill_gvals!GeneralizedGradients._geometry_from_strGeneralizedGradients._geometry_to_strGeneralizedGradients._get_eval_planGeneralizedGradients._gg_numGeneralizedGradients._hermite_derivsGeneralizedGradients._hermite_polyGeneralizedGradients._interp_gg_fitGeneralizedGradients._interp_m_dictGeneralizedGradients._interp_nm_dictGeneralizedGradients._interp_towerGeneralizedGradients._is_hdf5_pathGeneralizedGradients._make_dAGeneralizedGradients._make_towerGeneralizedGradients._peakGeneralizedGradients._polyvalGeneralizedGradients._read_field_groupGeneralizedGradients._taylor_derivsGeneralizedGradients._taylor_polyGeneralizedGradients._trim3GeneralizedGradients._write_coef_groupGeneralizedGradients._write_field_component_jlGeneralizedGradients._write_field_grid_textGeneralizedGradients._write_field_groupGeneralizedGradients._write_fixed_str_arrayGeneralizedGradients.field_and_potential_evaluateGeneralizedGradients.field_and_potential_evaluate_atGeneralizedGradients.field_coefficients_at_planeGeneralizedGradients.field_coefficients_at_sGeneralizedGradients.field_evaluate_atGeneralizedGradients.gg_coefficients_at_planeGeneralizedGradients.gg_coefficients_at_sGeneralizedGradients.gg_fitGeneralizedGradients.gg_fit_show_resultsGeneralizedGradients.gg_to_bmad_curvesGeneralizedGradients.potential_evaluate_atGeneralizedGradients.read_field_grid_hdf5GeneralizedGradients.read_gg_fitGeneralizedGradients.write_bmad_field_grid_elementGeneralizedGradients.write_bmad_gg_fitGeneralizedGradients.write_field_gridGeneralizedGradients.write_field_grid_hdf5GeneralizedGradients.write_gg_fit
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 strength1/bending_radius, in 1/m (0for a straight reference curve).scale— overall field scale factor.RF_frequency— RF frequency in Hz (0for a static field).RF_phase— RF phase [rad].anchor_pt— grid anchor point, aGridAnchorPt.T(Beginning,Center, orEnd).geometry— grid geometry, aGridGeometry.T(XYZ).
FieldGridTable() builds an empty table with T = Float64; read one from a file with read_field_grid_hdf5.
GeneralizedGradients.GGCoefs — Type
mutable struct GGCoefsHolds 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—zposition of each base plane [m].params— list of fitted unknowns as(type, n, m)tuples, wheretypeis one of:a,:b,:bs(bsusesn = 0).a— fitteda(n,m)functions,Dict (n,m) => values_over_planes.b— fittedb(n,m)functions,Dict (n,m) => values_over_planes.bs— fittedbs(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] (0for 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 compiledGGEvalPlanused byfield_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.
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— theGGCoefsstruct returned byread_gg_fit.ip— 1-based plane index intofit.z_base.x,y— absolute transverse coordinates.fit.originis 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).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— theGGCoefsstruct fromread_gg_fit.x,y— absolute transverse coordinates (fit.originsubtracted 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.
GeneralizedGradients.field_coefficients_at_plane — Method
field_coefficients_at_plane(fit, ip::Integer) -> (CBx, CBy, CBs)Field-expansion coefficients at a grid plane.
fit— theGGCoefsstruct fromread_gg_fit.ip— 1-based plane index intofit.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.
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.
GeneralizedGradients.field_evaluate_at — Method
field_evaluate_at(fit::GGCoefs, x::Real, y::Real, s::Real) -> BLike 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.
GeneralizedGradients.gg_coefficients_at_plane — Method
gg_coefficients_at_plane(fit, ip::Integer) -> (a, b, bs)Generalized-gradient coefficients at a grid plane.
fit— theGGCoefsstruct fromread_gg_fit.ip— 1-based plane index intofit.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ᵐ.
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.
GeneralizedGradients.gg_fit — Method
gg_fit(field::FieldGridTable, params::GGFitInputParams) -> GGCoefsFit 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— aFieldGridTable.field.magnetic[ix,iy,iz]is the[Bx,By,Bz]3-vector at the grid point, whose(x, y, z)position isfield.r0 + field.dr .* (ix, iy, iz).params— aGGFitInputParamsholding 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)^2The 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_maxwhere 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. Iffield.g_refis non-zero,originmust be[0, 0]. Default[0.0, 0.0].n_planes_add— number ofz-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. Default1(uniform).outer_plane_weight— merit-function weight for the outerz-planes. Default1.output_file— name of the output HDF5 file written bywrite_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.
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.
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.
GeneralizedGradients.read_field_grid_hdf5 — Method
read_field_grid_hdf5(path; index = 1) -> FieldGridTableRead 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).
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 curvatureGeneralizedGradients.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. Defaultele_name.field_scale— overall field scale factor written to the field grid. Default1.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.
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_pathConvert 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, theoutput_basebasename).output_base— base name for the two output files:<output_base>.bmad(the lattice element) and<output_base>_gg.bmad(the attachedgen_grad_map). Defaults to the input file name without extension, orele_namefor an in-memory fit.cutoff— relative magnitude cutoff for pruning negligible multipole curves. A curve is dropped if its peak|GG|is belowcutoff * (largest peak |GG| of any curve). Default0(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.
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.
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.
GeneralizedGradients.write_gg_fit — Method
write_gg_fit(results::GGCoefs, field::FieldGridTable, params::GGFitInputParams) -> output_file_pathWrite 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,:]}Internal
These functions are not exported but are documented for reference.
GeneralizedGradients.GGEvalPlan — Type
GGEvalPlanCompiled, 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).
GeneralizedGradients._CompTerms — Type
_CompTermsOne 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.
GeneralizedGradients._Tower — Type
_TowerOne 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.
GeneralizedGradients._accum — Method
_accum(tdict, valfun, g_ref) -> KCoefficient-array builder. K[p+1,q+1] = coefficient of xᵖ yᵠ. valfun(key) returns the GG function value multiplying that table entry.
GeneralizedGradients._anchor_from_str — Method
_anchor_from_str(s) -> GridAnchorPt.TParse an openPMD eleAnchorPt string into a GridAnchorPt enum value.
GeneralizedGradients._anchor_to_str — Method
_anchor_to_str(a::GridAnchorPt.T) -> StringMap a GridAnchorPt enum value to its openPMD eleAnchorPt string.
GeneralizedGradients._attr — Method
_attr(obj, name, default)Read an attribute if present, else return default.
GeneralizedGradients._build_comp — Method
_build_comp(Ta, Tb, Tbs, bump, g_ref, slot_a, slot_b, slot_bs) -> _CompTermsFlatten 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.
GeneralizedGradients._build_eval_plan — Method
_build_eval_plan(fit::GGCoefs) -> GGEvalPlanCompile 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.
GeneralizedGradients._build_towers_m! — Method
_build_towers_m!(towers, z, d, slotmap, next) -> nextLike _build_towers_nm! but for the m-keyed bs dict: a single _Tower.
GeneralizedGradients._build_towers_nm! — Method
_build_towers_nm!(towers, z, d, slotmap, next) -> nextAssign 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.
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.
GeneralizedGradients._comp_array — Method
_comp_array(Ta, Tb, Tbs, aval, bval, bsval, g_ref) -> KCombined coefficient array of a component: sum of its a, b and bs parts. Ta/Tb are keyed by (n,m) and Tbs by m.
GeneralizedGradients._comp_full — Method
_comp_full(ct, gvals, xp, yq) -> (val, dvx, dvy)Like _comp_value but also returns the x and y partial derivatives of the component.
GeneralizedGradients._comp_value — Method
_comp_value(ct, gvals, xp, yq) -> valEvaluate 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.
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.
GeneralizedGradients._contiguous_order — Method
_contiguous_order(orders) -> NLargest N such that orders 0,1,…,N are all present in orders (sorted).
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.
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.
GeneralizedGradients._fill_gvals! — Method
_fill_gvals!(gvals, upow, plan, s) -> gvalsInterpolate 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.
GeneralizedGradients._geometry_from_str — Method
_geometry_from_str(s) -> GridGeometry.TParse an openPMD gridGeometry string into a GridGeometry enum value.
GeneralizedGradients._geometry_to_str — Method
_geometry_to_str(::GridGeometry.T) -> StringMap a GridGeometry enum value to its openPMD gridGeometry string (only XYZ is supported).
GeneralizedGradients._get_eval_plan — Method
_get_eval_plan(fit::GGCoefs) -> GGEvalPlanReturn 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).
GeneralizedGradients._gg_num — Method
_gg_num(x::Real) -> StringLossless, 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.
GeneralizedGradients._hermite_derivs — Method
_hermite_derivs(zL, zR, fL, fR, sq) -> VectorTwo-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).
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.
GeneralizedGradients._interp_gg_fit — Method
_interp_gg_fit(fit, s::Real) -> fit::GGCoefsTake 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).
GeneralizedGradients._interp_m_dict — Method
_interp_m_dict(d, iL, iR, zL, zR, sq, single) -> DictInterpolate an m-keyed dict (bs): a single Hermite tower.
GeneralizedGradients._interp_nm_dict — Method
_interp_nm_dict(d, iL, iR, zL, zR, sq, single) -> DictInterpolate an (n,m)-keyed dict (a, b): build one Hermite per multipole n.
GeneralizedGradients._interp_tower — Method
_interp_tower(fL, fR, zL, zR, sq, single) -> VectorInterpolate one GG function's derivative tower onto sq (Hermite, or Taylor if single).
GeneralizedGradients._is_hdf5_path — Method
_is_hdf5_path(path)True if path should be treated as an HDF5 file (".h5" or ".hdf5" suffix).
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.
GeneralizedGradients._make_tower — Method
_make_tower(z, Fn, slots, extra_slots, extra_planevals) -> _TowerBuild 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).
GeneralizedGradients._peak — Method
_peak(d, m) -> Float64Peak |value| of a derivative tower's value column (j = 0), used for cutoffs.
GeneralizedGradients._polyval — Method
_polyval(K, x, y) -> (val, dvx, dvy)Value and (x,y) partials of the plain polynomial Σ K[i,j] xⁱ yʲ.
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.
GeneralizedGradients._taylor_derivs — Method
_taylor_derivs(z0, f0, sq) -> VectorSingle-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.
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.
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}.
GeneralizedGradients._write_coef_group — Method
_write_coef_group(parent, name, d; single::Bool = false)Write a Dict keyed by (n,m) (or by m, if single) as index arrays + matrix.
GeneralizedGradients._write_field_component_jl — Method
_write_field_component_jl(io, name, field)Write the fg.<name> OffsetArray of [Bx,By,Bz] 3-vectors as include-able Julia.
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).
GeneralizedGradients._write_field_group — Method
_write_field_group(g1, name, field, unit_dim, unit_sym)Write one field group ("magneticField"/"electricField") from an (ix,iy,iz) OffsetArray of 3-vectors.
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).
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.