API Reference
The API reference documents every importable module in radpair.
The package is organised into six modules: two public entry points
(radpair.core, radpair._types) and four internal modules
that implement the simulation pipeline stages.
Core simulation functions
The radpair.core module provides the two entry points that users
call directly. do_simulation() runs the full
single-core pipeline; do_simulation_multicore()
distributes the Gaussian summation stage across worker processes.
Core simulation routines for cw-EPR spectra of radical pairs.
Sc. Theresia Quintes, M. Sc. Florian Quintes, 2019-2026
@author: Thresia Quintes, Florian Quintes
- radpair.core.do_simulation(spinsystem, experiment, simopt)
Simulate a cw-EPR spectrum for a spin-correlated radical pair.
Solves the spin Hamiltonian analytically using a pseudo-secular approximation for the hyperfine couplings. Supports an arbitrary number of anisotropic nuclei groups, each assignable to the donor or acceptor radical. Zero-field splitting (D, E) and exchange interaction (J) are included.
The simulation is composed of eight stages:
prepare_spinsystem()— unit conversionsetup_orientation_grid()— grid setupbuild_tensors()— diagonal tensorsrotate_tensors()— frame + orientation rotationcompute_hyperfine_combinations()— hyperfine sumscompute_resonance_fields()— resonance fieldscompute_intensities()— line intensitiesgaussian_summation()— Gaussian line-shape summation
- Parameters:
spinsystem (
Spinsystem) – Spin-system object describing the radical pair. See theSpinsystemprotocol for required attributes.experiment (
Experiment) – Experiment object with the magnetic-field axis and microwave frequency. See theExperimentprotocol.simopt (
SimulationOptions) – Simulation options (grid density, interpolation, CPU cores). See theSimulationOptionsprotocol.
- Returns:
Real-valued intensity array of the simulated spectrum, matching the shape of
experiment.B_z.- Return type:
ndarray
- radpair.core.do_simulation_multicore(spinsystem, experiment, simopt)
Simulate a cw-EPR spectrum using multiple CPU cores.
Runs the analytic pipeline (stages 1–7) on the main process, then distributes the Gaussian summation across
simopt.cpu_coresworker processes. Each worker handles a chunk of peaks, keeping per-process memory bounded bysimopt.max_chunk_mb.- Parameters:
spinsystem (
Spinsystem) – Spin-system object (seeSpinsystem).experiment (
Experiment) – Experiment object (seeExperiment).simopt (
SimulationOptions) – Simulation options (seeSimulationOptions).simopt.cpu_corescontrols the number of worker processes (0= auto-detect).simopt.max_chunk_mbcontrols the per-chunk memory limit.
- Returns:
Real-valued intensity array of the simulated spectrum, matching the shape of
experiment.B_z.- Return type:
ndarray
Data types
The radpair._types module defines three dataclasses that the user
instantiates and passes to the simulation functions. Each dataclass
validates its fields in __post_init__ and raises ValueError or
TypeError for invalid inputs.
Typed dataclass definitions for the radpair simulation interface.
These dataclass types replace the former
SimpleNamespace + Protocol approach with concrete, instantiable,
validated types. Users construct Spinsystem, Experiment, and
SimulationOptions objects and pass them to
radpair.core.do_simulation().
© M. Sc. Florian Quintes, 2026
@author: Florian Quintes
- class radpair._types.Experiment(B_z, freq_mw)
Experiment parameters for
do_simulation.- Parameters:
B_z (ndarray)
freq_mw (float)
- B_z
Magnetic field axis for the output spectrum in milliTesla.
- Type:
np.ndarray
- freq_mw
Microwave frequency in Hz.
- Type:
float
- class radpair._types.SimulationOptions(knots=12, refinement=1, cpu_cores=1, max_chunk_mb=None)
Simulation options for
do_simulation.- Parameters:
knots (int)
refinement (int)
cpu_cores (int)
max_chunk_mb (int | None)
- knots
Number of orientation-grid knots for the spherical integration.
- Type:
int
- refinement
Interpolation factor.
1disables interpolation; values > 1 enable interpolation onto a finer grid.- Type:
int
- cpu_cores
Number of worker processes for multicore execution.
0means auto-detect viamultiprocessing.cpu_count().- Type:
int
- max_chunk_mb
Maximum memory (in megabytes) allowed for a single Gaussian summation chunk. If
0or negative, no limit is enforced and all peaks are processed in one pass. IfNone(default), the chunk size is determined automatically from available RAM. Smaller values reduce peak memory usage at the cost of more iterations; larger values are faster but may cause out-of-memory errors. See Chunked Gaussian summation for details.- Type:
int
- class radpair._types.Spinsystem(g1, g2, A_tensors, nuclei_n, nuclei_I, A_frames, width_gauss, D=0.0, E=0.0, J_ex=0.0, g1_frame=<factory>, g2_frame=<factory>, D_frame=<factory>, donor_list=<factory>, acceptor_list=<factory>)
Spin-correlated radical pair with an arbitrary number of nuclei groups.
- Parameters:
g1 (ndarray)
g2 (ndarray)
A_tensors (list[ndarray])
nuclei_n (list[int])
nuclei_I (list[float])
A_frames (list[ndarray])
width_gauss (float)
D (float)
E (float)
J_ex (float)
g1_frame (ndarray)
g2_frame (ndarray)
D_frame (ndarray)
donor_list (list[int])
acceptor_list (list[int])
- g1, g2
Diagonal g-tensor elements of radical 1 (donor) and radical 2 (acceptor), shape
(3,). All values must be positive.- Type:
np.ndarray
- A_tensors
Diagonal hyperfine coupling tensors for each nuclei group in MHz, each of shape
(3,). Inactive groups should be zero arrays.- Type:
list[np.ndarray]
- nuclei_n
Number of chemically equivalent nuclei in each group (>= 0). Must have the same length as
A_tensors.- Type:
list[int]
- nuclei_I
Nuclear spin of each group (multiple of 0.5, >= 0). Must have the same length as
A_tensors.- Type:
list[float]
- A_frames
Euler angles
[alpha, beta, gamma](radians) for each hyperfine tensor. Must have the same length asA_tensors.- Type:
list[np.ndarray]
- width_gauss
Gaussian linewidth in milliTesla (despite the attribute name). Must be positive.
- Type:
float
- D
Zero-field splitting parameter D in MHz.
- Type:
float
- E
Zero-field splitting parameter E in MHz.
- Type:
float
- J_ex
Exchange interaction J in MHz.
- Type:
float
- g1_frame, g2_frame, D_frame
Euler angles
[alpha, beta, gamma](radians) for the g-tensors and ZFS tensor relative to the lab frame, each of shape(3,).- Type:
np.ndarray
- donor_list
0-indexed positions of nuclei groups assigned to the donor radical.
- Type:
list[int]
- acceptor_list
0-indexed positions of nuclei groups assigned to the acceptor radical.
- Type:
list[int]
Hamiltonian
The radpair.hamiltonian module implements the analytic solution
of the spin Hamiltonian. It provides:
Tensor rotation — Euler-angle similarity transformation of diagonal tensors into the lab and orientation frames.
Unit conversion — converting MHz to Tesla using the isotropic g-value and Bohr magneton.
Resonance fields — solving the four allowed transitions of the spin-correlated radical pair for each orientation and hyperfine combination.
Line intensities — computing the absorptive/emissive intensity pattern from the phase angles of the quantum beat frequencies.
Physics math: tensor rotation, unit conversion, and Hamiltonian stages.
Provides the analytic solution of the spin Hamiltonian for singlet-born spin-correlated radical pairs, including tensor rotation, resonance-field computation, and line-intensity calculation.
Sc. Theresia Quintes, M. Sc. Florian Quintes, 2019-2026
@author: Thresia Quintes, Florian Quintes
- radpair.hamiltonian.MHz_2_T(nu, g_tensor)
Convert a frequency in MHz to the corresponding magnetic field in Tesla.
The conversion uses the isotropic g-value and the Bohr magneton:
\[B = \frac{\nu_{\mathrm{MHz}} \times 10^{6}} {g_{\mathrm{iso}} \cdot \mu_{B} \times 10^{-3}}\]- Parameters:
nu (
float|ndarray) – Frequency (or array of frequencies) in MHz.g_tensor (
ndarray) – g-tensor diagonal elements, shape(3,). All values must be positive.
- Returns:
Magnetic field in Tesla (scalar if
nuis scalar, array otherwise).- Return type:
float|ndarray- Raises:
ValueError – If any element of
g_tensoris not positive.
- radpair.hamiltonian.compute_intensities(delta_omega, quantum_beat)
Calculate line intensities from phase angles.
The phase angle \(\varphi\) is obtained from \(\sin(2\varphi) = \Delta\omega / \Omega_{\mathrm{beat}}\) and the intensity is \(\sin^2\varphi \cdot \cos^2\varphi\) with an alternating sign pattern
[+1, -1, +1, -1]for the four transitions.- Parameters:
delta_omega (
ndarray) – Frequency offsets, shape(N, n_comb, 4).quantum_beat (
ndarray) – Quantum beat frequencies, shape(N, n_comb, 4).
- Returns:
Line intensities with absorptive/emissive pattern
[+1, -1, +1, -1], shape(N, n_comb, 4).- Return type:
ndarray
- radpair.hamiltonian.compute_resonance_fields(J_ex, freq_mw, g1, g2, D, A_1, A_2)
Calculate resonance fields, quantum beats, and transition widths.
Solves the analytic Hamiltonian for the four allowed transitions of the spin-correlated radical pair, producing resonance fields, frequency offsets (\(\Delta\omega\)), quantum beat frequencies, and transition widths (intensity derivatives).
- Parameters:
J_ex (
float) – Exchange interaction in angular-frequency units.freq_mw (
float) – Microwave frequency in angular-frequency units.g1 (
ndarray) – zz-projection of the rotated g1 tensor, shape(N,).g2 (
ndarray) – zz-projection of the rotated g2 tensor, shape(N,).D (
ndarray) – zz-projection of the rotated D tensor, shape(N,).A_1 (
ndarray) – Sum hyperfine, shape(N, n_comb, 1).A_2 (
ndarray) – Difference hyperfine, shape(N, n_comb, 1).
- Return type:
tuple[ndarray,ndarray,ndarray,ndarray]- Returns:
res_fields (np.ndarray) – Resonance fields for 4 transitions, shape
(N, n_comb, 4).delta_omega (np.ndarray) – Frequency offsets, shape
(N, n_comb, 4).quantum_beat (np.ndarray) – Quantum beat frequencies, shape
(N, n_comb, 4).widths (np.ndarray) – Transition widths, shape
(N, 4, n_comb).
- radpair.hamiltonian.get_D_diag(D, E)
Return the diagonal elements of the ZFS D-tensor.
The diagonal tensor is constructed from the zero-field splitting parameters D and E as:
\[\begin{split}\mathrm{diag}(D) = \begin{pmatrix} D - E & 0 & 0 \\ 0 & D + E & 0 \\ 0 & 0 & -2D \end{pmatrix}\end{split}\]- Parameters:
D (
float) – ZFS parameter D.E (
float) – ZFS parameter E.
- Returns:
Array of shape
(3,)containing the diagonal elements.- Return type:
ndarray
- radpair.hamiltonian.tensor_rotation(tensor, phi, theta, psi=None)
Rotate a tensor (or batch of tensors) via Euler transformation.
The Euler matrix O of the SO(3) group is set up in y-convention (already in multiplied form) and the orthogonal similarity transformation is carried out:
\[T' = O^{\mathsf{T}} \cdot T \cdot O\]where \(O^{-1} = O^{\mathsf{T}}\) (orthogonality).
- Parameters:
tensor (
ndarray) – Tensor to be rotated. A single 2-D array of shape(3, 3)or a batch of 2-D arrays of shape(N, 3, 3).phi (
ndarray) – Phi (Euler) angles in radians, shape(N,).theta (
ndarray) – Theta (Euler) angles in radians, shape(N,).psi (
ndarray|None) – Psi (Euler) angles in radians, shape(N,). IfNone, zeros are used (default).
- Returns:
Rotated tensor(s). Shape matches the input
tensorexcept that the leading dimension becomesN(the number of angles).- Return type:
ndarray- Raises:
ValueError – If
tensordoes not have 2 or 3 dimensions.
Hyperfine combinatorics
The radpair.hyperfine module provides the combinatorial
machinery for hyperfine line patterns:
Multiplicity — \(2S+1\) for a given nuclear spin S.
Generalised Pascal triangles — relative intensities for groups of chemically equivalent nuclei with arbitrary spin.
Hyperfine combinations — outer-product enumeration of magnetic spin projections across all nuclei groups, producing the sum and difference hyperfine matrices used by the Hamiltonian solver.
Hyperfine combinatorics: multiplicities, Pascal triangles, and combinations.
Provides the combinatorial machinery for computing hyperfine line patterns from groups of chemically equivalent nuclei, including generalised Pascal triangles and the outer-product combinations of magnetic spin projections.
Sc. Theresia Quintes, M. Sc. Florian Quintes, 2019-2026
@author: Thresia Quintes, Florian Quintes
- radpair.hyperfine.compute_hyperfine_combinations(Sys, a_projections)
Compute sum and difference hyperfine matrices and spectral weights.
For each combination of magnetic spin projections across all nuclei groups, computes the sum hyperfine (A_1) and difference hyperfine (A_2) contributions, weighted by Pascal-triangle intensities.
- Parameters:
Sys (
Spinsystem) – Spin-system object with nuclei group parameters (nuclei_n, nuclei_I, donor_list, acceptor_list).a_projections (
list[ndarray]) – Effective hyperfine couplings for each nuclei group, each of shape(N,)where N is the number of orientations.
- Return type:
tuple[ndarray,ndarray,list[float]]- Returns:
A_1 (np.ndarray) – Sum hyperfine multiplied by 2, shape
(N, n_comb, 1).A_2 (np.ndarray) – Difference hyperfine multiplied by 2, shape
(N, n_comb, 1).spec_weights (list[float]) – Spectral weights (Pascal-triangle products) for each combination.
- radpair.hyperfine.get_generalized_Pascal(number, spin)
Compute a generalized Pascal triangle for
numbernuclei of spinspin.Returns the relative intensities of the hyperfine lines for a group of
numberchemically equivalent nuclei with magnetic spinspin.(c) Stephan Rein Modified by: Florian Quintes
- Parameters:
number (
int) – Number of chemically equivalent nuclei (>= 0).spin (
float) – Magnetic spin quantum number (>= 0, multiple of 0.5).
- Returns:
Array of relative intensities. For
number == 0returns[1].- Return type:
ndarray- Raises:
ValueError – If
numberorspinis negative, orspinis not a multiple of 0.5.TypeError – If
numberis not an integer.
- radpair.hyperfine.get_multiplicity(spin)
Return the multiplicity of a particle with spin S.
\[M = 2S + 1\]- Parameters:
spin (
float) – Magnetic spin quantum number (must be non-negative and a multiple of 0.5).- Returns:
Multiplicity (number of Zeeman levels).
- Return type:
int- Raises:
ValueError – If
spinis negative or not a multiple of 0.5.
- radpair.hyperfine.get_normalized_Pascal(number, spin)
Compute a normalized generalized Pascal triangle (sum = 1).
Wraps
get_generalized_Pascal()and rescales the result so that all intensities sum to 1.- Parameters:
number (
int) – Number of chemically equivalent nuclei (>= 0).spin (
float) – Magnetic spin quantum number (>= 0, multiple of 0.5).
- Returns:
Normalized array of relative intensities summing to 1.
- Return type:
ndarray
Pipeline stages
The radpair.pipeline module implements the first four stages of
the simulation pipeline:
Unit conversion (
prepare_spinsystem()) — deep-copy the spin system and convert all parameters from physical units (MHz, mT, Hz) to internal angular-frequency units.Orientation grid (
setup_orientation_grid()) — create a coarse (and optionally fine) orientation grid for spherical integration, usingeprbase.grid.Grid.Tensor construction (
build_tensors()) — build diagonal 3×3 tensors from the spin-system parameters and extract the Euler frame angles.Tensor rotation (
rotate_tensors()) — tilt each tensor from its eigenframe into the lab frame, then rotate for every orientation on the integration grid. Returns the zz-projections used by the Hamiltonian solver.
Pipeline stages: unit conversion, grid setup, tensor construction, and rotation.
These functions compose the first four stages of the simulation pipeline, converting user-supplied spin-system parameters into orientation-dependent tensor projections ready for the Hamiltonian solver.
Sc. Theresia Quintes, M. Sc. Florian Quintes, 2019-2026
@author: Thresia Quintes, Florian Quintes
- radpair.pipeline.build_tensors(Sys)
Build diagonal tensors and extract Euler frame angles from the spin system.
- Parameters:
Sys (
Spinsystem) – Spin-system object with parameters in internal units (output ofprepare_spinsystem()).- Return type:
tuple[ndarray,ndarray]- Returns:
all_tensors (np.ndarray) – Stacked diagonal tensors of shape
(3 + n_nuclei, 3, 3)in the order[g1, g2, D, A0, A1, ...].frame_angles (np.ndarray) – Euler angles
[alpha, beta, gamma]for each tensor, shape(3 + n_nuclei, 3).
- radpair.pipeline.prepare_spinsystem(spinsystem, freq_mw, B_z)
Deep-copy the spin system and convert all parameters to internal units.
Performs unit conversion from physical units (MHz, mT, Hz) to internal angular-frequency units. The original spinsystem is not modified.
- Parameters:
spinsystem (
Spinsystem) – Spin-system object with attributes in physical units.freq_mw (
float) – Microwave frequency in Hz.B_z (
ndarray) – Magnetic field axis in milliTesla.
- Return type:
tuple[Spinsystem,float,ndarray]- Returns:
sys (Spinsystem) – Deep-copied spin system with all parameters converted to internal angular-frequency units.
freq_mw (float) – Microwave frequency converted to angular-frequency units.
B_z (np.ndarray) – Magnetic field axis converted to angular-frequency units.
- radpair.pipeline.rotate_tensors(all_tensors, frame_angles, theta_angles, phi_angles)
Tilt tensors into their reference frames and rotate for each orientation.
Performs two rotations: (1) tilt each tensor from its eigenframe to the lab frame using the Euler angles from
frame_angles, and (2) rotate each tilted tensor for every orientation(theta, phi)on the integration grid.- Parameters:
all_tensors (
ndarray) – Stacked diagonal tensors, shape(3 + n_nuclei, 3, 3).frame_angles (
ndarray) – Euler angles for each tensor, shape(3 + n_nuclei, 3).theta_angles (
ndarray) – Polar angles of the orientation grid.phi_angles (
ndarray) – Azimuthal angles of the orientation grid.
- Return type:
tuple[ndarray,ndarray,ndarray,list[ndarray]]- Returns:
g1 (np.ndarray) – zz-element of the rotated g1 tensor for each orientation, shape
(N,).g2 (np.ndarray) – zz-element of the rotated g2 tensor, shape
(N,).D (np.ndarray) – zz-element of the rotated D tensor, shape
(N,).a_projections (list[np.ndarray]) – Effective hyperfine couplings for each nuclei group, each of shape
(N,).
- radpair.pipeline.setup_orientation_grid(knots, refinement)
Set up the orientation grid for spherical integration.
Creates a coarse (and optionally fine) orientation grid for orientational averaging of the EPR spectrum.
- Parameters:
knots (
int) – Number of orientation-grid knots.refinement (
int) – Interpolation factor.1disables interpolation; values > 1 enable interpolation onto a finer grid.
- Return type:
tuple[ndarray,ndarray,ndarray|None,ndarray|None,ndarray,bool]- Returns:
theta_angles (np.ndarray) – Polar angles of the coarse grid.
phi_angles (np.ndarray) – Azimuthal angles of the coarse grid.
theta_fine (np.ndarray or None) – Polar angles of the fine grid (
Noneif no interpolation).phi_fine (np.ndarray or None) – Azimuthal angles of the fine grid (
Noneif no interpolation).weights (np.ndarray) – Integration weights for the (fine or coarse) grid.
interpolation_mode (bool) – Whether interpolation is enabled.
Gaussian summation
The radpair.summation module implements the final stage of the
pipeline: summing Gaussian line shapes via chunked evaluation. Chunking
bounds peak memory usage by splitting the peaks into batches, each of
which produces a dense float32 array of shape
(n_peaks_in_chunk, n_field) via eprbase.spectra.Spectra.
Chunked Gaussian summation and memory management.
Provides the final stage of the simulation pipeline: summing Gaussian line shapes via chunked evaluation to bound peak memory usage.
Sc. Theresia Quintes, M. Sc. Florian Quintes, 2019-2026
@author: Thresia Quintes, Florian Quintes
- radpair.summation.gaussian_summation(fields, intensities, widths, weights, field_axis, max_chunk_mb=None)
Sum Gaussian line shapes via chunked evaluation.
Splits the peaks into chunks so that the dense
(n_peaks_in_chunk, n_field)float32 array insideeprbase.spectra.Spectranever exceedsmax_chunk_mbmegabytes. Each chunk is delegated toeprbase.spectra.Spectra.by_summation(); the partial spectra are accumulated and returned.- Parameters:
fields (
ndarray) – Resonance field centers, shape(n_orient, n_peaks_per_orient).intensities (
ndarray) – Peak intensities, same shape asfields.widths (
ndarray) – Peak linewidths (FWHM), same shape asfields.weights (
ndarray) – Integration weights, broadcastable to the first dimension offields(i.e. shape(1, n_orient)or(n_orient,)).field_axis (
ndarray) – Magnetic field axis, shape(n_field,).max_chunk_mb (
int|None) – Maximum memory in MB for a single chunk’s Gaussian array. If0or negative, no chunking is performed (all peaks in one pass). IfNone, the limit is auto-determined from available RAM via_get_available_ram(), targeting at most 25% of available memory per chunk.
- Returns:
Real-valued spectrum, shape
(n_field,).- Return type:
ndarray