Skip to content

API reference

Lumped-element detectors, cavity haloscopes and SRF heterodyne cavities search for axion dark matter. Here we list the public objects of the axionmultiphysics Python package, grouped by topic.

Errors

Every error the package raises is an AxionMultiPhysicsError. Besides its text it has four attributes: where (a JSON pointer into the document, or an empty string), hint (what to change), code (a stable dotted identifier, or an empty string) and details (a dict of structured facts, or None; None also when the details are nested deeper than 64 levels, the details object being level 1, as on the command line and in the MCP reply). The command line prints code and details in its error JSON only when they are not empty (see the command line), and the MCP server's failure reply carries the same four fields.

The physics catalogue (beta)

axionmultiphysics.physics(routes=False, type=None) returns the physics catalogue of model documents as a dict, the JSON that axmp physics --json prints (schema axionmultiphysics.physics_catalogue/1): the physics types with their options, condition kinds, sources and quantities, the coupling terms, the reserved instance ids and, with routes=True, the route table and the layer rules. Everything in it is beta, and no route is implemented in this version. The reference page is generated from it.

The codes that the findings about a model document carry are listed in the error codes of the model document, a page generated from the table of codes in the core (axionmultiphysics._core.error_codes() returns it as JSON text). Design.validate(strict=False, all_errors=False) of a model document (one with a top-level physics key) returns its validation report (ok, name, parameters, errors, unavailable, deferred, warnings), raising the first error (with strict, also the first unavailable finding) unless all_errors; axmp.load refuses a model document whose file repeats a key (json.duplicate_key). Design.boundaries(mesh=False, all_errors=False) returns the table of the named boundaries of a model document as axmp boundaries --json prints it (the validation report with symmetry, boundaries and edges added; mesh=True adds faces), raising the first error unless all_errors; axmp.mesh(d, workdir=None, mesher=None) meshes a model document (a Design or a dict) and returns a MeshedModel with symmetry, geometry_order, regions, boundaries, mesh_file, info_file and instance(domain=None), which returns the InstanceMesh of a region or domain name, a list of names or every region: its attributes, remaining_attributes, axis_attributes, master_attribute, region_attribute, the arrays vertices(), elements(), element_attributes(), boundary() and boundary_attributes(), section(name) and face_points(name=None, *, order, attribute=None), the quadrature on the faces of a boundary, a section or one instance attribute (the way to the edges no boundary names and to the axis), with the points, weights and normals as NumPy arrays. Both need the mesher: without one that runs they raise build.requires_mesher; a 3D document, a document on an imported mesh and (for axmp.mesh) a document with no geometry raise route.not_implemented; a failed mesher run is mesh.generation_failed; misuse of an instance mesh (an unknown name, an attribute that is not on it) is a ValueError; an electromagnetic design is refused without a code. An InstanceMesh also has fluids_mesh() (a fluids.Mesh copy of it; MPI builds, else build.requires_fluids) and chem_mesh(order=2) (a chem.TriMesh; MeshedModel.fluids_mesh(domain=None) and MeshedModel.chem_mesh(domain=None, order=2) are shorthands). See meshes of model documents. Design.solve refuses a model document with route.not_implemented, and the electromagnetic-only operations (Design.gradient, Design.optimize, axmp.optimize, axmp.global_optimize, sensitivity.optimize, convert.to_3d, comsol.export_comsol, the model classes of _core) refuse it with model.em_only_operation; both name the operation in details.operation. Design.explain() and Design.patch() read a model document too.

Design.explain(json=False) returns the resolved model of a model document as the text that axmp explain prints, or with json=True as the dict of schema axionmultiphysics.explain/1. It raises AxionMultiPhysicsError for a document that fails validation (the first error) and for an electromagnetic design.

Design.patch(ops) applies an RFC 6902 JSON Patch (a list of operations; paths are RFC 6901 JSON pointers) atomically and returns the design: either every operation applies and the result validates, or AxionMultiPhysicsError is raised and design.doc is unchanged. The keys of the patched document are in sorted order (the order of the keys of a JSON object carries no meaning). An operation that cannot be applied raises with the code patch.operation_failed and where /<index>; a result that does not validate raises the validation's own error. It works on electromagnetic designs too.

physics

physics(
    routes: bool = False, type: str | None = None
) -> dict

The physics catalogue of model documents (beta), as axmp physics --json prints it.

The catalogue lists the physics types (their options, condition kinds, sources, quantities per geometry class and what is not implemented), the coupling terms and the reserved instance ids; routes=True adds the route table, one row per combination of physics, couplings, geometry class and study type that an engine of this version solves, with what each row offers and needs, and the rules of this layer. Every entry is beta, and no route is implemented yet (every row has "implemented": False and "status": "not_implemented"). The catalogue is the same in every build. The schema string is axionmultiphysics.physics_catalogue/1.

Parameters:

Name Type Description Default
routes bool

Add the route table ("routes") and the layer rules ("layer_rules").

False
type str | None

Restrict the catalogue to one physics type, the rows whose physics contain it and the coupling terms it produces or consumes.

None

Returns:

Type Description
dict

The catalogue: schema, status, types, terms, reserved_ids and, with routes=True, routes and layer_rules.

Raises:

Type Description
AxionMultiPhysicsError

type is not the name of a physics type (an alias is refused too); the hint names the types.

Designs and solves

axionMultiPhysics provides functions and classes for creating designs from templates or files, solving them and accessing the results.

template

template(name: str, **params: Any) -> 'Design'

Instantiate a parametric template, overriding parameter defaults.

Values may be numbers or expression strings over other parameters, e.g. template("core", Rc=1.5, b="2*Rc").

templates

templates() -> list[dict]

Parametric templates with their parameters (default, units, meaning).

load

load(path: str | Path) -> 'Design'

Load a design from a JSON file. A model document (one with "physics") that repeats a key in an object is refused (json.duplicate_key): JSON would keep only the last value.

Design

Design(doc: dict)

A design document (dict) with helpers.

The document is the single source of truth; this class never hides state. d.doc is the underlying dict and may be edited directly.

Methods:

Name Description
resolved_params

Numerical values of all parameters (expressions evaluated).

set

Change existing parameters in place; returns self.

add_param
with_params

A modified copy.

copy
validate

Parse and check the design in C++; raises AxionMultiPhysicsError with a hint on problems.

boundaries

The named boundaries of a model document, as axmp boundaries --json prints them (beta).

explain

The resolved model of a model document (beta), as axmp explain prints it.

patch

Apply an RFC 6902 JSON Patch (a list of operations) atomically; returns self.

to_json
save
solve

Mesh and solve; returns Results.

export_gdml

Writes the geometry of an axisymmetric or 3D electromagnetic design as GDML for particle transport (beta).

gradient

Solve and return the derivatives of the figures of merit with respect to parameters.

optimize

Optimize this design; see axionmultiphysics.optimize() (method="global": differential evolution).

Attributes:

Name Type Description
doc dict
name str
params dict

Parameter definitions (numbers or expressions).

doc instance-attribute

doc: dict = copy.deepcopy(doc)

name property

name: str

params property

params: dict

Parameter definitions (numbers or expressions).

resolved_params

resolved_params() -> dict

Numerical values of all parameters (expressions evaluated).

set

set(**params: Any) -> 'Design'

Change existing parameters in place; returns self.

Raises KeyError for unknown names (use add_param to create one).

add_param

add_param(name: str, value: Any) -> 'Design'

with_params

with_params(**params: Any) -> 'Design'

A modified copy.

copy

copy() -> 'Design'

validate

validate(
    strict: bool = False, all_errors: bool = False
) -> dict

Parse and check the design in C++; raises AxionMultiPhysicsError with a hint on problems.

A model document (one with "physics") returns the validation report: ok, name, parameters and the findings errors, unavailable, deferred, warnings. It raises the first error, and with strict the first unavailable finding; all_errors=True returns the report without raising. An electromagnetic design ignores both flags.

boundaries

boundaries(
    mesh: bool = False, all_errors: bool = False
) -> dict

The named boundaries of a model document, as axmp boundaries --json prints them (beta).

Validates the document, runs the mesher's resolve_only pass and the full check (the partition rule of every physics, the empty selections, the partial matches, the outputs on resolved boundaries), and returns the validation report with symmetry, boundaries (one row per name: selector, entities, measure, bbox, point, adjacent, used_by) and edges added. mesh=True also meshes the model and adds the number of boundary elements, faces, to every row and edge. Raises AxionMultiPhysicsError with the first error (also build.requires_mesher when the mesher does not run, and mesh.generation_failed); all_errors=True returns the report instead of raising. Needs the mesher; an electromagnetic design is refused.

explain

explain(json: bool = False) -> 'str | dict'

The resolved model of a model document (beta), as axmp explain prints it.

Every default is listed and tagged, each physics with its boundary conditions and the form the engine gives them, the coupling terms, the study, the route each group of physics takes and what it needs. Returns the text, or with json=True the dict of schema axionmultiphysics.explain/1. Raises AxionMultiPhysicsError for a document that fails validation (the first error) and for an electromagnetic design.

patch

patch(ops: Any) -> 'Design'

Apply an RFC 6902 JSON Patch (a list of operations) atomically; returns self.

Either every operation applies and the result validates, or AxionMultiPhysicsError is raised (code patch.operation_failed with the index of the operation in where, or the validation's own error) and the document is unchanged. Paths are JSON pointers (RFC 6901). Works on electromagnetic designs too.

to_json

to_json(indent: int | None = 2) -> str

save

save(path: str | Path) -> Path

solve

solve(
    workdir: str | Path | None = None,
    order: int = 0,
    verbose: int = 1,
    threads: int | None = None,
    mpi_ranks: int = 1,
    launcher: str | None = None,
    self_force: bool = True,
    force_samples: int = 200,
) -> "Results"

Mesh and solve; returns Results.

workdir defaults to runs/<name>. order overrides mesh.order. 3D designs: mpi_ranks > 1 runs axmp solve --save on that many MPI ranks (launcher: e.g. "srun" or "mpirun"; default: $AXMP_MPI_LAUNCHER, else srun inside a SLURM allocation when srun is on PATH, else mpirun, else mpiexec) and loads the saved solution, so sampling and scenes work as after a single-process solve.

self_force estimates (and, for linear designs, removes) the numerical self-force of each powered azimuthal winding, at the price of one extra linear solve per such winding (axisymmetric designs only).

force_samples is the number of samples per body in forces.distributions. The merge that produces them preserves the integral, so the net forces do not depend on it; it only sets how finely the load is resolved and how big results.json gets (about 160 bytes per sample per body). 0 keeps the net forces and the closure check but writes no arrays.

export_gdml

export_gdml(
    path: str | Path,
    composition: dict,
    *,
    solids: str | Path | None = None,
    chord_tol_m: float | None = None,
    workdir: str | Path | None = None,
    mesher: str | Path | None = None,
) -> dict

Writes the geometry of an axisymmetric or 3D electromagnetic design as GDML for particle transport (beta).

The route is the design's mesher input (the one axmp mesh writes), axmp-mesher --export-regions on it (the exact partition of the model: its regions, the background air included, with their curves) and axionmultiphysics.solids.from_partition() on that partition. Returns the solids document (axionmultiphysics.solids/1) and writes the GDML at path and, when solids is a path, the document as solids.json there.

composition maps each material name the regions use to a particle block (nist, or elements and by; optional mean_excitation_eV, state, T_K, pressure_Pa) with an optional density (kg/m3). A region takes its design material, the background region the material named air. A material's density is the design's (as the electromagnetic parser resolves it: the built-in iron, copper and nb values, expressions evaluated) when it has one, else the block's density; two different positive values are particle.composition_invalid, none particle.density_missing, and a used material without a block particle.composition_missing. Blocks of materials no region uses are ignored.

For a 3D design the mesher input is the 3D engine's (mesh3d_in.json, made by the same library function in every build, without running the engine: each rank of a parallel program exports on its own), the partition the mesher's 3D one (one triangulation of every face, to the chord tolerance) and the solids are tessellated; chord_tol_m then goes to the mesher (default: min(1 mm, 1e-4 x the diagonal of the geometry)). A design reduced by symmetry planes (mesh.symmetry) is refused.

chord_tol_m is the conversion's chord tolerance. workdir, when given, keeps regions_in.json (the mesher input) and regions.json (the partition); without it nothing is left behind. mesher is the program (default: $AXMP_MESHER, else the one of the package). Refused: a model document (model.em_only_operation); a 3D design with mesh.symmetry, an imported mesh (mesh.file) and a mesher without the export mode (particle.partition_unavailable); a mesher that cannot be run or loaded (build.requires_mesher, with the loader's message); a planar design (particle.planar_not_offered); a failed mesher run (mesh.generation_failed, the last lines of the mesher's log in the hint; with workdir the log is kept there as regions_mesher.log). Nothing is written then.

gradient

gradient(
    params: Any = None,
    objectives: Any = None,
    method: str = "adjoint",
    step: float = 0.0001,
    steps: dict | None = None,
    benchmark: str = "",
    workdir: str | Path | None = None,
    order: int = 0,
    verbose: int = 0,
) -> dict

Solve and return the derivatives of the figures of merit with respect to parameters.

Shorthand for self.solve(...).sensitivities(...); see axionmultiphysics.Results.sensitivities() for the arguments and the returned dict.

optimize

optimize(
    objective: str = "cost",
    params: dict | None = None,
    **kw,
) -> dict

Optimize this design; see axionmultiphysics.optimize() (method="global": differential evolution).

Results

Results(model: '_core.Model', design, workdir: Path)

Results of a solved design.

res.data is the full results document (also written to <workdir>/results.json). Convenience properties give the most used numbers in SI units.

Methods:

Name Description
fullwave_losses

The surface losses of the full-wave sweep per solved frequency as arrays: f_Hz, Gamma and

fullwave_dense

Beta (the adaptive sweep). The dense curve of an adaptive 3D full-wave sweep (fullwave.adaptive) as

write_touchstone

Write the full-wave port parameters as a Touchstone v1 file (.sNp; kind "S", "Z" or "Y",

cavity_modes

Eigenmodes of a cavity design (design section cavity) as flat rows sorted by

cavity_mode_field

Fields of a cavity eigenmode on the cavity mesh (2D designs with a cavity section).

cavity_mode_sample

Fields of a cavity eigenmode at points (r, z) [m] (same keys, normalization and mode selection as

cavity_mode_probe

Fields of a cavity eigenmode on a regular (r, z) grid: r = (r0, r1, nr), z = (z0, z1, nz)

save_cavity_modes

Write each cavity eigenmode's fields (cavity_mode_field()) to <directory>/<FAM>_<index>.npz

mode_scene

Viewer/renderer scene of a cavity eigenmode: the design's regions with the mode's normalized fields

plot_mode

PNG of a cavity eigenmode on the meridional section, mirrored about the axis (C++ renderer;

hts_sample

Screening-current quantities of the final critical-state state at points (r, z) [m]:

benchmark
summary
sensitivities

Derivatives of the figures of merit with respect to design parameters.

reach

Expected 95% reach g_95(m_a) of this design for a noise benchmark.

readout

Readout-circuit analysis of this solved design.

draw_readout

Effective-circuit schematic of this design's readout: the network that

sample

Fields at points (r, z) [m]: Br, Bz, Bphi [T], psi [Wb/rad], pickup fields per ampere.

export_field_map

Field map of the static field for particle transport (beta; axionmultiphysics.fieldmap,

sample_mech

Displacement (u_r, u_z [m]), stress (sigma_rr, sigma_zz, sigma_hoop, sigma_rz,

torsion

Axisymmetric m = 0 torsional modal / harmonic analysis (beta; physics: docs/physics/mechanics_thermal.md

torsion_band

Band-averaged torsional mobility over [f_min, f_max] (n frequencies, n odd): harmonic.band

scene

Viewer scene.

save_scene
write_vtu
png

PNG snapshot (C++ renderer). Options: view='section'|'3d', quantity, log_scale, theme, ...

export_html

Self-contained interactive 3D viewer page.

show

Show this result in a Jupyter notebook and return the widget.

Attributes:

Name Type Description
design
workdir
data dict
coupling dict
forces dict

Lorentz / Maxwell forces.

Psi float

Signal coupling Psi = (1/I) int A_I . B_lab d^3x [H T m^2] (SI).

L_p float

Pickup inductance [H].

F float

Scan figure of merit Psi^4 / L_p^2 [T^4 H^2 m^8].

W float

Stored magnetic energy [J].

g float

Geometric factor g = Psi^2/(L_p W R^2) (natural units).

fullwave dict

Full-wave analysis beyond MQS (present when the design has a fullwave section): sweep rows

electrostatics dict

Electrostatics (present when the design has an electrostatics section): capacitance_F

C_matrix list

Maxwell capacitance matrix [F]; rows follow electrostatics['bodies'].

port_capacitance dict

Readout-gap capacitance of a poloidal (port) pickup: C_gap_F (with fringing),

conductors dict

Critical-current margins of every winding made of a named conductor: operating point

hts dict

Critical-state (screening-current) analysis (present when the design has an hts section):

B_max float
mechanics dict

Elasticity results (present when the design has a mechanics section): per-region

thermal dict

Steady-conduction results (present when the design has a thermal section):

design instance-attribute

design = design

workdir instance-attribute

workdir = Path(workdir)

data instance-attribute

data: dict = json.loads(model.results())

coupling property

coupling: dict

forces property

forces: dict

Lorentz / Maxwell forces.

Per winding: Fz_N and radial_force_per_radian_N (the hoop load); for a powered azimuthal winding also Fz_self_N (the numerical self-force, exactly zero in theory, so the error bar on Fz_N) and Fz_excluding_self_N (the force from all other sources -- the number to quote for a linear design). Per body: superconductor:<name> / iron:<name> Maxwell pressure forces. closure is the Newton's-third-law sum over all bodies, which must vanish. distributions holds the distributed load of each body; plot it with axionmultiphysics.plots.force_distribution().

Psi property

Psi: float

Signal coupling Psi = (1/I) int A_I . B_lab d^3x [H T m^2] (SI).

L_p property

L_p: float

Pickup inductance [H].

F property

F: float

Scan figure of merit Psi^4 / L_p^2 [T^4 H^2 m^8].

W property

W: float

Stored magnetic energy [J].

g property

g: float

Geometric factor g = Psi^2/(L_p W R^2) (natural units).

fullwave property

fullwave: dict

Full-wave analysis beyond MQS (present when the design has a fullwave section): sweep rows with Psi(omega), Z(omega), L(omega), R_rad, Q_rad, F(omega); eigenmodes.

electrostatics property

electrostatics: dict

Electrostatics (present when the design has an electrostatics section): capacitance_F (the Maxwell matrix, rows in the order of bodies), capacitance_to_ground_F, pairs with the mutual capacitances, and checks.

C_matrix property

C_matrix: list

Maxwell capacitance matrix [F]; rows follow electrostatics['bodies'].

port_capacitance property

port_capacitance: dict

Readout-gap capacitance of a poloidal (port) pickup: C_gap_F (with fringing), C_gap_port_region_F (gap region only, no fringing) and the self-resonance estimates.

Neither capacitance is a proven bound on the other: the rigorous relation, exact for the discrete problems, is checks.dirichlet_bound. self_resonance_Hz = 1/(2 pi sqrt(L_p C_gap)) is an estimate of the first self-resonance, not a bound.

conductors property

conductors: dict

Critical-current margins of every winding made of a named conductor: operating point (engineering and superconductor current density, peak |B|, field angle to the tape), Jc at the worst point of the winding, the load-line fraction and short-sample scale, and the temperature margin. The same block appears per benchmark (conductor_margins) at the required amplitude and at the cost-optimal size.

hts property

hts: dict

Critical-state (screening-current) analysis (present when the design has an hts section): steps (screening current, moment, max |J|/Jc, SCIF at the field-of-view points, Psi, energy balance), final (field quality, trapped flux, current profiles), ac_loss_per_cycle_J, psi (Psi with and without screening currents).

B_max property

B_max: float

mechanics property

mechanics: dict

Elasticity results (present when the design has a mechanics section): per-region max |u|, von Mises, hoop/radial/axial stress; support reactions; equilibrium closure.

thermal property

thermal: dict

Steady-conduction results (present when the design has a thermal section): per-region T min/max and the heat-flow balance.

fullwave_losses

fullwave_losses(port: int = 0) -> dict

The surface losses of the full-wave sweep per solved frequency as arrays: f_Hz, Gamma and R_eff_ohm per surface, R_loss_ohm, Q_loss, Q_total, T_over_Q_K and, from the 3D engine, L_eff_H, Q_loss_tuned, Q_total_tuned, T_over_Q_tuned_K, R_loss_over_abs_X (axionmultiphysics.circuit.fullwave_losses(); definitions in docs/physics/fullwave_surface_losses.md). The summary of a 3D sweep is fullwave["surface_losses"]. The R_s models behind R_loss are beta.

fullwave_dense

fullwave_dense() -> dict

Beta (the adaptive sweep). The dense curve of an adaptive 3D full-wave sweep (fullwave.adaptive) as arrays: f_Hz, Z, L_H, Psi (port 0), Z_matrix, Psi_vector, dZ_domega_H, estimated_relative_error (axionmultiphysics.circuit.fullwave_dense(); axionmultiphysics.circuit.fullwave_model() evaluates the model at any frequency).

write_touchstone

write_touchstone(
    path: str | Path | None = None,
    kind: str = "S",
    z0: float = 50.0,
    dense: bool = False,
    **kw,
) -> dict

Write the full-wave port parameters as a Touchstone v1 file (.sNp; kind "S", "Z" or "Y", reference resistance z0 ohm, dense: the adaptive model's dense curve instead of the solved rows; surface_losses=True adds the perturbative conductor loss). The values are in the engineering convention exp(+j omega t): the engine's exp(-i omega t) Z is conjugated. path defaults to <workdir>/<design>[_dense]_<kind>.s<N>p (the design name sanitised; an existing file is overwritten, see overwrote in the report). Returns the report (sigma_max of S, passivity violations, reciprocity error, warnings) of axionmultiphysics.touchstone.write_touchstone(); docs/physics/touchstone.md.

cavity_modes

cavity_modes(family: str | None = None) -> list[dict]

Eigenmodes of a cavity design (design section cavity) as flat rows sorted by frequency: family ("TE"/"TM"; "3D" for 3D designs), index (within the family), f_Hz, C (B0 at the reference point), C_rms, V_m3, G_ohm (geometry factor Q R_s of all walls), Q_wall, Q_dielectric, Q0, T_over_Q_K, residual_true, energy_fraction, walls (per body: G_ohm, Rs_ohm, Q, P_frac). Missing quantities are None. Empty for designs without a cavity section.

cavity_mode_field

cavity_mode_field(
    i=0, family: str | None = None, *, subdiv: int = 2
) -> dict

Fields of a cavity eigenmode on the cavity mesh (2D designs with a cavity section).

i indexes cavity_modes() (all families, sorted by frequency); with family ("TE"/"TM") it is the index within that family (row["index"]); a row of cavity_modes() also works. Returns numpy arrays over a lattice of points per cavity element (subdiv = 2: vertices and edge midpoints; points on element edges repeat with each element's value): r, z [m], tris (n, 3) sub-triangles, E_r, E_phi, E_z, H_r, H_phi, H_z, Emag, Hmag, flux, eps_r, mu_r, elem (element number), and mode (f_Hz, C, G_ohm, Q0, ... of the row).

Normalization: int eps_r |E|^2 dV = 1 over the cavity (E in m^-3/2, the normalization of the form factor); H is the matching physical field, so int mu_r |H|^2 dV = eps0/mu0 = 1/Z0^2 at resonance. The arrays are real amplitudes: the complex fields are E_c = i E, H_c = H (e^{-i omega t}, i.e. E(t) = E sin(omega t), H(t) = H cos(omega t)). TM modes have (E_r, E_z, H_phi), TE modes (E_phi, H_r, H_z); the other components are zero. The sign is fixed so that the largest E component at the point of largest |E| is positive (a convention: for modes whose |E| maxima are mirror images with opposite signs, e.g. TM011, it may differ between meshes). flux = r H_phi (TM; E field lines are its contours) or r E_phi/omega (TE; H field lines).

cavity_mode_sample

cavity_mode_sample(
    i, r, z, family: str | None = None
) -> dict

Fields of a cavity eigenmode at points (r, z) [m] (same keys, normalization and mode selection as cavity_mode_field(), without tris); NaN outside the cavity (a point exactly on the wall may fall in the wall element: sample just inside).

cavity_mode_probe

cavity_mode_probe(
    i, r: tuple, z: tuple, family: str | None = None
) -> dict

Fields of a cavity eigenmode on a regular (r, z) grid: r = (r0, r1, nr), z = (z0, z1, nz) (the design's cavity.probe_grid, evaluated on demand). Arrays have shape (nz, nr); R, Z hold the grid.

save_cavity_modes

save_cavity_modes(
    directory: str | Path | None = None,
    modes=None,
    *,
    subdiv: int = 2,
) -> list[Path]

Write each cavity eigenmode's fields (cavity_mode_field()) to <directory>/<FAM>_<index>.npz (default directory <workdir>/cavity_modes; modes: indices into cavity_modes(), default all). Every file holds the arrays plus meta (a JSON string: the cavity_modes() row, the normalization and the phase convention). Load with numpy.load(path).

mode_scene

mode_scene(
    i=0,
    family: str | None = None,
    *,
    subdiv: int = 2,
    field_lines: bool = True,
    contours: int = 14,
    view_scale: float = 1.3,
    label: str | None = None,
) -> dict

Viewer/renderer scene of a cavity eigenmode: the design's regions with the mode's normalized fields (quantities Emag, Hmag, Er, Ez, Ephi, Hr, Hz, Hphi; see cavity_mode_field()) on the cavity, and field lines (TM: E lines, contours of r H_phi; TE: H lines, contours of r E_phi) when field_lines. Render it with axionmultiphysics.render.save_png() or plot_mode().

plot_mode

plot_mode(
    i=0,
    path: str | Path | None = None,
    family: str | None = None,
    *,
    quantity: str = "Emag",
    subdiv: int = 2,
    field_lines: bool = True,
    contours: int = 14,
    view_scale: float = 1.3,
    label: str | None = None,
    **options,
) -> Path

PNG of a cavity eigenmode on the meridional section, mirrored about the axis (C++ renderer; mode_scene()). quantity: Emag (default), Hmag, Er, Ez, Ephi, Hr, Hz, Hphi. Other options go to axionmultiphysics.render.render_png() (width, height, theme, annotate, title, log_scale, ...).

hts_sample

hts_sample(r, z) -> dict

Screening-current quantities of the final critical-state state at points (r, z) [m]: engineering current density J [A/m^2], local engineering Jc, azimuthal electric field E [V/m], the total field (Br, Bz) [T], A_phi and in_hts.

benchmark

benchmark(name: str) -> dict

summary

summary() -> str

sensitivities

sensitivities(
    params: Sequence[str] | None = None,
    objectives: Sequence[str] | None = None,
    method: str = "adjoint",
    step: float = 0.0001,
    steps: dict | None = None,
    benchmark: str = "",
    order: int = 0,
) -> dict

Derivatives of the figures of merit with respect to design parameters.

params defaults to every entry of the design's parameters, objectives to Psi, L_p, W_mag, F and the cost of the first benchmark (axionmultiphysics.objectives() lists them all; cost quantities accept a benchmark, e.g. "cost:optimistic"). method: "adjoint" (discrete adjoint on a morphed mesh, the default), "fd_morph" (central differences with mesh morphing) or "fd_remesh" (central differences with a new mesh per evaluation; the only method for nonlinear iron or for parameters that change the mesh topology). step is the relative finite-difference step, steps gives absolute per-parameter overrides.

The returned dict holds values, gradient[objective][parameter] (SI), relative[objective][parameter] (= d log J / d log p), the primitive quantities and diagnostics.

reach

reach(
    benchmark: str = "optimistic",
    amplitude: str = "required",
    **kw,
) -> dict

Expected 95% reach g_95(m_a) of this design for a noise benchmark. amplitude='required': field scaled so that F = F_req (reaches the QCD target); 'as_designed': the ampere-turns given in the design. Extra keywords go to scan.reach.

readout

readout(
    f_Hz: float | None = None,
    benchmark: str | dict | None = None,
    amplitude: str = "as_designed",
    model: str = "mqs",
    pickup_Q: float | None = None,
    R_loss_ohm: float | None = None,
    parasitic: bool = False,
    analyze: bool = True,
    **kw,
) -> dict

Readout-circuit analysis of this solved design.

Builds a DMRadio-style network -- pickup in series with a tuning capacitor, the SQUID input coil and the leads -- from this design's Psi, L_p and losses, tunes it to f_Hz (default: the middle of the design's scan band in log frequency) and returns the analysis: resonance, loaded Q, referred T_eff, the amplifier coupling xi, the signal flux into the SQUID, the Johnson/amplifier noise budget, the bandwidths and the equivalent optimal-scan inputs (Psi, L_eff, Q, T, eta_A).

model="mqs": Z_p = R_loss - i omega L_p with R_loss from R_loss_ohm, from pickup_Q, or from the design's RF surface losses. model="fullwave": Z_p(omega) interpolated from results["fullwave"]["sweep"]. benchmark sets T_K and eta_A from scan.BENCHMARKS (and, when no loss data and no pickup_Q are available, the pickup Q too). amplitude="required" scales Psi so that F = F_req for that benchmark. parasitic=True puts this design's readout-port gap capacitance (pickup/port_capacitance/C_gap_F, only the gap's share of the distributed capacitance) across the pickup, so that the self-resonance it implies is part of the circuit. Extra keywords go to axionmultiphysics.circuit.series_readout() (L_in_H, R_in_ohm, lead_length_m, L_per_m, R_per_m, tan_delta, M_H, xi, ...). The returned dict carries the live Readout under "readout"; it holds complex impedances, so it is not JSON-serialisable.

draw_readout

draw_readout(annotate: bool = True, **kw)

Effective-circuit schematic of this design's readout: the network that readout() builds (same keywords: f_Hz, benchmark, model, pickup_Q, parasitic, L_in_H, ...), drawn by axionmultiphysics.circuit.Readout.draw() with the values at f_Hz. Needs schemdraw (axionmultiphysics[draw]).

sample

sample(r: Sequence[float], z: Sequence[float]) -> dict

Fields at points (r, z) [m]: Br, Bz, Bphi [T], psi [Wb/rad], pickup fields per ampere.

export_field_map

export_field_map(
    path: str | Path,
    *,
    regions: Sequence[str] | None = None,
    tol: float = 0.0001,
    merge: bool = True,
    track_volumes: Sequence[dict] | None = None,
    iterate_on_track_volumes: bool = False,
    outside: str = "refuse",
    max_patch_MB: float = 512.0,
    max_total_MB: float = 2048.0,
)

Field map of the static field for particle transport (beta; axionmultiphysics.fieldmap, docs/guides/field_maps.md): one patch per region (kind 1 here, kind 3 for 3D results), each sampling the region's recovered field B* on its own grid and refined until the RMS error of its chord integrals, relative to max(int |B*| dl, 0.1 L_c B_patch), meets tol (or a tenth of the FE indicator, whichever is larger).

regions: the regions to map (default: every region but ideal superconductors, where B = 0); merge: adjacent regions with the same constitutive law and no curve between them share a patch; a closed curve (superconducting sheet or thin magnetic layer) splits its region into one patch per side, and an open one is refused. track_volumes: boxes {"name", "r": [lo, hi], "z": [lo, hi]} (3D: "x", "y", "z") whose own chord families are reported, and iterated on with iterate_on_track_volumes. outside: what the evaluator does outside a patch's box ("refuse" or "zero"). max_patch_MB, max_total_MB: caps (MB = 2^20 bytes). Writes the directory path and returns fieldmap.load(path); refusals write nothing.

sample_mech

sample_mech(r: Sequence[float], z: Sequence[float]) -> dict

Displacement (u_r, u_z [m]), stress (sigma_rr, sigma_zz, sigma_hoop, sigma_rz, von_mises [Pa]) and temperature (T_K) at points (r, z) [m]. in_structure / in_thermal_domain flag the points that lie inside each analysis domain.

torsion

torsion(
    nmodes: int = 0,
    load=None,
    freqs_Hz=None,
    eta: float = 0.0001,
    shapes: bool = False,
    regions: dict | None = None,
    dofs: bool = False,
    lanczos_extra: int = 24,
    verbose: int = 0,
    loads: list | None = None,
    band: dict | None = None,
    solver: dict | None = None,
    mesh_check: str = "error",
) -> dict

Axisymmetric m = 0 torsional modal / harmonic analysis (beta; physics: docs/physics/mechanics_thermal.md and docs/physics/torsion_highfreq.md; validation: docs/validation/torsion.md and docs/validation/torsion_highfreq.md).

Loads (they add up): - load: one azimuthal body-force value per degree of freedom of the space (use dofs=True once to get dof_r, dof_z); the FEM integrates its P_p interpolant, and the response reports what was applied (load.force_N, load.torque_N_m); - loads: a list of named loads, integrated exactly at quadrature points: {"region": R, "g_N_m3": v} (body force in region R), {"surface": {"on": R, "from": S or "vacuum"}, "traction_Pa": v} (azimuthal traction on the faces R shares with S), {"curve": C, "traction_Pa": v} (on a zero-thickness curve); v is a number, an expression in r and z [m] (e.g. "exp(-z^2/(2*0.005^2))") or one value per DOF. Expressions use standard precedence: exp(-z^2/(2*0.005^2)) is a Gaussian. Check loads.total.force_N against the load you meant. With freqs_Hz, or band = {"f_Hz": [f0, f1], "n": N, "length_m": L} (N odd; length_m optional), the response returns the generalised mobility Y = -i omega q of the conjugate pair (load scale, q = int g u_phi dV + int tau u_phi dA), time dependence e^{-i omega t}; S_q = 4 kB T Re[Y]/omega^2. harmonic.band holds the band mean of Re Y, its quadrature uncertainty, a ripple diagnostic and, with length_m, a conservative scale of the finite-length deviation (edge_estimate). Single frequencies are not certified by the mesh guard (it is calibrated on band means). solver = {"backend": "auto"|"eigen"|"strumpack", "parallel_frequencies": p | "auto"}. mesh_check ("error", "warn", "off") guards the elements per shear wavelength at the highest frequency (harmonic.resolution).

torsion_band

torsion_band(
    f_min: float,
    f_max: float,
    loads=None,
    load=None,
    eta: float = 0.001,
    n: int = 201,
    solver: dict | None = None,
    mesh_check: str = "error",
    regions: dict | None = None,
    verbose: int = 0,
    length_m: float | None = None,
) -> dict

Band-averaged torsional mobility over [f_min, f_max] (n frequencies, n odd): harmonic.band holds the mean of Re Y, its quadrature uncertainty, a ripple diagnostic (ripple_sem) and, with length_m (the structure's axial length), edge_estimate, a conservative scale of how far the band mean of the finite structure may sit from a smooth value (docs/physics/torsion_highfreq.md). The default solver is serial STRUMPACK (serial Eigen SparseLU in a build without STRUMPACK): robust in memory and never far from the fastest choice. solver={"parallel_frequencies": "auto"} opts in to the measured choice between concurrent Eigen solves and serial STRUMPACK (faster on thin walls; it costs one STRUMPACK and possibly one Eigen probe solve).

scene

scene(
    subdiv: int = 1,
    contours: int = 28,
    view_scale: float = 1.3,
    fields: bool = True,
) -> dict

Viewer scene.

save_scene

save_scene(path: str | Path | None = None, **kw) -> Path

write_vtu

write_vtu(
    path: str | Path | None = None, subdiv: int = 2
) -> Path

png

png(path: str | Path | None = None, **options) -> Path

PNG snapshot (C++ renderer). Options: view='section'|'3d', quantity, log_scale, theme, ... With mode=i (and optionally family), a cavity eigenmode (plot_mode(); quantity Emag by default).

export_html

export_html(
    path: str | Path | None = None,
    title: str | None = None,
    **scene_kw,
) -> Path

Self-contained interactive 3D viewer page.

show

show(quantity: str | None = None, **kw)

Show this result in a Jupyter notebook and return the widget.

The same self-contained page as export_html(), in an iframe, with a selector for the plotted quantity (w.quantity = "Bz" also works). Keyword arguments go to axionmultiphysics.widget.SceneWidget (mode, scale, height, options, backend); subdiv, contours, view_scale and fields go to scene().

Results3D

Results3D(model: '_core.Model', design, workdir: Path)

Bases: Results

Results of a solved 3D design ("symmetry": "3d"). Same numbers and benchmarks as Results; fields are sampled at (x, y, z) and scenes carry region surfaces plus a slice.

Methods:

Name Description
sample

Static field Bx, By, Bz [T] and pickup field per ampere at points (x, y, z) [m]; NaN outside.

scene

3D viewer scene: region surfaces (with surface |B|) and a field slice.

torsion

Not available for 3D designs (the torsional analysis is axisymmetric, m = 0).

sensitivities

Not implemented for 3D designs.

save

Write the solved fields (mesh, A_lab, A_pickup, state) for load_solution().

write_vtu

ParaView output (high-order VTU collection) of A_lab and the pickup potential.

png

PNG snapshot of the 3D scene (C++ renderer): surfaces cut open at the slice plane.

sample

sample(
    x: Sequence[float],
    y: Sequence[float],
    z: Sequence[float],
) -> dict

Static field Bx, By, Bz [T] and pickup field per ampere at points (x, y, z) [m]; NaN outside.

scene

scene(fields: bool = True, **_ignored) -> dict

3D viewer scene: region surfaces (with surface |B|) and a field slice.

torsion

torsion(*args, **kw) -> dict

Not available for 3D designs (the torsional analysis is axisymmetric, m = 0).

sensitivities

sensitivities(*args, **kw) -> dict

Not implemented for 3D designs.

save

save(path: str | Path | None = None) -> Path

Write the solved fields (mesh, A_lab, A_pickup, state) for load_solution().

write_vtu

write_vtu(
    path: str | Path | None = None, subdiv: int = 2
) -> Path

ParaView output (high-order VTU collection) of A_lab and the pickup potential.

png

png(path: str | Path | None = None, **options) -> Path

PNG snapshot of the 3D scene (C++ renderer): surfaces cut open at the slice plane.

requirement

requirement(
    benchmark: str | dict = "optimistic", **scan: Any
) -> dict

F_req for a benchmark name ("optimistic", "conservative", "conservative_solenoid") or a dict {name, Q, T, eta_A}; keyword arguments override scan settings (f_min, f_max, live_time [yr], model, C_QCD, rho_DM, Q_axion, Theta95).

optimize

optimize(
    design,
    objective: Any = "cost",
    params: dict | None = None,
    *args,
    method: str | None = None,
    **kw,
) -> dict

Optimize a design: method="global" runs global_optimize() (differential evolution); any other method (default: L-BFGS-B, or SLSQP with constraints) runs the adjoint-gradient local optimizer axionmultiphysics.sensitivity.optimize() with the same arguments.

global_optimize

global_optimize(
    design,
    objective: Any = "cost",
    params: dict | None = None,
    *,
    bounds: dict | None = None,
    constraints: Iterable = (),
    sense: str = "min",
    log: Sequence[str] = (),
    seed: int | None = 0,
    popsize: int = 15,
    maxiter: int = 50,
    tol: float = 0.01,
    atol: float = 0.0,
    mutation: Any = (0.5, 1.0),
    recombination: float = 0.7,
    strategy: str = "best1bin",
    init: Any = "latinhypercube",
    x0: dict | None = None,
    workers: Any = 1,
    threads: int = 1,
    timeout: float | None = None,
    max_time: float | None = None,
    polish: Any = True,
    polish_max_iter: int = 30,
    polish_maxfev: int = 200,
    benchmark: str = "",
    amplitude: str | None = "auto",
    amplitude_tol: float = 1e-06,
    amplitude_max_solves: int = 16,
    workdir: str | Path | None = None,
    order: int = 0,
    keep_runs: bool = False,
    precheck: Callable | None = None,
    verbose: int = 1,
    callback: Callable | None = None,
) -> dict

Global minimization (or maximization) of a figure of merit by differential evolution.

params (or its alias bounds; not both) maps parameter names to (low, high) or (low, high, "log"); log lists parameters searched in log space (use it for sizes and ratios spanning decades). objective is a quantity name (axionmultiphysics.objectives(), e.g. "cost", "cost_optimal:conservative", "g_factor") or a picklable callable f(results) -> float (importable by name in a worker when workers > 1 or a map is given). constraints holds {"quantity": "sc_surface_at_req", "type": "<=", "value": 0.093} entries (or 3-tuples); they are enforced by the feasibility rule, not by a penalty weight. values are keyed by the quantity name; a callable by its __name__ ("custom" without one), suffixed #2, #3 ... when that key is already taken (two lambdas, or a callable named like a quantity). A feasible objective must have |f| < 1e99 (larger values are failed points: rescale).

DE settings are scipy's: the population has max(5, popsize * len(params)) members (rounded up to a power of 2 for init="sobol"; an init array is given in parameter units, one row per member, inside the bounds), at most maxiter generations after the initial one. The search stops when the whole population is feasible and std(f) <= atol + tol * |mean(f)| (scipy >= 1.12; older scipy runs all maxiter generations). It is deterministic for a given seed: every evaluation (serial, pool or map) and the polish run on threads OpenMP threads (default 1; the calling process is set to it and restored on return), so that the solver's parallel sums do not depend on the thread count. workers > 1 evaluates each generation on a process pool (-1: the CPUs this process may use, divided by threads); a callable workers(fn, tasks) -> records (a map) distributes evaluations elsewhere, e.g. a SLURM array. Scripts that use a process pool must guard their entry point with if __name__ == "__main__":.

Failure handling. A shape that fails to mesh or solve is an infeasible point. With a process pool (workers > 1) also: an evaluation slower than timeout [s] (killed when still running timeout s after submission, which includes a worker's start-up after a restart, then the pool is restarted and the other running points are re-run; a finished one whose own run time exceeds timeout is charged too) and a worker that dies (the points running with it are re-run one at a time, so the crash is charged to the point that caused it). In serial mode (workers=1) timeout is ignored (with a warning) and a hard crash of the solver ends the run. Nothing is saved before the run returns. An error of the configuration (an unknown benchmark, cost_optimal on an iron design, a nonlinear design without an amplitude parameter, NI optimized while it is the amplitude, a callable that cannot be loaded in a worker, ...) is raised as ValueError at the first evaluation that shows it, instead of failing every point.

max_time [s] is checked after every generation (not inside one, nor during the initial population): the search then stops, the polish is skipped if the time is exhausted, the Powell polish stops when it is, and the adjoint polish (which cannot be interrupted; at most polish_max_iter iterations) is replaced by Powell unless 7 (polish_max_iter + 1) evaluations of the DE's mean duration fit in the remaining time (an iteration takes several solves). max_time is thus a soft bound: the last generation, a Powell evaluation, or an adjoint polish that needs more solves than this estimate can overrun it. callback(generation, best_record) returning True stops the search too.

precheck(parameters) rejects a point before it is meshed: a returned string (the reason, also an empty one), False (also numpy.False_) or a raised exception rejects it, None or True (also numpy.True_) accepts it; any other return value is an error. Use it for cheap geometric rules (wall thickness, corner radii). polish="adjoint" cannot apply it and is refused with a precheck.

Requirement quantities (cost, cost_optimal, W_at_req, sc_surface_at_req, ...) are read at F = F_req: by the solver's exact rescaling for linear designs, as by axionmultiphysics.optimize(); when the rescaling is not exact (nonlinear iron, or fixed sources such as a background field) the parameter amplitude (default "NI") is solved for F = F_req of the objective's benchmark to amplitude_tol (log-secant, at most amplitude_max_solves solves), and all requirement quantities must then refer to that benchmark. A nonlinear solve whose Newton iteration did not converge is a failed point. Known limitation: the amplitude at which the other quantities are read differs by case. When the root runs (a requirement quantity or any callable is asked for on a nonlinear design or one with fixed sources), every quantity and callable -- also B_peak, W_mag, sc_surface_peak -- is read at the root amplitude; on a linear design without fixed sources, non-requirement quantities and callables see the design's own NI. A constraint such as ("B_peak", "<=", 6) therefore means different things in the two cases; use the *_at_req quantities for limits at the operating point. A callable on a nonlinear design needs the amplitude parameter and costs the ~3 solves of the root.

polish: True/"auto" refines the best point with the adjoint-gradient optimizer when the design is linear without fixed sources (no amplitude root), the objective and constraints are named quantities, no precheck is given and order is 0, else with bounded Powell; "adjoint" (falling back to Powell if the adjoint optimizer fails or the point needed the amplitude root), "powell" or False choose. The polished point replaces the DE point only if it is feasible and better.

Returns the structure of axionmultiphysics.optimize() (parameters, values, caps, constraints, design, history of every evaluation with stage, generation, energy and feasible), plus feasible, de (generations, evaluations, convergence, scipy's own message), de_best, polish and found_by. converged is the DE convergence test above and message says how the search ended. evaluations is len(history) (DE and Powell points, adjoint iterates, precheck rejections); solves counts the FE solves (one per evaluated point, plus the amplitude-root and adjoint-polish solves). The default workdir is a new directory per run under runs/<design>__global/.

Lumped-element scan and reach

scan.multipole_scan (with scan.reach_multiband and scan.reach_2211, module axionmultiphysics.multipole) is beta.

reach

reach(
    Psi_SI: float,
    L_H: float,
    benchmark: str | dict = "optimistic",
    live_time_yr: float = 3.0,
    f_min: float = 120900.0,
    f_max: float = 1000000.0,
    allocation: str = "target",
    n: int = 200,
    model: str = "DFSZ",
    C_gamma: float = 1.77,
    Q_axion: float = 680000.0,
    Theta: float = 2.71,
    rho: float = 0.3,
) -> dict

Expected 95% upper-limit reach g_95(m_a) of a detector (Psi [H T m^2], L_p [H]) for a noise benchmark, with the optimal resonant scan over [f_min, f_max] in the live time. The default band, live time and model (DFSZ over 0.5-4.1 neV in 3 years) and the benchmarks are illustrative: set them for your study. allocation: 'target' (time distributed to follow the QCD line) or 'log_uniform'.

The result carries a "band" dict that echoes what was scanned -- mass and frequency range, number of mass points, allocation, live time, the benchmark (Q, T, eta_A), the detector (Psi, L, F) and the scan conventions (Q_axion, Theta, rho, v0, vobs, the QCD line) -- so that an output document is self-describing.

benchmark["eta_A"] may also be a callable eta_A(f_Hz), e.g. an axionmultiphysics.squid.Chain (squid.benchmark(chain, Q, T_K)). The scan then runs reach_dispersive() with constant Psi, L, Q, T and the frequency-dependent eta_A. That route also applies reach_dispersive's local-validity guards (noise bandwidth < 0.1 f, slow variation), which the scalar route does not, so a very low Q raises there; and its band entries for Q, T, eta_A, L, Psi are [f_min, f_max] endpoint values rather than scalars.

g_qcd

g_qcd(
    m_eV: Iterable[float],
    model: str = "DFSZ",
    C_gamma: float = 1.77,
) -> ndarray

|g_agg| [GeV^-1] on the QCD line (E/N from model, lattice C_gamma = 1.77 by default).

reach_fullwave

reach_fullwave(
    results,
    benchmark: str | dict = "optimistic",
    *,
    amplitude: str = "as_designed",
    T_K: float | None = None,
    eta_A: float | None = None,
    Q_floor: float | None = None,
    compare_mqs: bool = True,
    T_radiation_K: float | None = None,
    **kw,
) -> dict

Local beyond-MQS reach with the series-tuned slope inductance.

Independent resistances add: R_total=R_rad+R_material+omega*L_p/Q_other. The Q_floor argument (or the benchmark's Q) is the intrinsic MQS Q_other, referenced to the static L_p; it is not a minimum-Q ceiling. The MQS comparison retains material and intrinsic losses and removes radiation. Material/intrinsic loss is at T_K. Radiation uses T_radiation_K; omitting it explicitly assumes the same bath temperature and records that assumption. Both the tabulated slope and local noise bandwidth must pass the guards in reach_dispersive. Requested bands must lie in the contiguous positive-L sweep. For broad or rapidly dispersive response use finite_band with a tuned circuit.

The sweep's R_ohm holds the surface loss R_loss that the engines compute from the conductors' rf blocks (2D and 3D), so Q_other must exclude that loss: a benchmark Q that stands for the total intrinsic Q counts the conductor loss twice. When every row carries the exact tuned-pole L_eff_H (3D designs whose conductors are meshed as volumes: from dZ/domega), the full-wave scan takes L_eff from a cubic Hermite interpolant of L with those exact slopes, which must agree with the linear interpolation of the rows' L_eff within 5 % (else the rows are too sparse and the reach refuses), instead of L + 0.5 dL/dln(f) of the interpolated L (which needs four rows and spline/PCHIP agreement within 5 %). The MQS comparison always uses L_p.

finite_band

finite_band(
    readout,
    f_min_Hz: float,
    f_max_Hz: float,
    *,
    n_settings: int = 40,
    n_targets: int = 60,
    xi_factors: Sequence[float] = (1.0,),
    match_xi: bool = True,
    model: str = "DFSZ",
    C_gamma: float = 1.77,
    Theta: float = 2.71,
    rho: float = 0.3,
    Q_axion: float | None = None,
    stat: str = "weak",
    n_v: int = 96,
    half_widths: float = 60.0,
    decades: float = 3.0,
    points_per_decade: float = 48.0,
    band_points: int = 200,
    band_margin: float = 4.0,
    reduced: bool = True,
    reduced_R_exp: float = 0.0,
    narrow_line: bool = True,
    local_schedule: bool = True,
    convergence: bool = False,
    live_time_yr: float | None = None,
) -> dict

Plan a scan with the exact circuit noise N_V(omega) instead of the reduced pole.

Driven by axionmultiphysics.circuit: for each setting -- a tuning capacitance (hence an omega_0) and a coupling xi -- the readout network is tuned, N_V(omega) is tabulated exactly (noise_curve()), and the C++ kernel

``K_j(m) = (1/2pi) int domega h(S_Va(omega)/N_{V,j}(omega))``   [1/s]

is built for every target mass. The minimum-total-time schedule is the LP, and the reach follows from sum_j t_j K_j(m) = Theta. The pickup's Psi is taken from the readout at each tuning, so a frequency-dependent Psi(omega) is used if the readout has one.

With reduced=True the same settings are also evaluated through the single-pole reduction of each setting (L_eff, Q, T_eff, eta_A_eff, xi), which is what the rest of the package uses; comparison then quantifies the error of that reduction. reduced_R_exp gives the reduced pole a power-law resistance R(omega) = R_0 (omega/omega_0)^{R_exp} within a tuning (0 = constant, 1/2 for a normal-metal skin effect, 2 for a superconductor), which is the one piece of dispersion the single pole can carry. narrow_line=True adds the narrow-line kernel, evaluated with the exact N_V(omega_a). convergence=True repeats the kernel with half the N_V grid density and half the line nodes, so the numerical error of the exact kernel is reported rather than assumed.

Parameters:

Name Type Description Default
readout

an axionmultiphysics.circuit.Readout with a tuning capacitor (tuner) -- it is tuned in place, setting by setting, and left at the last setting -- or a callable f0_Hz -> Readout that builds the network for each tuning. The factory form is the one to use when the network itself depends on the tuning (a surface resistance quoted at the operating point, a full-wave Z_p(omega) and Psi(omega), a different input coil per octave); Psi(omega) is read from the first instance, the pickup being the same.

required
n_settings int

n_settings log-spaced tunings over [f_min, f_max] times one setting per entry of xi_factors (multiples of xi_opt; match_xi rescales M accordingly).

40
xi_factors Sequence[float]

See n_settings.

(1.0,)
n_targets int

log-spaced target masses over the same band; the LP covers these exactly and the returned reach is evaluated on them.

60
live_time_yr float | None

if given, the LP schedule is also reported rescaled to this live time (coverage_at_live_time = the Theta reached per target, in units of Theta).

None
Notes

local_schedule=True also discretises the local optimal-scan dwell density onto the settings and scores it with the exact kernel: a plan made from the Lorentzian scan rate covers at ~Theta only while the sensitivity band is narrow.

Returns a dict with band (the echo), settings, targets, K_per_s, schedule, reach, and -- when asked for -- reduced/narrow_line/ local_schedule/convergence and comparison.

multipole_scan

multipole_scan(table, **kw) -> dict

Beta. The multipole (multi-band) scan strategy (arXiv:2211.00008) on a full-wave Z(omega), V(omega) table (axionmultiphysics.multipole.SourceTable, or axionMultiPhysics results with a fullwave sweep). Thin wrapper of axionmultiphysics.multipole.multiband_scan(). The scan of arXiv:2211.00008 as defined there is reach_2211(). reach_fullwave is the single-band local scan below the first self-resonance.

Readout circuit and SQUID chains

The dc SQUID chains (axionmultiphysics.squid) are beta.

series_readout

series_readout(
    L_p_H: float | None = None,
    *,
    Z_p: ZFunc | None = None,
    Psi_SI: float | Callable[[float], float] = 0.0,
    f_Hz: float = 120900.0,
    Q: float | None = None,
    R_loss_ohm: float = 0.0,
    T_K: float = 0.02,
    C_F: float | None = None,
    tan_delta: float = 0.0,
    T_C_K: float | None = None,
    C_par_F: float = 0.0,
    tan_delta_par: float = 0.0,
    T_par_K: float | None = None,
    L_in_H: float = 0.0,
    R_in_ohm: float = 0.0,
    T_in_K: float | None = None,
    L_lead_H: float = 0.0,
    R_lead_ohm: float = 0.0,
    T_lead_K: float | None = None,
    lead_length_m: float = 0.0,
    L_per_m: float = 0.0,
    R_per_m: float = 0.0,
    M_H: float | None = None,
    k_in: float | None = None,
    L_squid_H: float = 0.0,
    eta_A: float = 1.0,
    xi: float | None = None,
    S_Phi: float | None = None,
    transformer_ratio: float | None = None,
    L_1_H: float = 0.0,
    L_2_H: float = 0.0,
    k_T: float = 1.0,
    R_2_ohm: float = 0.0,
    T_2_K: float | None = None,
    label: str | None = None,
) -> Readout

DMRadio-style readout: pickup in series with a tuning capacitor and the SQUID input coil.

Plain series topology (the default):

gnd -[ pickup: EMF, Z_p ]- a -[ L_lead ]- b -[ R_lead ]- c
    -[ C (tan_delta) ]- d -[ R_in ]- e -[ L_in ]- gnd          (M couples L_in -> SQUID)

With transformer_ratio an ideal transformer closes the resonant loop and the input coil (plus R_2_ohm) sits on its secondary; with L_1_H and L_2_H a real flux transformer (two inductors coupled by k_T) does the same job with finite inductance and leakage.

Parameters:

Name Type Description Default
L_p_H float | None

the pickup, either as an inductance (Z_p = R_loss - i omega L_p, R_loss from R_loss_ohm or from Q at f_Hz) or as a callable Z_p(omega) -- e.g. pickup_impedance() built from a solved design's full-wave sweep. With Z_p the pickup inductance used for the participation ratio is -Im Z_p(2 pi f_Hz)/omega unless L_p_H is also given.

None
Z_p ZFunc | None

See L_p_H.

None
Psi_SI float | Callable[[float], float]

the design's signal coupling [T H m^2]; the EMF amplitude is omega kappa_a Psi_SI. A callable Psi_SI(omega) -- e.g. pickup_coupling() built from the design's full-wave sweep -- makes the coupling frequency dependent.

0.0
C_F float | None

the tuning capacitance; None (default) tunes it to resonate at f_Hz.

None
C_par_F float

a parasitic capacitance across the pickup terminals -- e.g. the solver's results["pickup"]["port_capacitance"]["C_gap_F"], which sets the self-resonance f_SR = 1/(2 pi sqrt(L_p C_gap)). The loop is then not a plain series chain, and the reduction diagnostics (backaction_transfer_ratio, react_resid) show it.

0.0
L_lead_H float

the leads: either L_lead_H/R_lead_ohm, or lead_length_m with L_per_m [H/m] and R_per_m [ohm/m].

0.0
R_lead_ohm float

See L_lead_H.

0.0
lead_length_m float

See L_lead_H.

0.0
L_per_m float

See L_lead_H.

0.0
R_per_m float

See L_lead_H.

0.0
T_K float

temperatures: T_K is the default for every dissipative element; T_C_K, T_in_K, T_lead_K and T_2_K override it per element (the referred T_eff then obeys T_eff/Q = sum_k T_k/Q_k).

0.02
T_C_K float | None

See T_K.

None
T_in_K float | None

See T_K.

None
T_lead_K float | None

See T_K.

None
T_2_K float | None

See T_K.

None
M_H float | None

SQUID coupling: M_H directly; or k_in with L_squid_H (M = k sqrt(L_in L_squid)); or neither, in which case M is derived from xi (default: xi_opt at the resonance, which is what the optimal scan assumes). S_Phi [Wb^2 s] fixes the amplifier's flux noise; left out, it is derived from xi with the reference M = L_in (k = 1 to a SQUID of the input coil's inductance), or M = L_eff when there is no input coil. Only the absolute flux in Wb depends on that reference; Q, T_eff, xi, G-bar, N_V and the reach do not.

None
k_in float | None

See M_H.

None
L_squid_H float

See M_H.

0.0
S_Phi float | None

See M_H.

None

Readout dataclass

Readout(
    circuit: Circuit,
    squid: Squid,
    pickup: str = "pickup",
    Psi_SI: float | Callable[[float], float] = 0.0,
    L_p_H: float = 0.0,
    label: str = "readout",
    tuner: str | None = None,
)

A pickup + readout network, its noise budget and its reduction to the scan inputs.

Build one with series_readout() (DMRadio style), or assemble a Circuit yourself and name the pickup branch and the SQUID.

Methods:

Name Description
Psi_at

The pickup coupling Psi_SI [T H m^2] at omega.

flux

Flux coupled into the SQUID loop, Phi = M I_in [Wb].

H_signal

Phi_SQ per volt of pickup EMF [Wb/V].

Z_eff

Impedance in series with the pickup branch, including Z_p [ohm].

M_eff

Phi_SQ/I_pickup [H]: the mutual inductance an equivalent single loop needs.

resonance

Resonant angular frequency: the omega nearest the guess where Im Z_eff = 0.

tune

Set the tuning capacitor so that the loop resonates at f_Hz; returns C [F].

equivalent

Reduce the network to the single-pole detector the optimal scan assumes.

signal

Signal amplitudes at omega for an axion of coupling g.

noise_psd

Noise PSDs at omega, referred both to the SQUID flux [Wb^2 s] and to a series

sweep

Signal and noise versus frequency (one tuning): |Z_eff|, |H_signal|,

noise_curve

The exact N_V(omega) of this setting tabulated for the finite-band kernel.

kernel

Narrow-line matched-filter kernel at resonance, in SI:

analyze

Tune to f_Hz (if there is a tuning capacitor), then report everything:

match_xi

Scale M so that the readout coupling is xi (default xi_opt) at

summary
draw

Effective-circuit schematic of this readout (schemdraw; install axionmultiphysics[draw]):

Attributes:

Name Type Description
circuit Circuit
squid Squid
pickup str
Psi_SI float | Callable[[float], float]
L_p_H float
label str
tuner str | None

circuit instance-attribute

circuit: Circuit

squid instance-attribute

squid: Squid

pickup class-attribute instance-attribute

pickup: str = 'pickup'

Psi_SI class-attribute instance-attribute

Psi_SI: float | Callable[[float], float] = 0.0

L_p_H class-attribute instance-attribute

L_p_H: float = 0.0

label class-attribute instance-attribute

label: str = 'readout'

tuner class-attribute instance-attribute

tuner: str | None = None

Psi_at

Psi_at(omega: float) -> float

The pickup coupling Psi_SI [T H m^2] at omega.

A constant unless Psi_SI was given as a callable (a full-wave Psi(omega)); the axion line is narrower than omega/Q_axion ~ 10^-6, so one value per tuning is all the signal PSD needs.

flux

flux(sol: Solution) -> complex

Flux coupled into the SQUID loop, Phi = M I_in [Wb].

H_signal

H_signal(omega: float) -> complex

Phi_SQ per volt of pickup EMF [Wb/V].

Z_eff

Z_eff(omega: float) -> complex

Impedance in series with the pickup branch, including Z_p [ohm].

M_eff

M_eff(omega: float) -> complex

Phi_SQ/I_pickup [H]: the mutual inductance an equivalent single loop needs. Equals M whenever the pickup and the input coil carry the same current.

resonance

resonance(
    f_guess_Hz: float | None = None,
    span: float = 10.0,
    n_scan: int = 400,
) -> float

Resonant angular frequency: the omega nearest the guess where Im Z_eff = 0.

Scans [f_guess/span, f_guess*span] log-uniformly for a sign change and bisects in log omega. Default guess: the series resonance of the stored L and C.

tune

tune(
    f_Hz: float,
    branch: str | None = None,
    span: float = 1000000.0,
) -> float

Set the tuning capacitor so that the loop resonates at f_Hz; returns C [F].

The start value is the closed form C = -1/(omega X_rest) with X_rest the loop reactance with the capacitor shorted; bisection on Im Z_eff(2 pi f) = 0 then makes it exact for any network (a transformer-coupled secondary, a frequency-dependent Z_p, ...).

equivalent

equivalent(
    omega0: float | None = None,
    f_Hz: float | None = None,
    dlog: float = 1e-05,
    corr_tol: float = 0.01,
) -> dict

Reduce the network to the single-pole detector the optimal scan assumes.

Definitions (all exact for the series topology):

  • omega0 : Im Z_eff(omega0) = 0
  • R_eff : Re Z_eff(omega0)
  • L_eff : |dIm Z_eff/domega|/2 at omega0 (the reactance-slope inductance; = L_p + L_in + L_lead for a series loop)
  • Q_loaded : omega0 L_eff/R_eff
  • n_eff : from sum_k |H_k/H_s|^2 R_k (2 n_k + 1) = R_eff (2 n_eff + 1), so the referred thermal noise is matched exactly; T_eff/Q = sum_k T_k/Q_k classically
  • xi : 2 R_eff S_Phi/(hbar omega0 |M_eff|^2)
  • participation: L_p/L_eff, the amplitude factor; the scan rate carries its square

With a correlated SQUID (S_PhiJ != 0) the noise is reduced by completing the square; correlated_reduction_resid compares that pole with the exact N_V at the noise-doubling points and the call raises above corr_tol.

react_resid, R_noise_over_R_eff, backaction_transfer_ratio and reciprocity_resid are the diagnostics that say how good the reduction is: the first should be ~0, the next two ~1, the last ~0. R_noise_over_R_eff is the Nyquist identity referred with the pickup current (the flux referral is not an identity); reciprocity_resid is the asymmetry of the solved branch transfer matrix, and matrix_symmetry_resid the tautological assembled-matrix one. port_coupling is Q1/sqrt(1 + Q1^2) with Q1 = coupling_Q1, not 1.

signal

signal(
    omega: float,
    g_GeV: float = 1e-19,
    rho_GeV_cm3: float = 0.3,
) -> dict

Signal amplitudes at omega for an axion of coupling g.

The pickup EMF amplitude is |V| = omega kappa_a Psi_SI (with Phi_a = kappa_a Psi_SI). Returns the EMF, the pickup current, the flux into the SQUID in Wb and in Phi_0, and two ratios: Phi_SQUID_per_kappa_Wb_H and flux_gain = |Phi_SQ|/Phi_a. flux_gain is a resonant gain, not an efficiency: on resonance it is ~ Q M/L and is routinely much larger than 1. The dc flux-transfer efficiency of a non-resonant superconducting loop is instead M/(L_p + L_in), which flux_transformer_circuit() exercises.

noise_psd

noise_psd(omega: float) -> dict

Noise PSDs at omega, referred both to the SQUID flux [Wb^2 s] and to a series EMF in the pickup branch [V^2 s], so that s = S_Va/N_V exactly.

sweep

sweep(
    f_Hz: Sequence[float],
    g_GeV: float = 1e-19,
    rho_GeV_cm3: float = 0.3,
) -> dict[str, ndarray]

Signal and noise versus frequency (one tuning): |Z_eff|, |H_signal|, Phi_SQUID, and the EMF-referred N_V and its parts (the correlation part is 0 for an uncorrelated SQUID).

noise_curve

noise_curve(
    omega0: float | None = None,
    *,
    half_widths: float = 60.0,
    decades: float = 3.0,
    points_per_decade: float = 48.0,
    extra_omega: Sequence[float] | None = None,
    omega: Sequence[float] | None = None,
) -> dict[str, ndarray | float]

The exact N_V(omega) of this setting tabulated for the finite-band kernel.

The finite-band kernel needs N_V(omega) of each setting (one tuning capacitance, one coupling), not the single-pole reduction of it; this returns it on a grid that the C++ kernel_row_noise interpolates log-log. The grid is symmetric in the detuning,

``omega = omega0`` and ``omega0 +- hw x``,  ``x`` geometric over
``[10^-decades, half_widths]`` at ``points_per_decade`` points per decade,

with hw half the noise-doubling width of the equivalent pole, so it resolves the resonance (where N_V is flat, so the x < 10^-decades gap costs nothing) and the |Z|^2 ~ (2 L domega)^2 wings (where N_V is a power law, hence exact in log-log). half_widths = 60 covers the window the discrete sums use (+-40 half-widths truncate below 1e-5). The interpolation error of N_V is second order in the step, ~(ln 10/ppd)^2/8, so 48 points per decade keeps K (which goes as 1/N_V^2) accurate to a few times 10^-4; halve points_per_decade to check.

extra_omega merges extra frequencies into the grid. Use it for structure that does not scale with the detuning -- above all a self-resonance of Z_p (a pole at a fixed frequency), which a grid centred on omega_0 resolves only by accident.

Pass omega= to use your own grid instead. Returns omega_rad_s, f_Hz, N_V_V2_s and its components (thermal, backaction, imprecision, correlation), plus omega0_rad_s, f0_Hz and N_V_at_omega0_V2_s.

kernel

kernel(
    omega0: float | None = None,
    g_GeV: float = 1e-19,
    Q_axion: float = 680000.0,
    rho_GeV_cm3: float = 0.3,
    Theta: float = 2.71,
) -> dict

Narrow-line matched-filter kernel at resonance, in SI:

K = (pi/8) Q_a omega_a^3 Phi_a^4/N_V(omega_a)^2    [1/s]

(Phi_a in Wb, N_V in V^2 s; no hbar appears because Wb^4 s^-3/(V^2 s)^2 = s^-1). K is the Asimov TS gained per second of dwell at coupling g for an axion on resonance, and dwell_for_Theta_s = Theta/K is the time one tuning needs for a 95% limit there. Unlike the scan rate, K does not involve L: a bigger total inductance narrows the band without changing the on-resonance SNR.

analyze

analyze(
    f_Hz: float | None = None,
    tune: bool = True,
    g_GeV: float | None = None,
    m_a_eV: float | None = None,
    rho_GeV_cm3: float = 0.3,
    match_xi: bool = False,
    reach: bool = False,
    **reach_kw,
) -> dict

Tune to f_Hz (if there is a tuning capacitor), then report everything: the resonance, the loaded Q, the equivalent single-pole detector, the signal flux, the noise budget, the bandwidths and the scan inputs.

g_GeV/m_a_eV default to the QCD (DFSZ) line at the resonant frequency. match_xi=True re-scales M to xi_opt at the resonance (what the optimal scan assumes). reach=True also calls axionmultiphysics.scan.reach().

match_xi

match_xi(
    omega0: float | None = None, xi: float | None = None
) -> float

Scale M so that the readout coupling is xi (default xi_opt) at omega0; returns the new M [H]. S_Phi and S_J (hence eta_A) are amplifier properties and are left alone.

summary

summary(f_Hz: float | None = None, **kw) -> str

draw

draw(
    annotate: bool = True,
    *,
    f_Hz: float | None = None,
    title: str | None = None,
)

Effective-circuit schematic of this readout (schemdraw; install axionmultiphysics[draw]): the network exactly as built -- the pickup branch drawn as its EMF and series impedance (R_loss, L_p when Z_p has the MQS form, a Z_p(omega) box otherwise) -- with the SQUID coupled to its input coil by M. annotate=True adds the element values (resistances with their noise temperatures, C and tan delta, L_in, M), the SQUID's noise and xi against xi_opt at f_Hz (default: the resonance); annotate=False gives the symbolic figure. Returns a schemdraw.Drawing.

chain

chain(
    preset: str = "C1+low+RT",
    *,
    first: FirstStage | None = None,
    T2_K: float = 1.0,
    sign: float = 1.0,
    amplifier=None,
) -> Chain

A named chain from Ankel et al. (arXiv:2504.20398).

"C1": the TC first stage alone (no later stages; eta = 3.70, a lower bound). "C1+low|medium|high+RT|cryo": C1 + a 48x3 / 32x2 / 16x1 array at T2_K (Table II) + the RT preamps (XXF-1 below 50 MHz, the 300 MHz RT preamp above; Fig. 3 solid) or the CITLF2 cryogenic RF amplifier (specified for 5-500 MHz only; Fig. 3 dashed). first replaces C1 (e.g. squid.C1.at_eta(10)); amplifier replaces the preset's. sign is the open correlation sign s.

Chain dataclass

Chain(
    first: FirstStage,
    second: SecondStage | None = None,
    amplifier: OpAmpPreamp
    | CryoRFAmp
    | SwitchedPreamp
    | None = None,
    sign: float = 1.0,
    label: str = "chain",
)

First stage, optional second stage + amplifier, and the correlation sign s.

Later stages add uncorrelated imprecision only (their backaction on the first stage and on S_IV is neglected).

Methods:

Name Description
one_sided

One-sided PSDs referred to the FIRST-STAGE flux [Wb^2/Hz, A^2/Hz, Wb A/Hz].

eta

``eta(omega) = sqrt(S_VV S_IIsys - (Im S_IV)^2)/(hbar omega)

eta_uncorrelated

sqrt(S_Phi,tot S_J)/hbar: what eta would be with the correlation dropped.

eps_uc

eps_uc(omega) = M^2 S_IIsys/(2 L_sq) = S_Phi,tot/(2 L_sq) [J s].

eps_uc_over_hbar
input_referred

One-sided PSDs referred to the input coil coupled by M:

noise_temperature

Amplifier noise temperature [K] for a source of loop impedance Z (package

optimal_source_impedance

Complex source impedance minimizing T_n (package convention):

T_min_K

Minimum noise temperature at the optimal complex source: eta hbar omega/(2 k).

on_resonance

Real-source (on-resonance) match: the correlation drops out.

xi_opt

xi_opt = 2 eta^2/(2n+1+sqrt((2n+1)^2+8 eta^2)), with Bose-Einstein occupation n.

kappa_g2_scan

Scan-optimal global coupling:

M_scan_H

M = sqrt(kappa_g^2 L_sq L_tot) at the scan-optimal coupling [H].

squid

A axionmultiphysics.circuit.Squid with this chain's PSDs FROZEN at f0 (Foster

squid_for_resonator

squid() at the scan-optimal mutual inductance of a resonator (Q, L_tot, T).

draw

Block schematic of the chain (schemdraw; install axionmultiphysics[draw]): input coil,

summary

eta, eps_uc/hbar, the referred-noise breakdown and (with Q, T) the scan-optimal

Attributes:

Name Type Description
first FirstStage
second SecondStage | None
amplifier OpAmpPreamp | CryoRFAmp | SwitchedPreamp | None
sign float
label str
tau_s float

first instance-attribute

first: FirstStage

second class-attribute instance-attribute

second: SecondStage | None = None

amplifier class-attribute instance-attribute

amplifier: (
    OpAmpPreamp | CryoRFAmp | SwitchedPreamp | None
) = None

sign class-attribute instance-attribute

sign: float = 1.0

label class-attribute instance-attribute

label: str = 'chain'

tau_s property

tau_s: float

one_sided

one_sided(f_Hz) -> dict

One-sided PSDs referred to the FIRST-STAGE flux [Wb^2/Hz, A^2/Hz, Wb A/Hz].

S1_Phi_total = S1_Phi_TC + (dPhi1/dI |Phi_n2| /M_IN2)^2 (1 + omega^2 tau^2). The input-current PSD is multiplied by M^2 to refer it to flux. S1_PhiJ is signed (sign * 12 k T/V_Phi).

eta

eta(f_Hz)

eta(omega) = sqrt(S_VV S_IIsys - (Im S_IV)^2)/(hbar omega) = sqrt(S_Phi,tot S_J - S_PhiJ^2)/hbar (independent of M).

eta_uncorrelated

eta_uncorrelated(f_Hz)

sqrt(S_Phi,tot S_J)/hbar: what eta would be with the correlation dropped.

eps_uc

eps_uc(f_Hz)

eps_uc(omega) = M^2 S_IIsys/(2 L_sq) = S_Phi,tot/(2 L_sq) [J s].

eps_uc_over_hbar

eps_uc_over_hbar(f_Hz)

input_referred

input_referred(f_Hz, M_H: float) -> dict

One-sided PSDs referred to the input coil coupled by M: S_IIsys = S_Phi,tot/M^2 [A^2/Hz], S_VV = omega^2 M^2 S_J [V^2/Hz] and S_IV = <I_n V_ba*> = -i omega S_PhiJ [W/Hz], S_PhiJ signed (backaction EMF +i omega M J for exp(-i omega t)).

noise_temperature

noise_temperature(f_Hz, Z_ohm, M_H: float)

Amplifier noise temperature [K] for a source of loop impedance Z (package convention, Z = R - i X for an inductive loop), from the series-EMF referral 4 k T_n Re Z = S_VV + |Z|^2 S_IIsys + 2 omega S_PhiJ Im Z (S_PhiJ signed; the cross term is the correlation).

optimal_source_impedance

optimal_source_impedance(f_Hz, M_H: float)

Complex source impedance minimizing T_n (package convention): Im Z = -omega S_PhiJ/S_IIsys (S_PhiJ signed), Re Z = sqrt(S_VV/S_IIsys - (Im Z)^2).

T_min_K

T_min_K(f_Hz)

Minimum noise temperature at the optimal complex source: eta hbar omega/(2 k).

on_resonance

on_resonance(
    f_Hz, Q: float | None = None, M_H: float | None = None
) -> dict

Real-source (on-resonance) match: the correlation drops out.

k T_min = (1/2) omega sqrt(S_Phi,tot S_J) and T_min/SQL = sqrt(S_Phi,tot S_J)/hbar; with Q the matching coupling kappa_g^2 = sqrt(S_Phi,tot/S_J)/(L_sq Q) (1.2/Q for TC); with M the matching resistance R = omega M^2 sqrt(S_J/S_Phi,tot).

xi_opt

xi_opt(f_Hz, T_K: float)

xi_opt = 2 eta^2/(2n+1+sqrt((2n+1)^2+8 eta^2)), with Bose-Einstein occupation n.

kappa_g2_scan

kappa_g2_scan(f_Hz, Q: float, T_K: float)

Scan-optimal global coupling: kappa_g^2 = (1/Q)(eps_uc/hbar)[2n+1+sqrt((2n+1)^2+8 eta^2)]/eta^2 = 2 eps_uc/(hbar Q xi_opt), kappa_g^2 = M^2/(L_sq L_tot). Unconstrained: values > 1 are not attainable (see M_scan_H()).

M_scan_H

M_scan_H(f_Hz, Q: float, L_tot_H: float, T_K: float)

M = sqrt(kappa_g^2 L_sq L_tot) at the scan-optimal coupling [H].

This is an unconstrained optimum; kappa_g^2 = kappa^2 L_in/L_tot <= 1 is required, so this raises where the optimum asks for more (e.g. low Q at low frequency). With a known input coil the tighter bound is kappa^2 L_in/L_tot.

squid

squid(
    f0_Hz: float, M_H: float, input_coil: str = "L_in"
) -> Squid

A axionmultiphysics.circuit.Squid with this chain's PSDs FROZEN at f0 (Foster normalisation, S = S^(1)/2), including S_PhiJ = s S^(1)_PhiJ/2; eta_A is the correlated eta(f0). Across a noise band of width dw the frozen 1 + w^2 tau^2 is off by at most 2 dw/w (relative), < 1e-6 for C1+low+RT at 1 MHz and Q = 1e6.

squid_for_resonator

squid_for_resonator(
    f0_Hz: float,
    Q: float,
    L_tot_H: float,
    T_K: float,
    input_coil: str = "L_in",
) -> Squid

squid() at the scan-optimal mutual inductance of a resonator (Q, L_tot, T).

draw

draw(
    f_Hz: float | None = None,
    annotate: bool = True,
    title: str | None = None,
)

Block schematic of the chain (schemdraw; install axionmultiphysics[draw]): input coil, TC first stage, second-stage array and preamplifier, as present in this chain. With annotate each stage shows its parameters (L_sq, I0, R_j, T_j, V_Phi, eta_TC; N_ser x N_par, T_2, L_2, tau, M_IN2, flux gain; the amplifier's noise), and with f_Hz also eta(f), eps_uc/hbar and each stage's referred flux noise. Returns a schemdraw.Drawing.

summary

summary(
    f_Hz, Q: float | None = None, T_K: float | None = None
) -> dict

eta, eps_uc/hbar, the referred-noise breakdown and (with Q, T) the scan-optimal coupling, on a frequency grid; plain lists, ready for JSON.

benchmark

benchmark(ch: Chain | str, Q: float, T_K: float) -> dict

A noise benchmark for axionmultiphysics.scan.reach() with eta_A = eta(f) of the chain: scan.reach(Psi, L, squid.benchmark("C1+low+RT", Q=1e6, T_K=0.03)).

Cavity haloscopes

Everything in this section is beta, as are the related modules axionmultiphysics.cavity_xsec, axionmultiphysics.cavity_coupling and axionmultiphysics.haloscope_presets.

pillbox_design

pillbox_design(
    a: float = 0.1,
    L: float = 0.2,
    *,
    t: float | None = None,
    h: float | None = None,
    order: int = 2,
    wall_material: dict | None = None,
    fill: dict | None = None,
    Bz: float = 1.0,
    modes: int = 6,
    families=("TE", "TM"),
    target_f_Hz: float | None = None,
    domain_radius: float | None = None,
)

Closed right cylinder (inner radius a, length L, centred on z = 0) with a conducting wall of thickness t (default a/10) inside the closed outer sphere, a uniform axial background field Bz, and the cavity section. fill: material of the interior (e.g. {"kind": "linear", "eps_r": 2, "tan_delta": 1e-4}), vacuum by default. wall_material defaults to a perfect conductor without rf data, with cavity.allow_lossless_walls set (lossless on purpose; Q0 = Q_dielectric if any). domain_radius: the closed outer sphere (default 1.5x the device); the mesher caps elements at about pi R/96, so a larger sphere is needed for coarse cavity meshes (convergence studies).

coax_design

coax_design(
    a: float = 0.05,
    b: float = 0.2,
    L: float = 0.2,
    *,
    t: float | None = None,
    h: float | None = None,
    order: int = 2,
    wall_material: dict | None = None,
    Bz: float = 1.0,
    modes: int = 4,
    families=("TM",),
    target_f_Hz: float | None = None,
    domain_radius: float | None = None,
)

Coaxial cavity: conducting rod of radius a on the axis spanning both end caps, outer wall radius b, length L; the rod, caps and barrel form one conducting body.

pillbox_modes

pillbox_modes(
    a: float, L: float, f_max: float, eps_r: float = 1.0
) -> list[dict]

Analytic m = 0 modes of a closed cylinder below f_max: family ("TM" or "TE"), n, p, f_Hz, C (axial uniform B0, eps-weighted; 0 except TM0n0), G_ohm (Q R_s with one R_s on all walls; vacuum filling only).

surface_resistance

surface_resistance(
    rf: dict, f_Hz, *, flux_flow_part: bool = False
)

R_s(f) [ohm] of an rf block of the design format (any model: skin, power, table, anomalous, bcs, with an optional flux_flow term), evaluated by the same C++ code as the solvers (arguments checked by the design parser). Scalar or sequence f_Hz. With flux_flow_part=True returns (R_s, flux_flow part of R_s). The flux_flow part here needs an explicit B_T and uses the fixed orientation factor, or 1 (current perpendicular to the vortices, the upper bound); the cavity wall losses weight it per wall point by sin^2(J_rf, B0) instead.

sweep

sweep(
    build: Callable[[Any], Any],
    values: Sequence[Any],
    *,
    workdir: str | Path = "runs/cavity_sweep",
    probes=None,
    probe_n: int | Sequence[int] | None = None,
    families: Sequence[str] | None = None,
    solve_kw: dict | None = None,
    refine: int = 0,
    min_step: float | None = None,
    refine_crossings: bool = True,
    track_kw: dict | None = None,
    verbose: int = 0,
    map_fn: Callable | None = None,
) -> Tracking

Solve build(v) (a Design) for each value, collect the modes and their probe vectors, and track() them; returns the Tracking.

Probes: 2D/xsec: probes = (p0, p1) flat arrays, default a probe_n grid (40 x 40) over the union of the cavity's bounding boxes at the first and last values (two extra solves; stored in <workdir>/probes.json and reused); 3D: probes = a list of [x, y, z], default probe_points_3d() of the first design (probe_n = (nx, ny, nz)), written into every design's fullwave.field_probes. solve_kw: passed to Design.solve (e.g. mpi_ranks). Each step is cached in <workdir>/step_<hash of the design document>/ (track_step.npz/.json): a re-run reuses it. refine: rounds of bisection of Tracking.needs_refinement() intervals (numeric values; not below min_step; refine_crossings: also crossings, to tell true crossings from narrow avoided ones). map_fn: optional parallel map over the values of one round, e.g. concurrent.futures.ThreadPoolExecutor(n).map (the step function is a closure, so process pools cannot pickle it; 3D solves run as MPI subprocesses, so threads suffice).

track

track(
    steps: Sequence[ModeStep],
    *,
    accept: float = 0.5,
    good: float = 0.9,
    degenerate_rtol: float = 1e-06,
    freq_weight: float = 0.1,
    gap_factor: float = 3.0,
    reject_floor: float = 0.2,
    doublet: float = 100.0,
) -> Tracking

Link the modes of consecutive ModeStep s into adiabatic branches and classify the crossings (module docstring). Steps are sorted by value (numeric, incl. numpy scalars) or kept in order.

accept: minimum overlap of a link (below it the branch ends and a new one starts); good: links below it, a competing second overlap (above half the best and above 0.3), or a rejected best match with overlap above reject_floor mark the interval ambiguous; degenerate_rtol: relative splitting below which modes form a degenerate cluster (their frequency order is noise: no crossing is read from it); freq_weight: weight of the frequency-continuity term in the assignment cost; gap_factor: an avoided-crossing window extends from the gap minimum until the gap exceeds gap_factor x the minimum (or stops growing, or the common range ends: truncated); doublet: pairs split by less than doublet x degenerate_rtol on both sides of a frequency-order change or a gap minimum are treated as a near-degenerate doublet (no crossing, no avoided crossing, links flagged doublet_mixing instead of ambiguous).

Tracking

Tracking(
    steps,
    branches,
    crossings,
    intervals,
    warnings,
    options,
    aligned,
)

Result of track(): steps (sorted by value), branches (adiabatic), crossings (events: kind "crossing" / "avoided"), intervals (per consecutive pair of steps: values, minimum link overlap, ambiguous), warnings, options.

Methods:

Name Description
branch

A branch: which = a branch id, "max_C" (the branch through the largest-C mode of step at),

branch_table

Flat rows (one per branch point): branch, value, f_Hz, C, Q0, overlap,

diabatic

Character-following (diabatic) branches: copies of the adiabatic branches whose tails are permuted at each

needs_refinement

Intervals (lo, hi) of swept values to bisect: ambiguous links, crossings (crossings: a true crossing

summary
to_dict

JSON-ready record: branches (rows), crossings, intervals, warnings, options.

plot

Mode map: every mode as a dot coloured by color_by (C), the branches as lines (highlight: branch

Attributes:

Name Type Description
steps
branches
crossings
intervals
warnings
options

steps instance-attribute

steps = steps

branches instance-attribute

branches = branches

crossings instance-attribute

crossings = crossings

intervals instance-attribute

intervals = intervals

warnings instance-attribute

warnings = warnings

options instance-attribute

options = options

branch

branch(
    which: Any = "max_C",
    *,
    at: int = 0,
    diabatic: bool = False,
) -> Branch

A branch: which = a branch id, "max_C" (the branch through the largest-C mode of step at), "lowest" (through its lowest mode), or a callable row -> score (the branch through the highest-scoring mode of step at).

branch_table

branch_table(
    branches: Sequence[Branch] | None = None,
) -> list[dict]

Flat rows (one per branch point): branch, value, f_Hz, C, Q0, overlap, degenerate, ambiguous (the link to this point came through an ambiguous interval), step, mode.

diabatic

diabatic(
    events: Sequence[dict] | None = None,
) -> list[Branch]

Character-following (diabatic) branches: copies of the adiabatic branches whose tails are permuted at each avoided crossing (events: default all of kind "avoided"). A two-branch event swaps the two tails beyond x0; a multi-branch event applies its pair-minimum swaps in x order when they compose to its permutation (so the character is right between the minima too), else the permutation at x0. Within a few kappa/slope of a crossing every eigenmode is a mixture, so the diabatic quantities there are those of mixed modes.

needs_refinement

needs_refinement(
    *, crossings: bool = True, min_points: int = 3
) -> list[tuple]

Intervals (lo, hi) of swept values to bisect: ambiguous links, crossings (crossings: a true crossing and an avoided crossing narrower than the step look alike) and avoided crossings with fewer than min_points steps inside the fit window. Non-numeric sweeps return [].

summary

summary() -> str

to_dict

to_dict() -> dict

JSON-ready record: branches (rows), crossings, intervals, warnings, options.

plot

plot(
    path: str | Path | None = None,
    *,
    ax=None,
    quantity: str = "f_Hz",
    scale: float = 1e-09,
    color_by: str = "C",
    branches: Sequence[Branch] | None = None,
    label: str = "f [GHz]",
    xlabel: str = "swept value",
    highlight: Sequence[int] = (),
    vmax: float | None = None,
)

Mode map: every mode as a dot coloured by color_by (C), the branches as lines (highlight: branch ids drawn thick), avoided crossings as open circles and crossings as crosses.

Cavity dataclass

Cavity(
    B_T: object,
    V_m3: object,
    C: object,
    Q0: object,
    beta: object = 2.0,
    eta: object = 1.0,
    label: str = "",
)

One cavity mode as seen by the sensitivity layer. Any field may be a callable of f [Hz] (e.g. an interpolant of the FEM per-mode outputs C(f), Q0(f) along a tuning branch).

Methods:

Name Description
at
from_QL

Build from a loaded Q: Q0 = Q_L (1 + beta).

Attributes:

Name Type Description
B_T object
V_m3 object
C object
Q0 object
beta object
eta object
label str

B_T instance-attribute

B_T: object

V_m3 instance-attribute

V_m3: object

C instance-attribute

C: object

Q0 instance-attribute

Q0: object

beta class-attribute instance-attribute

beta: object = 2.0

eta class-attribute instance-attribute

eta: object = 1.0

label class-attribute instance-attribute

label: str = ''

at

at(f_Hz: float) -> dict

from_QL classmethod

from_QL(B_T, V_m3, C, Q_L, beta, **kw) -> 'Cavity'

Build from a loaded Q: Q0 = Q_L (1 + beta).

Receiver dataclass

Receiver(
    T_cav_K: float = 0.0,
    N_A: float | None = None,
    T_A_K: float | None = None,
    T_sys_K: float | None = None,
    T_in_K: float | None = None,
    n_cav: float | None = None,
    squeeze_dB: float = 0.0,
    squeeze_eff: float = 1.0,
    eta_out: float = 1.0,
    phase_sensitive: bool = False,
    eta_snr: float = 1.0,
    label: str = "",
)

Noise model of a single-port haloscope receiver.

Exactly one way of fixing the noise level:

  • T_sys_K: a total system noise temperature as quoted by the experiment, referred to the cavity port (flat in detuning; k_B T_sys per Hz). Overrides the physical noise model; only eta_snr still applies (eta_out must stay 1).
  • otherwise the physical model, in quanta per Hz referred to the amplifier input:

    N_sys(delta) = k [ eta_out N_port(delta) + (1 - eta_out)(n_in + 1/2) + N_A ], N_port = |chi|^2 S_cav (n_in + 1/2) + (1 - |chi|^2)(n_c + 1/2),

|chi|^2 = ((beta - 1)^2 + x^2)/((beta + 1)^2 + x^2) the cavity reflection, x = 2 Q0 delta/f, n_c the cavity-bath occupation (n_cav if given, else n_th(T_cav_K)), n_in = n_th(T_in_K) the occupation of the termination incident on the port AND of the transmission-loss baths (all at the fridge temperature; T_in_K defaults to T_cav_K), S_cav the squeezing delivered to the cavity (1 without squeezing), k = 2 for a phase-sensitive readout, else 1. This is 2301.09721 Eq. A4 (with alpha = eta_out, rho = squeeze_eff, G_S = 1/G_s). With an isolator at the cavity temperature and no squeezing, N_sys = k(n_c + 1/2 + N_A) is flat and independent of beta. T_in_K = 0 mimics "no isolator, cold amplifier input" (Kim et al. 2020 Sec. 3).

eta_out (HAYSTAC's alpha, 2301.09721 Table II): power transmission between the cavity port and the amplifier. It attenuates the axion signal (scan_rate and the limits multiply P by it) and replaces a fraction 1 - eta_out of the cavity output by fresh noise at n_in. N_A is then the added noise referred to the AMPLIFIER input (HAYSTAC's N_a).

N_A (quanta, excludes the input 1/2: SQL = 0.5) or T_A_K (classical HEMT noise temperature, N_A = k T_A/hf).

phase_sensitive=True (HAYSTAC phase II squeezed-state receiver, SSR): one quadrature is measured; the axion's random-phase signal puts half its power there, so the noise is reported in phase-insensitive-equivalent quanta N_sys = 2 N_quad, with N_quad counted so that vacuum is 1/2 (the convention of the corrected HAYSTAC analysis, arXiv:2301.09721 Sec. III, Eqs. A1, A3-A6). An ideal phase-sensitive amplifier without squeezing therefore gives N_sys = 1, the same as the SQL phase-insensitive one (no free lunch). N_A is then the single-quadrature added noise (HAYSTAC's N_a).

Squeezing convention (Malnou et al. 2019, arXiv:1809.06470): squeeze_dB is the squeezer's own one-quadrature gain G_s = 10^(dB/10) (noise reduction at the squeezer OUTPUT, before any loss). squeeze_eff is the squeezer -> cavity transmission eta_1 (HAYSTAC's rho = (alpha rho)/alpha), so S_cav = eta_1/G_s + 1 - eta_1 (2301.09721 Eq. 6 at the cavity). A squeezing MEASURED at the receiver output already contains N_A and eta_out; never enter it as squeeze_dB -- convert it with squeezer_gain_dB(), which removes N_A (otherwise the added noise is counted twice). The squeezer and the measured quadrature are centred on the cavity frequency, so chi(delta) multiplies both sideband quadratures by the same factor (chi(-delta)* = chi(delta)): no rotation of the ellipse, anti-squeezing never enters. This agrees with Malnou et al. Eq. 2. eta_snr multiplies the SNR (analysis efficiency, < 1), so the rate goes as eta_snr^2.

Methods:

Name Description
amp_N
measured_S

Output-referred off-resonance squeezing sigma^2_on/sigma^2_off INCLUDING N_A (what an

N_sys

System noise in quanta per Hz at cavity detuning delta = f - f_c, referred to the

T_sys

k_B T_sys = h f N_sys [K] (amplifier-input referred; divide by eta_out for the cavity port).

Attributes:

Name Type Description
T_cav_K float
N_A float | None
T_A_K float | None
T_sys_K float | None
T_in_K float | None
n_cav float | None
squeeze_dB float
squeeze_eff float
eta_out float
phase_sensitive bool
eta_snr float
label str
delivered_S float

Squeezing delivered to the cavity, S_cav = eta_1/G_s + 1 - eta_1 (2301.09721 Eq. 6 with

output_S float

Off-resonance squeezing at the amplifier input, s = 1 - eta + eta/G_s with

flat bool

True when N_sys does not depend on detuning or beta.

T_cav_K class-attribute instance-attribute

T_cav_K: float = 0.0

N_A class-attribute instance-attribute

N_A: float | None = None

T_A_K class-attribute instance-attribute

T_A_K: float | None = None

T_sys_K class-attribute instance-attribute

T_sys_K: float | None = None

T_in_K class-attribute instance-attribute

T_in_K: float | None = None

n_cav class-attribute instance-attribute

n_cav: float | None = None

squeeze_dB class-attribute instance-attribute

squeeze_dB: float = 0.0

squeeze_eff class-attribute instance-attribute

squeeze_eff: float = 1.0

eta_out class-attribute instance-attribute

eta_out: float = 1.0

phase_sensitive class-attribute instance-attribute

phase_sensitive: bool = False

eta_snr class-attribute instance-attribute

eta_snr: float = 1.0

label class-attribute instance-attribute

label: str = ''

delivered_S property

delivered_S: float

Squeezing delivered to the cavity, S_cav = eta_1/G_s + 1 - eta_1 (2301.09721 Eq. 6 with eta = squeeze_eff); 1 without squeezing.

output_S property

output_S: float

Off-resonance squeezing at the amplifier input, s = 1 - eta + eta/G_s with eta = squeeze_eff * eta_out (2301.09721 Eq. 6, noiseless amplifier).

flat property

flat: bool

True when N_sys does not depend on detuning or beta.

amp_N

amp_N(f_Hz)

measured_S

measured_S(f_Hz) -> float

Output-referred off-resonance squeezing sigma^2_on/sigma^2_off INCLUDING N_A (what an experiment measures, 2301.09721 Sec. II A); equal temperatures assumed.

N_sys

N_sys(
    f_Hz,
    delta_Hz=0.0,
    Q0: float | None = None,
    beta: float | None = None,
)

System noise in quanta per Hz at cavity detuning delta = f - f_c, referred to the amplifier input (= the cavity port when eta_out = 1).

T_sys

T_sys(f_Hz, delta_Hz=0.0, Q0=None, beta=None)

k_B T_sys = h f N_sys [K] (amplifier-input referred; divide by eta_out for the cavity port).

scan_rate

scan_rate(
    f_Hz: float,
    cav: Cavity,
    rx: Receiver,
    *,
    g_GeV: float | None = None,
    snr: float = 5.0,
    Q_a: float | None = None,
    rho_GeV_cm3: float = 0.45,
    model: str = "DFSZ",
    prefactor: str = "optimal",
) -> float

Scan rate df/dt [Hz/s] reaching snr on an axion of coupling g.

Optimal weighting, dense steps: df/dt = eta_snr^2 int d delta [P(delta)/(h f N_sys(delta))]^2 / (SNR^2 Delta f_eff), Delta f_eff = f/Q_a, P = eta eta_out beta/(1+beta) Q_L P_coef L(delta). Q_a is the radiometer quality factor (f/Delta f_eff); None -> SHM, 6.78e5. Flat noise: (pi/4) (eta_c P_coef)^2 Q_L Q_a / (SNR k T_sys)^2, i.e. ~ g^4 B^4 V^2 C^2 Q_L/T^2. The separation of line shape and cavity response is exact in the dense-scan limit for any Q_L/Q_a, so there is no Q_L Q_a/(Q_L+Q_a) saturation here (cf. scan_rate_kim2020()).

prefactor="haystac": replace pi/4 by the 4/5 of 1611.07123 Eq. 5 (squared Lorentzians summed over steps of ~Delta nu_c/2, boxcar bins); use it with Q_a ~ 1e6. g_GeV None -> the benchmark model coupling (haloscope convention).

beta_opt

beta_opt(
    f_Hz: float, cav: Cavity, rx: Receiver, **kw
) -> float

Coupling maximising scan_rate() at fixed Q0 (numerical; = 2 for flat noise).

g_limit_scan

g_limit_scan(
    f_Hz,
    cav: Cavity,
    rx: Receiver,
    *,
    rate_Hz_s=None,
    tau_step_s=None,
    df_step_Hz=None,
    snr: float = 5.0,
    Q_a: float | None = None,
    rho_GeV_cm3: float = 0.45,
    prefactor: str = "optimal",
)

Excluded |g_agg| [GeV^-1] at f for a scan at rate r = df_step/tau_step.

SNR scales as g^2 at fixed scan rate, so g_lim = g_ref (r/r_ref(g_ref))^(1/4) where r_ref is scan_rate() at g_ref for the target SNR. f_Hz may be an array.

SRF heterodyne

Beta: axionmultiphysics.srf and axionmultiphysics.heterodyne.

elliptical_cell_design

elliptical_cell_design(
    cell: dict | None = None,
    *,
    axial_factor: float = 0.86,
    scale: float = 1.0,
    tube_radius: float | None = None,
    tube_length: float = 0.1,
    h: float | None = None,
    wall_size: float | None = None,
    order: int = 2,
    modes: int = 8,
    families=("TE", "TM"),
    target_f_Hz: float | None = 1420000000.0,
    wall_material: dict | None = None,
    t: float | None = None,
    angle_tol: float = 0.01,
    wall: str = "smooth",
)

Axisymmetric design of the elliptical cell (elliptical_cell_contour) inside a conducting wall of thickness t (default 5 % of the equator radius): cavity region (mesh_size h, default Req/30) and wall surface mesh size wall_size (default h/3; the mesher also refines by curvature). With wall="polygon" the wall is the polyline (vertex spacing <= wall_size, denser near the iris by angle_tol, see elliptical_cell_contour()) and the mesh follows its vertices. target_f_Hz is scaled by 1/scale. wall_material as in axionmultiphysics.cavity.pillbox_design() (default lossless, G still reported). The design carries the contour in design.srf_contour (used by figures_of_merit()). wall: "smooth" (default) meshes the exact wall (elliptical arcs, contour shape) with curved second-order elements on it; "polygon" meshes the polyline (angle_tol), whose vertices are weak field singularities (docs/srf/README.md, "Wall representation").

tune_degeneracy

tune_degeneracy(
    pump: str = "TM020",
    signal: str = "TE011",
    *,
    cell: dict | None = None,
    bracket=(0.8, 0.92),
    tol: float = 1e-05,
    design_kw: dict | None = None,
    workdir=None,
    verbose: bool = False,
) -> dict

Axial factor s (scaling the half-cell length and the axial semi-axes) at which the 2D pump and signal frequencies coincide: secant/Brent on Delta f(s) = f_signal - f_pump, each evaluation one axisymmetric solve. Every evaluation re-meshes, so Delta f(s) carries mesh noise at the level of the discretization error (a few kHz at h = Req/40, order 3, i.e. ~1e-5 in s): a tol below that only converges onto the noisy root. Returns {"axial_factor", "f_Hz", "history": [(s, f_pump, f_signal)], "design_kw"}.

find_mode

find_mode(
    res,
    name: str,
    contour: dict | None = None,
    labels: list | None = None,
) -> dict

The cavity_modes() row labelled name (e.g. "TM020") by classify_modes(); error if absent or ambiguous.

figures_of_merit

figures_of_merit(
    res,
    pump="TM020",
    signal="TE011",
    *,
    contour: dict | None = None,
    subdiv: int = 4,
    with_fields: bool = False,
) -> dict

Heterodyne figures of merit of an axisymmetric cavity result (see the module docstring for definitions).

pump/signal: mode labels for find_mode(), or rows of res.cavity_modes(). contour: the cell contour (design.srf_contour; default res.design.srf_contour): mode labels, equator and A. Wall peaks: the solver's peak_wall_fields, the largest normal |E| and tangential |B| over the Gauss points of the wall faces evaluated in the cavity element (never at mesh vertices), the same field the 3D peaks estimate (figures_of_merit_3d()); face-rms variants and the tangential |E| (a PEC check) too. The peak ratios use the solver's B_rms, the equator values the lattice B0 (they agree to ~3e-5). Integrals: sub-triangle lattice of each element (subdiv) with the fields linear on each sub-triangle (converges as (h/subdiv)^2; the eigenvectors themselves converge with the mesh). Returns xi (pump, signal), f, the frequency splitting, eta_10, B_pk/B0 and E_pk/(c B0) of the pump (and of the signal, normalized by the signal's own rms B), A/V^(2/3), G (solver), V, and with with_fields the mode fields (cavity_mode_field dicts) under "fields".

SRFGeometry dataclass

SRFGeometry(
    xi: float,
    eta: float,
    G_pump_ohm: float,
    G_signal_ohm: float,
    Bpk_over_B0: float,
    area_coeff: float,
    Epk_over_cB0: float | None = None,
    name: str = "",
    source: str = "",
)

Scale-free figures of merit of a cavity and its (pump, signal) mode pair.

xi: omega_0 = xi c V^(-1/3) (angular frequency; f_0 V^(1/3)/c is xi/2pi) eta: overlap eta_10 (C_01 = eta^2), NOT its square G_pump_ohm, G_signal_ohm: geometry factors in ohm, G = omega mu0 int|H|^2 dV / int|H_t|^2 dA, Q = G/R_s (the dimensionless natural-unit G times Z0 = 376.73 ohm) Bpk_over_B0: peak wall magnetic field of the pump / B_0 (B_0 = spatial RMS, peak in time), i.e. the largest |B| anywhere on the wall area_coeff: A_cav / V^(2/3) (>= 4.836, the sphere) Epk_over_cB0: peak wall electric field of the pump / (c B_0), dimensionless, informational: the pump's peak surface E is Epk_over_cB0 * c * B_0 (NOT times c B_pk).

The constructor validates every value (finite, in a physically possible range, and in the units above) and raises ValueError naming the field, so that a slipped convention (eta^2 for eta is the one it cannot catch; xi without 2 pi, G in natural units, B0/B_pk inverted, an impossible area) fails loudly instead of returning a plausible-looking design.

Methods:

Name Description
f0_Hz
V_m3
area_m2
Epk_V_per_m

Peak surface electric field of the pump [V/m] at volume-rms field B0_T: Epk_over_cB0 c B0.

from_modes

Build from the eigenmode side's figures of merit.

Attributes:

Name Type Description
xi float
eta float
G_pump_ohm float
G_signal_ohm float
Bpk_over_B0 float
area_coeff float
Epk_over_cB0 float | None
name str
source str

xi instance-attribute

xi: float

eta instance-attribute

eta: float

G_pump_ohm instance-attribute

G_pump_ohm: float

G_signal_ohm instance-attribute

G_signal_ohm: float

Bpk_over_B0 instance-attribute

Bpk_over_B0: float

area_coeff instance-attribute

area_coeff: float

Epk_over_cB0 class-attribute instance-attribute

Epk_over_cB0: float | None = None

name class-attribute instance-attribute

name: str = ''

source class-attribute instance-attribute

source: str = ''

f0_Hz

f0_Hz(V_m3)

V_m3

V_m3(f0_Hz)

area_m2

area_m2(V_m3)

Epk_V_per_m

Epk_V_per_m(B0_T)

Peak surface electric field of the pump [V/m] at volume-rms field B0_T: Epk_over_cB0 c B0.

from_modes classmethod

from_modes(
    modes: dict, *, bpk: str = "wall", **kw
) -> "SRFGeometry"

Build from the eigenmode side's figures of merit.

modes is either the output of axionmultiphysics.srf.figures_of_merit() (keys xi_pump, eta_10, G_pump_ohm, G_signal_ohm, Bpk_over_B0, B_equator_over_B0, A_over_V23, Epk_over_cB0) or a dict with this class's own field names. bpk picks the peak-field value:

  • "wall" (default): the largest pump |B| anywhere on the wall, 1.464 for the Project X cell shortened by 0.86 (iris-side lobe). This is the peak wall magnetic field, to which the field limit applies.
  • "equator": DIAGNOSTIC ONLY, the pump |B| at the equator (1.404). It is not the peak wall field: a design built on it runs the iris-side wall 4.3 % above the stated field limit. For an own-key dict it needs a B_equator_over_B0 entry.

kw overrides any field. The result is checked by SRFGeometry.

scan_rate

scan_rate(
    f_a_Hz,
    f1_Hz,
    V_m3,
    B0_T,
    eta,
    Q_i,
    A,
    n_i,
    *,
    beta=None,
    tau: float = 1.0,
    n_e=0.0,
    target: Target = DEFAULT_TARGET,
    g_GeV=None,
)

Weak-signal dense-scan rate d(nu_1 - nu_0)/dt [Hz/s] (the angular-frequency rate divided by 2 pi):

d(omega_1 - omega_0)/dt = (pi^2/32) (Q_axion/Theta_95) g^4 rho^2 eta^4 B_0^4 V^2 Q_i
                          / (m_a omega_1^3) x G-bar_SRF(beta).

In SI with P0 = g^2 rho eta^2 B_0^2 V/omega_1 [W] (= 4 P_sig/Q_1) this is (pi^2/32)(Q_a/Theta) P0^2 Q_i G-bar/(hbar^2 omega_a omega_1). beta None -> beta_opt() at every mass. Vectorised over f_a (and any broadcastable argument).

required_volume

required_volume(
    sc: ScenarioA,
    target: Target = DEFAULT_TARGET,
    *,
    omega1: str = "shifted",
    n: int = 256,
    adiabatic_eps: float | None = None,
    guard_Hz: float = 0.0,
) -> float

Smallest V [m^3] whose optimal scan covers the target band in the live time, with omega_0 = xi c V^(-1/3) and the coupling optimised at every mass. omega1: "shifted" (omega_1 = omega_0 + m_a, the definition) or "pump" (omega_1 = omega_0). adiabatic_eps: None (weak-signal optimum, no schedule constraint) or eps of tracking_rate() (e.g. 0.1).

guard_Hz: the resonance sweep is extended by this much beyond both band ends. The dense-scan rate assumes every target mass sees the whole detuning response and its whole (one-sided, upward) SHM line; without a guard the masses within ~ (Delta_c + nu_a v^2/2) of the ends are under-exposed (at 1 MHz an unguarded end collects only a few % of the statistic). The default, 0, integrates over the band only; 20 Hz guards raise V by 1.3e-4 here because the rate at the ends is fast.

Touchstone (S-, Y- and Z-parameters)

write_touchstone

write_touchstone(
    results: Mapping[str, Any],
    path: str | Path,
    kind: str = "S",
    z0: Any = DEFAULT_Z0,
    dense: bool = False,
    *,
    surface_losses: bool = False,
    passivity_tol: float = PASSIVITY_TOLERANCE,
) -> dict[str, Any]

Write the port parameters of a full-wave sweep as a Touchstone file (.sNp).

results: a results document (Results.data or results.json). kind: "S" (default), "Z" or "Y"; z0: reference resistance (ohm; one for every port, or for S one per port, written as a v1.1 option line); dense: the adaptive model's dense curve instead of the solved rows; surface_losses: add the resistive part of the perturbative conductor surface loss (port_parameters()). The values are in the engineering convention e^{+j omega t} (the engine's Z is conjugated), sorted by frequency, with a comment block giving the source, the port order and polarity, and the checks. Passivity violations (sigma_max(S) > 1 + passivity_tol) are warned about and written as computed. Returns the report of write_touchstone_data() plus source, Re_Z_unresolved_Hz and surface_loss_beyond_perturbation_Hz; its warnings holds every warning raised on the way.

read_touchstone

read_touchstone(
    path: str | Path, nports: int | None = None
) -> dict[str, Any]

Read a Touchstone v1.0/v1.1 file (.sNp) with S-, Z- or Y-parameters.

nports defaults to the N of the extension. Handles the frequency units (Hz, kHz, MHz, GHz), the formats RI, MA and DB, the v1 defaults (# GHz S MA R 50), values spread over any number of lines, the 2-port order N11 N21 N12 N22, a v1.1 per-port R r1 ... rn (S-parameters only) and a 2-port file's trailing noise parameters (checked and ignored; noise_rows_ignored). Refuses data before the option line, Touchstone v2 keywords and H/G parameters.

Returns f_Hz, kind, z0_ohm (a float, or a list per port), data (n_f x n x n as stored but de-normalised: Z in ohm, Y in siemens), S and Z (both engineering convention, e^{+j omega t}), ports (names from an axionMultiPhysics port-order comment, else port_k), comments, option_line and noise_rows_ignored. S is always present (stored S, or converted where it exists); Z (and S of a Y file) is NaN at the frequencies where it does not exist (an open, an ideal thru, a singular Y), with a warning naming the file and the frequencies (Z_undefined_Hz, S_undefined_Hz).

port_parameters

port_parameters(
    results: Mapping[str, Any],
    *,
    dense: bool = False,
    surface_losses: bool = False,
) -> dict

The port impedance matrix of a full-wave sweep, sorted by frequency, in the engineering convention.

results: a results document (Results.data or a loaded results.json) with fullwave.sweep. dense=False takes the solved rows (Z_matrix_re_ohm/Z_matrix_im_ohm, or Z_re_ohm/Z_im_ohm for a one-port 2D sweep); dense=True the adaptive sweep's dense model curve (fullwave.adaptive.dense, axionmultiphysics.circuit.fullwave_dense()). surface_losses=True adds the resistive part of the perturbative conductor surface loss of the solved rows, which Z does not contain (docs/physics/ fullwave_surface_losses.md): R_loss_ohm to a one-port's Re Z; for a multiport R_loss_matrix_ohm, which is the impedance perturbation only for in-phase port fields, so it is refused when that matrix has an imaginary part above 1e-6 of its norm or Z has a resistive part (radiation or bulk loss). The surface reactance (internal inductance, kinetic inductance) is not added. Rows where R_loss/|X| exceeds SURFACE_LOSS_PERTURBATION_LIMIT are warned about and listed (the perturbation is not accurate there).

Returns f_Hz, Z (n_f x n x n, ohm, e^{+j omega t}), ports (names in matrix order; port 1 is the pickup), port_details (polarity and terminals), source, notes (lines for a file header), Re_Z_unresolved_Hz (solved rows whose Re Z the solve's residual does not resolve; for dense=True the rows the model was fitted to), Re_Z_unresolved (per output frequency: flagged itself, or for the dense curve between flagged neighbouring solves), Z_relative_error (per output frequency, the estimated normwise relative error of Z: the rows' error indicator, signed where given, plus the solve's residual; the dense curve's model error; NaN when not known), Z_relative_error_source, Z_relative_error_kind ("normwise" for the rows; "proportional" for the dense curve, whose barycentric model shares one denominator over all entries, so that its error near a pole moves the entries together) and surface_loss_beyond_perturbation_Hz.

z_to_s

z_to_s(
    Z: Any, z0: Any = DEFAULT_Z0, *, convention: str
) -> ndarray

Scattering matrix S = (z - 1)(z + 1)^-1, z = D^-1 Z D^-1, D = diag(sqrt(z0)).

Z: an n x n impedance matrix or a stack (... x n x n; a 1-D array is a one-port sweep) in ohm. z0: the real positive reference impedance, one value or one per port (ohm). convention: the time convention of Z ("axionmultiphysics" or "engineering", see to_engineering()). The result is in the engineering convention e^{+j omega t}, with the shape of Z (n_f x 1 x 1 for a 1-D input). Raises a ValueError naming the matrices where Z + z0 is singular (e.g. Z = -z0 for a one-port).

COMSOL

The import (axionmultiphysics.comsol_import) is beta; the export is not.

export_comsol

export_comsol(
    source,
    out: str | Path,
    *,
    format: str = "mphtxt",
    order: int = 1,
    workdir: str | Path | None = None,
    mesher: str = "",
    verbose: int = 0,
    class_name: str | None = None,
    feature_angle: float | None = None,
    physics: str = "none",
) -> dict

Export an axionMultiPhysics geometry or mesh to COMSOL.

source: a Design, a design dict, a design .json, an axmp-mesher .msh or a run directory (axmp solve -o DIR / axmp mesh -o DIR: holds mesh.msh or mesh3d.msh and design.json).

format: * "mphtxt" -- COMSOL mesh with named selections (designs are meshed first with axmp mesh into workdir, default <out>_mesh/); order=2 keeps second-order nodes. * "java" -- COMSOL Java API model that rebuilds the geometry (needs the compiled core for designs, or a run directory with mesh*_in.json). * "step" -- 3D designs: the OCC solids as STEP via axmp-mesher, plus <out>.solids.json.

physics: "none" (default: geometry and selections only) or "fullwave" (3D designs with a port pickup): the Java model, or for mphtxt the Import_<name>.java program, also gets the Electromagnetic Waves physics, materials, lumped ports, the axion source, a Frequency study and the Z/V exports (axionmultiphysics.comsol_physics). The design is needed: a design, a design .json or a run directory with design.json.

A model document (beta: a design with a top-level physics key, given directly, as a .json or as the design.json of a run directory) is refused with model.em_only_operation before anything is resolved, meshed or written: the export builds an electromagnetic COMSOL model.

Returns a summary dict (files written, entity counts, selections, approximations).

import_comsol

import_comsol(
    path,
    out: str | Path | None = None,
    *,
    route: str = "mesh",
    allow_partial: bool = False,
    frequencies=None,
    max_frequencies: int = 20,
    study: str | None = None,
    order: int | None = None,
    physics: str | None = None,
    toward=None,
    write: bool = True,
    curved: bool = True,
    mesh_resource: str | None = None,
    axisymmetric: bool | None = None,
)

Import path (a COMSOL .mph) and return an axionmultiphysics.Design.

out is the design JSON to write (default <model stem>_axmp/design.json next to the model's name in the current directory); the mesh, its info file and import_report.md/.json go next to it. route is "mesh", "replay" or "auto" (replay when the whole geometry sequence is supported, else mesh). Raises ImportError_ when something that changes the results cannot be mapped, unless allow_partial. The report is attached as design.import_report.

Field maps (beta)

Per-region maps of the static field for particle transport, written by Results.export_field_map (see the field-map guide).

load

load(path: str | Path) -> FieldMap

Read a map directory written by export_field_map or write_map.

write_map

write_map(
    path: str | Path,
    patches: Sequence[Mapping[str, Any]],
    *,
    outside: str = "refuse",
) -> FieldMap

Write a map from nodal values: each patch is a dict with name, kind (1 or 3), origin, spacing, B (kind 1: shape (n_r, n_z, 3) holding (B_r, B_z, B_phi); kind 3: (n_x, n_y, n_z, 3) holding (B_x, B_y, B_z); T) and, for kind 3, an optional transform (4 x 4 placement, global = T @ local). The manifest's source is {"type": "nodal_values"} and the patches carry no error record.

FieldMap

FieldMap(path: str | Path)

A field map read from a directory (load): path, manifest (the parsed manifest.json), patches (list of Patch in manifest order), patch(name), evaluate(points, patch=None) and outside_calls (points refused as zero under outside: "zero").

Methods:

Name Description
patch
evaluate

B [T] at Cartesian points (n, 3) [m], shape (n, 3). patch names the patch whose grid serves the points

Attributes:

Name Type Description
path
manifest
outside
outside_calls
patches

path instance-attribute

path = Path(path)

manifest instance-attribute

manifest = json.loads(mf.read_text())

outside instance-attribute

outside = self.manifest.get('outside', 'refuse')

outside_calls instance-attribute

outside_calls = 0

patches instance-attribute

patches = [
    Patch(self, rec, np.load(self.path / rec["file"]))
    for rec in self.manifest["patches"]
]

patch

patch(name: str) -> Patch

evaluate

evaluate(points, patch: str | None = None)

B [T] at Cartesian points (n, 3) [m], shape (n, 3). patch names the patch whose grid serves the points (required when the map has more than one patch). A point outside that patch's box raises AxionMultiPhysicsError with code fieldmap.outside_map when the map's outside is "refuse"; with "zero" it gets B = 0 and is counted in outside_calls. The evaluator never decides the region: the transport does, by the volume the point is in.

Patch

Patch(owner: 'FieldMap', record: dict, B: ndarray)

One patch of a map: name, kind (1 or 3), regions, origin, spacing, shape (nodes per axis), B (the written array, read only), record (its manifest entry), evaluate(points) (Cartesian, as FieldMap.evaluate) and evaluate_native(coords) (kind 1: (r, z) -> (B_r, B_z, B_phi); kind 3: the patch frame's (x, y, z) -> (B_x, B_y, B_z)).

Methods:

Name Description
evaluate_native
evaluate

Attributes:

Name Type Description
record
name
kind
regions
origin
spacing
shape
margin
B

record instance-attribute

record = record

name instance-attribute

name = record['name']

kind instance-attribute

kind = int(record['kind'])

regions instance-attribute

regions = list(record.get('regions', []))

origin instance-attribute

origin = [float(x) for x in record['origin']]

spacing instance-attribute

spacing = [float(x) for x in record['spacing']]

shape instance-attribute

shape = tuple(int(n) for n in record['shape'])

margin instance-attribute

margin = [
    float(x) for x in record.get("margin", self.spacing)
]

B instance-attribute

B = B

evaluate_native

evaluate_native(coords)

evaluate

evaluate(points)

recovered_field

recovered_field(
    results,
    field_map: FieldMap | str | Path,
    patch: str,
    points,
)

The recovered field B* of patch at points in the patch's native coordinates ((n, 2) (r, z) for kind 1, returning (B_r, B_z, B_phi); (n, 3) for kind 3), from the patch's own elements; NaN where a point lies in none. On the axis (kind 1, r = 0) B_r = B_phi = 0.

chord_error

chord_error(
    results,
    field_map: FieldMap | str | Path,
    *,
    seed: int | None = None,
    patch: str | None = None,
) -> dict

E and H of every family of every patch (or of patch), recomputed from the written map read back from disk and the results' recovered field, with the chords of seed (default: the manifest's chord_seed): {patch: {family: {"n", "E", "E_q95", "E_max", "H"}}}. Field-free patches are omitted.

decide

decide(
    E: Mapping[str, Sequence[float]],
    tol_eff: Mapping[str, float],
) -> dict

The refinement decision after the last level in E (E[family][level], levels 0..L): returns {"status": "accepted" | "not_converging" | "refine", "level": int | None, "family": str | None, "gain": float | None}.

Accepted when every family is within its tol_eff. Otherwise, from L >= 2, not converging when a family still above its tol_eff gained less than GUARD_TWO_HALVINGS over the last two halvings, E(L-2) / E(L) (the smallest such gain; ties to the alphabetically first family; E(L) = 0 is an infinite gain); otherwise refine. A family already within its tol_eff never stops the loop.

Fluids and chemistry

The fluids (axionmultiphysics.fluids, axionmultiphysics.transport) and chemistry (axionmultiphysics.chem) modules are beta. The fluids and chemistry guides list their entry points, and help(...) on each entry point documents its arguments.

Solids for particle transport (beta)

The solids list of an axisymmetric partition and its GDML export (see the solids guide).

export_gdml

export_gdml(
    path: str | Path,
    composition: dict,
    *,
    solids: str | Path | None = None,
    chord_tol_m: float | None = None,
    workdir: str | Path | None = None,
    mesher: str | Path | None = None,
) -> dict

Writes the geometry of an axisymmetric or 3D electromagnetic design as GDML for particle transport (beta).

The route is the design's mesher input (the one axmp mesh writes), axmp-mesher --export-regions on it (the exact partition of the model: its regions, the background air included, with their curves) and axionmultiphysics.solids.from_partition() on that partition. Returns the solids document (axionmultiphysics.solids/1) and writes the GDML at path and, when solids is a path, the document as solids.json there.

composition maps each material name the regions use to a particle block (nist, or elements and by; optional mean_excitation_eV, state, T_K, pressure_Pa) with an optional density (kg/m3). A region takes its design material, the background region the material named air. A material's density is the design's (as the electromagnetic parser resolves it: the built-in iron, copper and nb values, expressions evaluated) when it has one, else the block's density; two different positive values are particle.composition_invalid, none particle.density_missing, and a used material without a block particle.composition_missing. Blocks of materials no region uses are ignored.

For a 3D design the mesher input is the 3D engine's (mesh3d_in.json, made by the same library function in every build, without running the engine: each rank of a parallel program exports on its own), the partition the mesher's 3D one (one triangulation of every face, to the chord tolerance) and the solids are tessellated; chord_tol_m then goes to the mesher (default: min(1 mm, 1e-4 x the diagonal of the geometry)). A design reduced by symmetry planes (mesh.symmetry) is refused.

chord_tol_m is the conversion's chord tolerance. workdir, when given, keeps regions_in.json (the mesher input) and regions.json (the partition); without it nothing is left behind. mesher is the program (default: $AXMP_MESHER, else the one of the package). Refused: a model document (model.em_only_operation); a 3D design with mesh.symmetry, an imported mesh (mesh.file) and a mesher without the export mode (particle.partition_unavailable); a mesher that cannot be run or loaded (build.requires_mesher, with the loader's message); a planar design (particle.planar_not_offered); a failed mesher run (mesh.generation_failed, the last lines of the mesher's log in the hint; with workdir the log is kept there as regions_mesher.log). Nothing is written then.

from_partition

from_partition(
    partition: dict,
    materials: dict,
    region_materials: dict,
    *,
    chord_tol_m: float | None = None,
) -> dict

The solids document (axionmultiphysics.solids/1) of an axisymmetric partition.

partition is the mesher's info file of a bounded mode (or of --export-regions) with the exact curve parameters and the face loops; materials the document's materials ({name: {"density": kg/m3, "particle": {...}}}); region_materials {region: material name}. chord_tol_m overrides the chord tolerance of every region (default: min(1 um, 1e-5 x the diagonal of the region's box)). Raises AxionMultiPhysicsError with a particle.* code, also for a layer thinner than about the chord tolerance, whose solids would overlap or lose their place in the tree (particle.partition_invalid: lower chord_tol_m); warns (SolidsWarning, code particle.volume_deficit) for a region whose instantiated volume or mass differs from the exact one by more than VOLUME_WARN. Every solid and material carries a gdml_name, the name GDML and Geant4 use.

write

write(doc: dict, path: str | PathLike) -> None

Writes a solids document as strict JSON (UTF-8, a final newline).

write_gdml

write_gdml(doc: dict, path: str | PathLike) -> None

Writes the solids document as GDML: every length in m and every angle in deg with 17 significant digits; each document material a material of the file (its density, its composition); NIST materials and elements referenced by name and never defined; volumes defined after their daughters. Volumes and materials carry their gdml_name; a solid, a placement and a position the volume's name with _solid, _pv, _pos. A tessellated solid is a tessellated element of triangular facets (type="ABSOLUTE") whose vertices are positions in m defined in <define> (<volume>_v<k>), in the list's order and orientation.

default_chord_tol

default_chord_tol(size_m: float) -> float

The default chord tolerance of a region of the given size (m): min(1 um, 1e-5 x size).

Particle transport (beta)

The driver of axmp-transport: plans, runs and merges transport runs and estimates their outputs (see the particle transport guide).

plan

plan(
    workdir,
    *,
    solids,
    sources,
    outputs,
    events,
    fields=(),
    seed=1,
    chunk_events=1000,
    jobs=1,
    physics_list="FTFP_BERT",
    production_cut_m=PRODUCTION_CUT_M,
    integrator=None,
    outside="refuse",
    quantum_eV=QUANTUM_EV,
    stop=None,
    threads=1,
    program=None,
    debug=None,
) -> dict

Plans a transport run into workdir and returns run.json's content. Nothing runs (see execute).

Validates everything first and refuses with a named code before writing anything: the event count (events.count_missing, events.invalid), the source, the physics list, the outputs, the fields and their coverage of the solids, the integrator, a tally that could overflow, and the geometry (Geant4's overlap check, particle.geometry_overlap). Resolves NIST compositions against the program's tables. Writes exchange/solids.json (the resolved list), one job file per block of chunks and exchange/commands.txt.

execute

execute(workdir, *, workers=1) -> None

Runs the planned job files with axmp-transport, workers processes at a time. A process that fails has its incomplete chunks rerun once, in one new process; a chunk still incomplete is failed. With a stop rule the run ends at the first complete prefix of chunks that meets it (whatever the number of workers). Chunks are checked against their checksums as they complete; run.json is updated after every process.

merge

merge(
    workdir, *, allow_failed_chunks=False
) -> "ParticleResults"

Merges the complete chunks in (chunk, event) order and estimates the outputs; writes results.json and merged/. Without allow_failed_chunks the sample is the longest complete prefix of the planned chunks; with it, every complete chunk. Fewer events than requested make a partial result (events.partial). A chunk whose manifest disagrees with the plan is refused (events.chunk_mismatch); one whose arrays do not match their checksums is missing.

run

run(
    workdir,
    *,
    workers=None,
    allow_failed_chunks=False,
    **plan_kwargs,
) -> ParticleResults

plan + execute + merge; workers defaults to the number of job files.

extend

extend(
    workdir,
    *,
    events,
    workers=1,
    chunk_events=None,
    allow_failed_chunks=False,
) -> ParticleResults

Extends a run to events (at least the events requested so far): complete full chunks are reused (their checksums checked), a short last chunk is run again in full and replaced, new chunks are run; the merged result equals, bit for bit, a direct run of events.

load

load(workdir) -> ParticleResults

The merged result of a run from its results.json and chunks (nothing is run or merged again).

transport

transport(
    design,
    results,
    *,
    sources,
    outputs,
    events,
    composition=None,
    solids=None,
    field_map=None,
    map_tol=0.0001,
    track_volumes=None,
    workdir=None,
    **run_kwargs,
) -> ParticleResults

Transports particles through a solved design (beta): its regions as solids, its field as a map.

solids: a solids document (or its file) of the design's regions, built from an exported partition (the document Design.export_gdml returns, or solids.from_partition of the partition axmp-mesher --export-regions writes). This version does not export the partition by itself (capabilities()["partition_export"] is false), so without solids the call raises particle.partition_unavailable. field_map: a map directory; without it the map is exported from results (Results.export_field_map, tol=map_tol, track_volumes) into <workdir>/fieldmap. Every patch of the map serves its record's regions. composition maps the design's material names to particle blocks (used when the partition is exported). Other keywords go to run.

resolve_materials

resolve_materials(doc, *, program=None) -> dict

The solids document with its NIST compositions resolved against Geant4's own tables (axmp-transport --nist); the input is not changed.

A material whose particle block is exactly {"nist": X} at X's density (within 1e-9, relative) becomes the NIST material itself: its solids name X, and the material record is dropped when no solid uses it. Any other NIST composition stays one component and takes X's mean_excitation_eV and state where the document gives none. A density more than 1 % from NIST's warns particle.density_differs_from_nist.

capabilities

capabilities() -> dict

What this installation can do for particle transport; never raises.

transport: found, path, check (the program's --check document, or None) and ok; partition_export: whether transport() exports a design's partition by itself (the API route without solids=), per geometry (axisymmetric, 3d); generator: the event generator (not in this version).

ParticleResults

ParticleResults(
    workdir: Path, record: dict, results: dict, O: Outputs
)

The merged result of a transport run (beta): res[name] (a Measured for an aggregate output), histogram(name), tally(name), events(names=None), hits(name); record (run.json), outputs (results.json "outputs"), n_events, events_requested, partial, missing_chunks, warnings and workdir. Statistical errors only: the physics-list dependence is not estimated.

Methods:

Name Description
events

The per-event variables of the merged events, in (chunk, event) order: chunk, event and each

hits

The records of a hits output: chunk, event, track, parent, pdg, region (index in

histogram
tally

The L1 tally: edges (per axis), edep_eV (mean deposit per event per bin), stat_error (batch

Attributes:

Name Type Description
workdir
record
results
outputs
n_events
events_requested
partial
missing_chunks
warnings

workdir instance-attribute

workdir = Path(workdir)

record instance-attribute

record = record

results instance-attribute

results = results

outputs instance-attribute

outputs = results['outputs']

n_events instance-attribute

n_events = results['events']

events_requested instance-attribute

events_requested = results['events_requested']

partial instance-attribute

partial = results['partial']

missing_chunks instance-attribute

missing_chunks = list(results['missing_chunks'])

warnings instance-attribute

warnings = list(results['warnings'])

events

events(names=None) -> dict

The per-event variables of the merged events, in (chunk, event) order: chunk, event and each variable (NaN where undefined).

hits

hits(name: str) -> dict

The records of a hits output: chunk, event, track, parent, pdg, region (index in the solids' regions), x_m (n, 3), p_eV_c (n, 3), t_s, ekin_eV.

histogram

histogram(name: str) -> dict

tally

tally(name: str) -> dict

The L1 tally: edges (per axis), edep_eV (mean deposit per event per bin), stat_error (batch means; None below 20 chunks), q_dep_J_m3, volume_m3, events, quantum_eV, lo and hi (the exact 128-bit batch sums hi x 2^64 + lo, quanta) and batch_events.

Measured

Bases: float

A Monte Carlo estimate: a float that carries its statistical error and how it was obtained.

Attributes: stat_error (None when there is none), error (the estimator: "sem", "clopper_pearson", "poisson", "batch_means" or "upper_limit"), events (events of the sample), events_defined (events where the variable is defined and the selection holds), units, mc (always True), upper_limit and cl (after zero events), interval (a fraction's Clopper-Pearson interval) and reason (why there is no error). Arithmetic on a Measured returns a plain float: the error is never carried along silently.

Methods:

Name Description
as_dict

The record of results.json (NaN written as None).

from_dict

as_dict

as_dict() -> dict

The record of results.json (NaN written as None).

from_dict classmethod

from_dict(d: dict) -> 'Measured'

estimate_mean

estimate_mean(values, units: str = '') -> Measured

The mean of the defined values (NaN marks an undefined value and is skipped) with its standard error s / sqrt(n) (s with ddof 1, n the defined values); no error below two defined values.

estimate_fraction

estimate_fraction(k: int, n: int) -> Measured

k of n events: the value k / n with its Clopper-Pearson interval at one sigma (interval) and half its width as stat_error; after zero events no error but the exact one-sided 95 % limit 1 - 0.05^(1/n).

estimate_count

estimate_count(
    k: int, units: str = "1", events: int | None = None
) -> Measured

A count k with its Poisson error sqrt(k); after zero events no error but the exact 95 % limit -ln 0.05.

batch_means

batch_means(values, weights) -> tuple[float, float]

vbar = sum w_b v_b and sigma^2 = B / (B - 1) sum w_b^2 (v_b - vbar)^2, with w_b the weights normalised to one (each batch weighted by its events).

derive_seed

derive_seed(seed: int, *keys) -> int

z = seed mod 2^64, then for each key z = mix(((z XOR h(key)) + 0x9E3779B97F4A7C15) mod 2^64), with mix SplitMix64's output function, h(int) = the int mod 2^64 and h(str) the first 8 bytes (little-endian) of the SHA-256 of its UTF-8. Injective in the last key for fixed earlier keys.

chunk_seed

chunk_seed(
    seed: int,
    chunk: int,
    stage: str = STAGE,
    instance: str = INSTANCE,
) -> int

The seed of chunk chunk of a run: derive_seed(seed, stage, instance, chunk).

event_words

event_words(
    chunk_seed_: int, event: int
) -> tuple[int, int, int, int]

The four 32-bit words that seed event event of a chunk: outputs 2e and 2e+1 of the SplitMix64 sequence that starts at the chunk seed, each split low half first (the program's rule).