Known Limitations#

torchspin was developed and audited rigorously, but a few simulators have documented caveats users should understand before relying on them for publication-quality work. This document is the public record of where the package is fully MATLAB-validated, where there are quantified caveats, and where validation is still pending.

If you find behavior that contradicts this document, please open an issue.


Trust matrix at a glance#

Module

Shape parity vs MATLAB

Absolute intensity

Caveats

pepper (CW powder, crystals, frequency sweeps)

≥0.999 on 102+12+11 general cases plus 22 crystal, 4 parallel-mode, 10 feature (isotopologues, ModAmp, dispersion, separate) and 26 feature-2 cases (non-equilibrium populations, ordering, photoselection, frequency sweeps), plus 34 Cu(II)+ligand cases covering matrix/perturb/hybrid on the same systems

matches EasySpin from first principles (isotropic closed form to 1e-4, amplitude ratio 1.00±0.02)

See § Pepper

garlic (solution)

line positions exact vs EasySpin Breit–Rabi (<1e-6 mT, 18-case suite); spectra cosine >0.9999; components/isotopologues/auto-range 11-case suite identical

matches EasySpin’s TransitionRate·dBdE convention to 1e-6

See § Garlic

chili (slow-motion)

59/60 MATLAB cases at cosine ≥0.999 (general Liouvillian port; intermediates exact)

matches EasySpin’s scaling chain

See § Chili

salt (ENDOR powder)

8-case EasySpin-mirroring suite passes (fixed-field mode)

matches in regime

See § ENDOR

saffron (pulse EPR)

25 strict cases (raw + mean-centered rel. error 1e-16..1e-14) over 2p/3p/4p ESEEM, HYSCORE, MimsENDOR, direct + binned, S=1/2 and S=3/2, quadrupole, orientation selection, P1 crystal, custom sequences, ProductRule, multi-component; plus 26 EasySpin-mirroring cases, also now strict (rel. error 1e-16..1e-7)

matches to roundoff

See § Pulse

spidyan (arbitrary pulse)

10 MATLAB cases (incl. tp sweeps and relaxation with complex detection), strict rel. error 1e-14..1e-12

matches to roundoff

See § Pulse

saffron_thyme (real-pulse)

28 strict cases (raw + mean-centered rel. error 3e-13..8e-12): 18 rectangular-pulse cases over powder and P1 crystal, transient and single-point detection, DetIntegrate, DetPhase, explicit SimFreq, relaxation, 1 and 2 indirect dimensions, predefined 2p/3pESEEM and HYSCORE; plus EasySpin’s own 10 saffron_thyme_* cases with quartersin/linear chirps, trise, swept Frequency, pulse-parameter sweeps and gFrame/AFrame tilts

matches to roundoff

See § Pulse

curry, blochsteady

5 MATLAB cases within 0.5–1 %

n/a

None

hamsymm

22 MATLAB cases exact (groups and frames)

n/a

See § Pepper (tilted axial frames)

cardamom (trajectory)

3 EasySpin 6 references (diffusion/fast, jump/fast, diffusion/ISTOs): cosine 0.9998 / ≥0.97 / 0.9992, amplitude 1.00

matches EasySpin’s scale

See § Cardamom

esfit (fitting)

6 EasySpin esfit references (levmar/simplex from offset starts): torchspin reaches EasySpin’s residual or better; levmar is a port of esfit_levmar.m

n/a

EasySpin’s own levmar stalls at symmetric starts in 2 of 6 cases

orca2torchspin

33 ORCA files identical to orca2easyspin (tensors compared in the molecular frame)

n/a

atoms without data are not listed (EasySpin lists zero rows)

autograd (differentiable)

differentiable_spectrum = pepper_autograd: forward equals pepper to 1e-11; Jacobians vs finite differences of pepper for g, A, D, lw, Temperature (see § Autograd)

same as pepper

mwPhase, ordering, crystals, frequency sweeps not differentiable

Hamiltonians, utilities, constants

exact — 92 cases mirroring EasySpin’s ham_* test suite (rtol 1e-10) plus ee2/D_ cases

exact

None

eprload

identical to EasySpin on all 75 readable files in tests/eprfiles (Bruker, JEOL, specman, Magnettech, Adani, CIQTEK, ETH formats)

n/a

See § eprload (native units)

isotopologues

EasySpin’s 15 isotopologues_* tests ported (incl. the A_ spherical form); pepper/garlic/chili mixtures validated in MATLAB

exact

None


Pepper — choosing a method, and what each costs (2026-10-07)#

Added after a Cu(II) phthalocyanine fit (CuPc diluted in ZnPc: S=1/2, g = [2.049 2.181], A(Cu) = [15.3 646.6] MHz, four effectively isotropic 14N at 45 MHz, lw 0.54 mT, X-band) ran into every limit of the resonance solvers at once. All timings below are the same machine, GridSize=[91,4], 2667 points, with EasySpin on MATLAB R2024b for comparison; the generator is tests/data/generate_pepper_cupc_refs.m and the comparison torchspin/tests/test_pepper_cupc_matlab_validation.py (34 cases).

Accuracy. Against the exact matrix result for the same system:

Nuclei

hybrid

perturb (2nd order)

Cu + 1×14N

0.9805

0.896

Cu + 2×14N

0.9740

0.918

These are cosine similarities, and EasySpin’s own hybrid gives 0.982 and 0.974 on the same comparison — the deviation is the first-order electron–nuclear decoupling that defines the method, not a port defect. It shrinks as the perturbational coupling shrinks (0.9805 → 0.9999 as A(N) goes 45 → 0.1 MHz) and as the exact core grows (0.974 → 0.984 when the first nitrogen joins the core). Second-order perturbation theory does not converge the same way: with A∥(Cu) ≈ 650 MHz it is wrong about the copper itself, so it plateaus near 0.95 however small the nitrogen coupling is.

Pick matrix when it is affordable, hybrid when a large central hyperfine coupling is surrounded by small ligand couplings, and perturb only when all couplings are small compared with the microwave quantum.

Cost. Exact diagonalization grows with the Hilbert space, and the natural-abundance isotopologue expansion multiplies whatever that costs (Cu + 4N natural abundance is 10 separate simulations):

System

method

torchspin

EasySpin

63Cu + 2×14N (72 states)

matrix

5.9 s

16.3 s

63Cu + 2×14N

hybrid

0.06 s

0.14 s

63Cu + 2×14N, tilted AFrame

matrix

590 s

630 s

63Cu + 2×14N, tilted AFrame

hybrid

5.1 s

143 s

63Cu + 4×14N (648 states)

matrix

not measured to completion

not measured to completion

63Cu + 4×14N

hybrid

0.27 s

0.28 s

63Cu + 4×14N

perturb

0.06 s

0.04 s

Cu + 4×N, natural abundance

hybrid

2.0 s

5.6 s

Cu + 4×N, natural abundance

perturb

0.41 s

0.71 s

Cu + N with n=[1,4]

hybrid

0.30 s

not supported

Two things follow. matrix on Cu + 4×14N is not a fit-loop operation in either code — that is what hybrid is for; neither code was run to completion on it here, and the tilted-frame row is the largest exact comparison that was. Note that torchspin’s exact solver is not the slower of the two: it is 2.8× faster at two nitrogens and comparable with a full A tensor. And if the isotope matters less than the run time, name the isotopes ('63Cu', '14N') or raise Opt.IsoCutoff: natural-abundance copper alone doubles the work for a 0.3 % spectral change.

Sets of equivalent nuclei. pepper accepts SpinSystem.n > 1 on the hybrid and perturb paths, where nuclei are treated one at a time and combined combinatorially, so a multiplicity is a pure saving — four equivalent 14N written as n=[1,4] cost 0.30 s instead of 2.0 s and agree with four explicit nitrogens to cosine 0.99999999. From 0.9.39 the matrix path takes n > 1 too, as total-spin blocks, and treats listed nuclei that are equivalent the same way (see “sets of equivalent nuclei” below; not with quadrupole coupling); EasySpin’s pepper rejects n > 1 for every method. Equivalence means identical couplings and identical orientations: four nitrogens with different AFrame tilts are not a set of equivalent nuclei, whatever their principal values.

The derivative peak at a turning point needs a finer grid than the spectrum as a whole. Worth knowing because it looks like a parity defect and is not. Comparing Cu + 1x14N by matrix against EasySpin at GridSize=[91,4] gives cosine 0.99948 but an amplitude ratio of 0.990, and at two nitrogens 0.978 — outside the 2 % amplitude convention. Refining the grid removes it entirely:

GridSize

torchspin peak

EasySpin peak

ratio

cosine

[91,4]

53.18

53.70

0.9903

0.99948

[181,4]

51.51

51.62

0.9978

0.99998

[361,4]

51.49

51.44

1.0010

1.00000

Neither code is converged at [91,4] — EasySpin’s own peak moves 53.70 → 51.62 → 51.44 over the same refinement, a 4 % change in its own answer — and the two are unconverged by slightly different amounts, which is the whole of the apparent disagreement. At [361,4] they agree to 0.1 % in amplitude and to cosine 1.00000. The derivative extremum at a turning point is the most grid-sensitive number in a powder spectrum, far more so than the integrated intensity, so it is the first thing to check when an amplitude looks wrong.

Absolute intensity does agree, including with nuclei. Integrated absorption (Harmonic=0, [91,4]) against EasySpin: 578.38/578.38 with no nuclei, 559.77/559.90 with one nitrogen, 535.49/534.99 with two — 0.02-0.09 %. Absorption peak heights agree to 0.2-0.8 %.

That the integral falls as nuclei are added (578 → 560 → 535) is real but is not a torchspin effect: EasySpin does the same, to 0.1 %. It is the matrix method’s transition pre-selection dropping weak transitions — both codes select exactly the same number of level pairs (60 with one nitrogen, 215 with two) — and Options.Threshold=0 does not recover it, because without pre-selection the pure nuclear transitions come back and put intensity in the wrong places. hybrid and perturb hold at 578 because they place all the nuclear intensity on the core lines instead.

Default GridSize=[19,4] is unconverged for narrow lines on a large hyperfine. For this system the default grid leaves the powder average dominated by ripple, and the two codes place that ripple differently: the same Cu + 4×N spectrum agrees with EasySpin to cosine 0.9998 at [91,4] but only 0.96–0.97 at [19,4]. Neither result is right — both are unconverged. There is no automatic warning, because there is no reliable shortcut: a heuristic on the field step between knots flags dozens of simulations that agree with EasySpin to cosine 0.9999, since the SOPHE projection integrates analytically over each grid segment. Use torchspin.grid_convergence(sys, exp, opt), which simulates again on a finer grid and reports what changed — the only trustworthy test, and the one used to produce the table above. The two cupc_grid19_4N_* cases are kept in the validation suite as the record of this.

Pepper matrix method: spectra with several nuclei are not smooth in the parameters (B135, open)#

For S = 1/2 systems with a large metal hyperfine coupling and one or more ligand nuclei, the matrix method’s spectrum can change in steps when a parameter changes smoothly. Synthetic Cu(II) with two equivalent 14N (g = [2.05 2.05 2.25], A(Cu) = [30 30 500] MHz, A(N) = 40 MHz, lwpp 0.5 mT, 9.5 GHz): along a straight line in (g∥, A∥, A(N), lwpp), steps of 6e-6 in g∥ and 0.009 MHz in A∥ change the spectrum by 9e-5 of its maximum, except one such step that changes it by 7.9 %. The steps are at the same parameter values at GridSize [10 4], [19 4] and [40 4], so a finer grid does not remove them; Options.RediagLimit = 1 does not either. Method='perturb' is smooth (1e-4 per step).

Cause. Transitions are followed across the orientation grid by their energy-ordered level pair. With several nuclei the sublevels reorder between orientations, so the allowed intensity moves from one level pair to another (in the example one pair carries 0.98 of the largest intensity at the θ = 90° knot and none at the other nine), and at some parameter values it moves to a pair outside the pre-selected set. This is the mechanism behind the intensity lost with nuclei (see “choosing a method” above, where EasySpin selects the same number of pairs); whether EasySpin’s spectra show the same steps has not been checked.

Consequence for fits. The least-squares objective is a staircase. In the example (1 % noise, start 0.005 / 10 MHz / 4 MHz / 0.1 mT from the truth) levmar stops at RMSD 0.021 with “parameter step below threshold” although the RMSD decreases all the way to the truth (0.0097, the noise level); restarts stay there, trf stops at 0.038 and simplex at 0.021. Finite-difference Jacobians, and the uncertainties computed from them, are unreliable for the line-position parameters of such systems.

What to do. There is no complete workaround yet.

  • Compare the final RMSD with the noise level of the data; a fit that stops well above it has probably stalled on a step, not found the minimum.

  • hybrid and perturb have a smooth objective and converge from the same start on data they describe, but they are approximations for these systems (cosine 0.97 and 0.92 against matrix, see above): on matrix-quality data their best fit stays at RMSD 0.06 to 0.12 in this example, and a matrix fit started from their result stalls as before.

  • Start matrix fits from several nearby points and keep the lowest RMSD.

0.9.39. The numbers above are for the full space (0.9.38, or Options.EquivalentNuclei = False). With the total-spin blocks of the next section, the default from 0.9.39, the example fit ends at RMSD 0.0110 in place of 0.0208 (noise level 0.0097; g∥ 2.2484, A∥ 498.1 MHz against 2.2475 and 496.5), and the RMSD decreases smoothly from there to the truth. The steps are still there: one step of the same scan changes the spectrum by 9.8 % of its maximum (3.2 % with Threshold = 0), and levmar still stops with “parameter step below threshold”.

Planned: follow the levels by eigenvector overlap between neighboring orientations and select transitions at their own resonance fields. That changes matrix-method spectra with nuclei (it also restores the lost intensity) and leaves EasySpin parity for them, so it will come as its own release.

Pepper matrix method: sets of equivalent nuclei (total-spin blocks, 0.9.39, B139): deviation from EasySpin#

Nuclei with the same isotope, hyperfine tensor and frame, gnscale and chemical shift, and without quadrupole coupling, enter the spin Hamiltonian only through their total spin K. From 0.9.39 the matrix method simulates each such set as its total-spin blocks and sums the block spectra (Options.EquivalentNuclei, default True; torchspin/equivnuclei.py): three 14N are K = 3, 2 (twice), 1 (three times) and 0, with weights 7/27, 10/27, 9/27 and 1/27. This is exact: the energy levels of the full space are the union of the block levels (checked to 1e-10 MHz on five systems), and single-crystal spectra with all transitions agree with the full space to 5e-6 of the maximum (Cu(II) + 2 14N with tilted hyperfine frames, S = 3/2 + 2 1H, triplet + 2 14N, with and without Boltzmann populations). It also lets the matrix method take SpinSystem.n > 1. EasySpin’s pepper diagonalizes the full space and rejects Sys.n > 1.

What it fixes. In the full space the copies of a total spin are exactly degenerate. Every resonance is diagonalized on its own, so every transition gets its own arbitrary basis of the degenerate levels, and the intensities of the transitions between two degenerate sets no longer add up to the basis-independent total. In 0.9.38:

  • Three equivalent 1H on a single crystal (S = 1/2, A = [60 65 70] MHz, all transitions) gave 93.0 % of the intensity of the electron transition. The blocks give 100.000 %.

  • Cu(II) + 3 14N (g = [2.04 2.06 2.25], A(Cu) = [30 40 500] MHz, A(N) = 40 MHz, lwpp 0.6 mT, 9.5 GHz, GridSize [4 4]) changed by 5.5 % of its maximum between Options.BatchSize 10 and 1, because the batch sets the field knots and with them the bases; ModellingAccuracy = 2e-8 did not remove it (1.8 %). The blocks agree to 5e-7 across batch sizes, and to 1.3e-8 of the full space once the three 14N are made inequivalent.

What changes for users. Default matrix spectra of systems with equivalent nuclei change, and are much cheaper (Cu(II) + 3 14N on GridSize [4 4]: 2 s, from about 250 s; Hilbert-space dimensions 56, 40, 24 and 8 in place of 216).

  • Systems where the full space was already right do not change: S = 3/2 + 2 1H and triplet + 2 14N powders agree to 1e-8 (all transitions).

  • Cu(II) + 2 14N (g = [2.05 2.05 2.25], A(Cu) = [30 30 500], A(N) = 40 MHz, lwpp 0.5 mT, 9.5 GHz) changes in the perpendicular region, by up to 23 % of the maximum of the absorption spectrum on GridSize [19 4] and 17 % on [40 4] (35 % of the maximum of the first-derivative spectrum on [10 4]). Most of this is intensity that the transition pre-selection (Options.Threshold, see “choosing a method”) loses in the full space, where it is spread over more level pairs: the integral is 91.9 % of the complete one in the full space and 97.1 % with the blocks on [19 4] (95.0 % and 97.9 % on [40 4]). Against the spectrum with all transitions on 181 knots the largest error is 33 % (full space) and 15 % (blocks) on [19 4], 26 % and 12 % on [40 4].

  • Against EasySpin (copper phthalocyanine model, 63Cu + 2 14N, A(N) = 45 MHz, GridSize [91 4], first derivative; test_pepper_cupc_matlab_validation.py): the full space agrees with EasySpin’s default spectrum to cosine 0.9996, the blocks to 0.986. EasySpin shares the pre-selection loss: the integrated absorption is 92.6 % of the complete one in the full space (EasySpin’s is within 0.1 % of that), 96.1 % with the blocks and 100.0 % with Threshold = 0, where the blocks and the full space agree to cosine 0.99997. The spectrum with all transitions is at cosine 0.990 from the default blocks and 0.973 from the default full space. The EasySpin comparisons therefore run with EquivalentNuclei = False.

  • With Threshold = 0 the two routes have the same integral and differ by 4 % of the maximum on [19 4] and 0.7 % on [40 4]; the blocks are the closer one to the 181-knot spectrum (1.6 % against 2.2 % on [40 4]).

Still open.

  • The pre-selection loss itself: with default Threshold the Cu(II) + 2 14N block spectrum stays 12 % of the maximum below the all-transitions spectrum in the perpendicular region, on any grid. Threshold = 0 removes it at several times the cost.

  • Sets that are not reduced keep the full space and its degeneracy errors: equivalent nuclei with quadrupole coupling (Q does not commute with K²), a set containing the nucleus that carries AStrain, systems with nn, H0Extra or a full-space initState, Options.Transitions given as level pairs, Options.separate other than 'components', and EquivalentNuclei = False. SpinSystem.n > 1 raises in these cases.

  • pepper_autograd (the route pepper takes when an input requires grad) and salt diagonalize the full space, so a differentiable spectrum of a system with equivalent nuclei differs from the default one by the amounts above.

  • The steps of the section above (B135) remain inside the blocks.

SpinSystem input shapes follow EasySpin (0.9.15)#

The constructor accepts the short forms EasySpin’s validatespinsys.m expands and expands them the same way, and raises ValueError for the shapes EasySpin rejects (up to 0.9.14 many of these failed later in pepper with an IndexError, or were silently ignored). A 1-D list is read as a MATLAB row vector. Deliberate differences from EasySpin:

  • torchspin shorthands are kept, although EasySpin rejects them: a scalar g, A (every nucleus and electron), gStrain, DStrain or ee; [x, y, z] for every electron (g, gStrain), every nucleus (A, AFrame with one electron spin) or every pair (ee, eeFrame); one DStrain row for every electron; D_, Q as flat lists of nNuclei/nElectrons pairs or triples.

  • Flat D for several electron spins raises (B61, 0.9.15). A 1-D D of 2 or 3 values with two or more electron spins could be one shared [D, E] / principal-value set (torchspin up to 0.9.14) or one D per electron (EasySpin, numel(Sys.D) == nElectrons). torchspin adopts neither and raises ValueError; give one row per electron spin ([[D1, E1], [D2, E2]], [[Dxx, Dyy, Dzz], ...], [[D1], [D2]]) or D_. EasySpin input Sys.D = [D1 D2] for two electrons must therefore be written D=[[D1], [D2]]. A scalar D and a flat list of one D per electron for four or more electron spins are accepted.

  • Flat ee for three electron spins. A 1-D ee of three values for three electron spins is read as principal values for every pair (EasySpin: one isotropic value per pair); give [[J12], [J13], [J23]] for the latter.

  • Missing A with Nucs gives zero hyperfine (EasySpin raises).

  • Not checked: sigma, sigmaFrame, nn, nnFrame (wrong shapes still fail late) and negative widths (lw, strains), which EasySpin rejects.

levelsplot resonances (fixed 0.9.19)#

Before 0.9.19 levelsplot(..., mwFreq=...) drew no transitions: the resonance call raised a TypeError that was swallowed (B78). It now follows EasySpin levelsplot.m:244-272 and errors propagate. Differences from EasySpin, both from torchspin diagonalizing exactly at every resonance field: fields differ by up to 2.9e-5 mT (EasySpin’s are roots of its spline level model) and relative intensities (line colors, stick heights) by up to 1.9e-4 (EasySpin interpolates eigenvectors between knots, RediagLimit 0.95; see § Pepper — round 3). Field-quadratic and higher Sys.Ham* terms are dropped, as for the level diagram (§ Simulator — field-quadratic Zeeman terms).

SpinSystem field assignment normalizes (0.8.7)#

Since 0.8.7 sys.<field> = value rebuilds the spin system with the new value, so the field holds what the constructor would store and invalid values raise at the assignment (up to 0.8.6 the raw value was stored and failed later, e.g. pepper’s TypeError for sys.HStrain = [1, 2, 3]). Consequences:

  • One field at a time. Every assignment must give a consistent system: changing the number of nuclei through Nucs raises because n (and the per-nucleus tensors) still have the old length. Build a new SpinSystem, or use nucspinadd/nucspinrmv.

  • Alternative pairs. Assigning D, A, lw, tcorr or Diff clears D_, A_, lwpp, logtcorr or logDiff (and the other way round).

  • Defaults are re-applied. sys.A = None gives zero hyperfine, as in the constructor; sys.g = ... on a system with Ham110/Ham112 raises, as in the constructor. Conversely sys.Ham = {'112': ...} raises on a system built without g, because g already holds the default g_free; give Ham to the constructor instead. object.__setattr__(sys, name, value) stores a value unnormalized (tests use it to check validate()).

  • Cost. An assignment costs one construction (about 0.02 ms).

  • dataclasses.replace and D_/A_. dataclasses.replace(sys, ...) passes every stored field, so for a system built with D_ (or A_) it also passes the D (A) derived from it, and the constructor raises “Zero-field splitting given in both D and D_” (“Hyperfine data given in both A and A_”). The constructor is deliberately unchanged. Assign the field instead (sys2 = copy.copy(sys); sys2.weight = 0.5), or build a new SpinSystem. torchspin’s own rebuilds (isotopologue expansion, HStrainL, spin2sys’s U term) use the internal spinsystem._replace, which passes such pairs through their source only; up to 0.8.11 they used dataclasses.replace and raised for systems with D_ (or with A_ and HStrainL).

Powder grid interpolation on closed-φ grids (fixed 0.8.9)#

pepper, pepper_autograd and salt interpolate resonance positions from the coarse grid (GridSize(1)) to the fine one with EasySpin’s G3 scheme: each θ row of the triangular grid is resampled along φ to a rectangle, then a bicubic spline is evaluated at the fine knots. Since 0.8.9 the rows use zero end slopes as in EasySpin (gridinterp.m:184, esspline1d(y,1,nc); a 2-knot row is the cubic Hermite polynomial with zero slopes, esspline1d.m:55-60); the bicubic step is not-a-knot in both codes. Up to 0.8.8 the rows were not-a-knot, which changed resonance fields next to the pole: field-sweep powder spectra at Harmonic 1 were 1.005–1.006 of EasySpin’s peak amplitude (S = 1/2, g = [2 2.05 2.1], GridSize [19 4]).

  • EasySpin agreement (tests/data/ref_closedphi_interp.mat): field sweeps at Harmonic 0 and 1, Gaussian, Lorentzian, 14N hyperfine, GridSize [19 4] and [31 4]: amplitude within 2e-7, relative residual 2e-8 to 6e-7 (the same as without interpolation). Frequency sweep and fixed-field salt (Method 'perturb1'): residual 1e-12. HStrain: residual 8e-5, amplitude 0.999996 (not traced; widths are interpolated linearly in both codes).

  • Grids without interpolation, axial (Dinfh) grids and open-φ grids (Ci, C2h, C4h, C6h, S6, C1) are not affected (axial grids: see § Powder grid interpolation on axial grids). (The D3d/D4h/D6h/Oh/C6h/S6 grids had a separate defect, fixed in 0.9.3; see § Powder grid φ range. C1 had another one, fixed in 0.9.21; see § C1 grid interpolation of the lower hemisphere.)

Powder grid interpolation on axial grids (fixed 0.9.7)#

On an axial (Dinfh) grid EasySpin interpolates resonance positions with esspline1d(y, 1, iphi) (gridinterp.m:77-78): a cubic spline over the θ knot index with zero first derivatives at both ends (esspline1d.m EndCon = 1). Up to 0.9.6 pepper, pepper_autograd and salt used a not-a-knot spline in cos θ, which bends differently next to both poles: axial g = [2 2 2.4] at GridSize [10 10] was cosine 0.99863 and amplitude 1.029 of EasySpin; a Cu(II)-like g = [2.05 2.05 2.25], 63Cu A = [50 500] MHz was cosine 0.99380 and amplitude 1.034 on the default grid.

  • EasySpin agreement (tests/data/ref_pepper_dinfh_interp.mat, 6 cases, Harmonic 0 and 1, default grid and [10 10]): cosine ≥ 1 − 1e-10, amplitude within 3e-6, pepper and pepper_autograd. The interpolation map is linear in the knot values, so pepper_autograd keeps its cached constant matrix and stays differentiable (checked against central differences).

  • Existing EasySpin comparisons that moved: the Cu(II) phthalocyanine cases at EasySpin’s default GridSize [19 4] (cupc_grid19_4N_*, dominated by grid ripple) went from cosine 0.970 / 0.956 and amplitude 0.765 / 0.820 to 1 − 5e-9 and 3e-5, so the ripple was this interpolation, not grid convergence; their tolerances were tightened. Other interpolated Dinfh cases moved closer, e.g. iso_Cu 0.99987, pt_ga1_matrix 0.99929, pt_ga2_matrix 0.99927, nobroadening_* 0.99914 and autorange_field_Cu 0.99984, all now ≥ 0.9999997. Cases limited by something else (perturbation theory, the 2N matrix grid convergence) moved by less than their own residual.

  • Intensities and widths on axial grids (L3) and axial positions with missing resonances (L3) were already EasySpin’s and are unchanged.

Coarse grids of two or three knots (fixed 0.9.39, B137)#

Options.GridSize accepts a coarse grid of two knots or more; EasySpin’s pepper rejects GridSize(1) < 10 (Opt.GridSizeMinimum, pepper.m:505). Up to 0.9.38 the smallest grids with interpolation (GridSize = [2, n] or [3, n], n > 1) failed:

  • Two orientations ([2, n] on the Dinfh grid, i.e. every axial system, and on C4h and C6h): pepper returned an all-zero spectrum without an error or a warning, for the matrix and perturbation methods, with strains and for frequency sweeps. Transitions with fewer than three knots were dropped before the interpolation. pepper_autograd and salt were not affected on the axial grid.

  • Open-φ grids (C2h, S6, Ci and C1 at two knots; C2h, C4h, C6h, S6 and Ci at three): pepper, pepper_autograd and salt raised scipy’s mx must be > kx, because the rectified θ × φ array has fewer than four rows or columns and FITPACK’s bicubic spline needs four.

Since 0.9.39 these grids are interpolated with the same scheme as larger ones. A two-knot axial grid uses the zero-slope cubic Hermite polynomial for positions (esspline1d(y,1,x), esspline1d.m:55-60) and for intensities and widths (L3 with zero tangents). On open-φ grids the tensor-product not-a-knot spline is the straight line through two rows or columns and the parabola through three, which is what EasySpin’s esspline2d/esspline1d compute for such arrays (esspline1d.m:49-71). A transition that is missing at one of two orientations is still dropped.

These grids are valid input, not accurate spectra: for S = 1/2, g = [2 2 2.3] at 9.5 GHz, [2 4] keeps the integral to 1 % but reaches 0.56 of the converged peak height. Check a grid with grid_convergence. Tests: torchspin/tests/test_small_grid_interpolation.py.

Powder grid φ range of the D3d/D4h/D6h/Oh/C6h/S6 grids (fixed 0.9.3)#

Up to 0.9.2 sphgrid covered φ = 0..π/2 for the D6h, D4h, Oh, D3d and C6h grids and 0..π for S6, while EasySpin (private/gridparam.m) and torchspin’s gridparam (used by pepper’s grid interpolation and by grid_triangulation) use π/6, π/4, π/4, π/3, π/3 and 2π/3. sphgrid now reads the same table. Spectra on these grids changed:

  • With orientations without resonances the coarse knots were interpolated in the wrong layout (S = 5/2, D4h, [200 480] mT: cosine 0.673 with EasySpin; Oh, [250 430] mT: 0.491).

  • The D3d, C6h and S6 grids held a non-integer number of symmetry wedges, also without interpolation (D3d, [0 800] mT: cosine 0.964; D3d system on an S6 grid 0.901; D6h system on a C6h grid 0.735). The D6h, D4h and Oh grids covered whole wedges, so they were only affected through the interpolation.

  • Now (tests/data/ref_sphgrid_maxphi.mat, 9 cases, pepper and pepper_autograd): cosine ≥ 0.99993, amplitude within 5e-4; EasySpin’s sphgrid knots and weights for all 14 groups agree to 1e-13.

  • With missing knots, positions of all transitions were interpolated linearly (EasySpin L1), also for transitions that resonate at every knot, on every grid (the D4h system on a D2h grid: cosine 0.959 before, 1.0000000 with EasySpin in 0.9.3-0.9.27). Since 0.9.28 the transitions that leave the range are searched again and the cases whose ranges cut transitions (d4h_*_wide, oh_auto) deliberately differ from EasySpin; see § Field sweeps whose range cuts transitions.

  • Options.GridSymmetry accepts all 14 EasySpin grid symmetries, 'auto' and '' (before 0.9.3 only Dinfh, D2h, C2h, Ci, C1, O3 and 'auto').

Field sweeps whose range cuts transitions (fixed 0.9.28; was § Powder grid interpolation when resonances are missing, 0.9.4)#

The matrix resonance search (resfields_batch) covers Exp.Range only, so a transition that leaves the sweep window at some orientations has knots without a resonance (NaN) there. Up to 0.9.27 pepper and pepper_autograd then, as EasySpin does,

  1. interpolated the positions of every transition linearly (L1 on 2-D grids, L3 on axial grids; pepper.m:701, 763-772) as soon as one transition had a missing knot (0.9.4, B31: before that pepper switched only the slots that carried NaNs, which disagreed with EasySpin and with pepper_autograd, B91). Linear position interpolation reproduces the coarse-grid facets for all transitions, so a narrow range made the default GridSize [19 4] no better than [19 1];

  2. dropped every triangle (or axial zone) with a NaN vertex, so the triangles crossing the range ends were lost even without interpolation and spectra converged only O(h) near the ends (B75; EasySpin too).

Since 0.9.28 (B88), after the first search the level pairs whose resonance count differs between orientations are searched again over Range ± 0.5 W (W = sweep width; lower edge clamped at 0), all orientations at once so that the occurrence index of a looping transition means the same at every knot, and their resonances are replaced wholesale. A pair’s new resonances are kept only if fewer are missing and no orientation loses one; pairs that improved but are still incomplete are searched again over a doubled window, up to ± 4 W. (Pairs that stop improving do not resonate at some orientations at any field nearby, e.g. looping transitions; searching them over ever wider windows only made the detection of their near-tangent resonances roundoff-sensitive: S = 5/2 parallel mode differed by 4.9 % between torch 2.10 and 2.15 with an unconditional ± 4 W round, 5e-13 now.) Out-of-range positions are kept: projection (_projecttriangles, _projectzones) and the strain summation clip them to the window, and the interpolation sees the transition at every knot. Only slots that still miss knots after that (transitions that genuinely do not resonate at some orientations, e.g. looping ones) are interpolated linearly; all others keep the global cubic G3. This is decided per slot in pepper._interp_slot and pepper_autograd._interp_slots_t; the global switch is gone.

  • Converged references (no interpolation, GridSize [181 1], on an aligned sweep wide enough that no transition leaves it, cropped; tests/data/ref_missing_knots.npz, generate_missing_knots_refs.py). 1 − cosine / max|dev| relative to the maximum, on the interior of the range (ends ± 5 FWHM dropped, see the next bullet), 0.9.27 → 0.9.28, pepper and pepper_autograd alike:

    • 63Cu, A = [50 50 500] MHz with AFrame [0 0.4 0], lw 0.3 mT, [290 350] mT (B88), auto C2h grid [19 4]: 0.201 / 0.62 → 0.0525 / 0.33 (cosine 0.7987 → 0.9475; the rest is the C2h grid at [19 4], B88 part 3: a wide sweep gives the same spectrum to 3e-11);

    • 91Zr, A = 780 MHz, D2h [19 4], [300 400] mT (B91): 6.7e-4 / 0.050 → 4.4e-6 / 0.0049;

    • S = 5/2 with D and B4, D2h [19 4], [200 480] mT (B31): 0.0434 / 0.236 → 9.6e-5 / 0.0135;

    • the 16 EasySpin cases of test_pepper_nanlinear_, test_interp_nan_edges_, test_sphgrid_maxphi_ and test_pepper_parallel_matlab_validation.py whose ranges cut transitions all move closer, e.g. the Oh system at [250 430] mT 0.579 / 0.90 → 2.0e-3 / 0.064, the B48 stick spectrum without interpolation (B75) 8.7e-3 / 0.27 → 1.9e-5 / 0.022, S = 5/2 parallel mode (with looping pairs that stay partly missing) 5.1e-3 / 0.130 → 7.0e-4 / 0.036.

    • A narrow sweep now equals the crop of a wide sweep at the same GridSize to 3e-11 (interior; stick and strain spectra, which have no final convolution, on the whole range but the first bin); 0.9.27: 0.04-0.6.

  • Range ends. Lines centered outside the range enter the final Sys.lw convolution only through the spectrum itself; the edge padding of Options.PaddingMultiplier (0.9.6) handles that. With it the full-range numbers equal the interior ones (Cu [19 4] cosine 0.94750, 91Zr 0.999865 / max dev 0.077, the Cu no-interpolation [181 1] spectrum 0.99569 → 1.000000 / 3e-4); without it the first and last few FWHM of a harmonic spectrum still deviate. Transitions that leave the range at every orientation are not searched; their Lorentzian tails inside the range are missing, as before (91Zr: the 0.077 above).

  • pepper vs pepper_autograd agree to 4e-12..1.3e-11 of the maximum on these cases (B91; they were already equal since 0.9.4). Gradients through the re-searched slots (d/dA, d/dg, d/dlw on the Cu case on a Ci grid and the 91Zr case) agree with converged central differences to 1e-6 / 4e-8 / 1e-8.

  • Unchanged when nothing is missing. If every level pair has the same number of resonances at every orientation the re-search is not run and no slot goes linear: 29 spectra (9 grid symmetries, Cu with and without strain, high spin, perturbation theory, frequency sweeps, pepper and pepper_autograd) are bit-identical to 0.9.27.

  • Cost. One extra search, over the partly missing pairs only, per doubling: case 3 at [19 4] 0.04 → 0.2 s, the Cu case at [181 1] 6 → 12 s.

  • Deliberate deviation from EasySpin. EasySpin keeps the NaNs, interpolates every slot linearly (pepper.m:701, 763-772) and drops the triangles that cross the range ends. For the EasySpin references above this gives 1 − cosine up to 0.06 (Oh: 0.54, amplitude 1.34), always farther from the converged reference than torchspin. Those EasySpin comparisons are xfail(strict=True) with the measured numbers; the 0.9.4 C2h case (EasySpin’s open-φ L1 rows, B58) is one of them.

  • Frequency sweeps are not affected: resfreqs_batch returns every level pair at every orientation (no window), so out-of-range knots do not occur, and the missing-knot handling there is unchanged.

  • Perturbation theory (Options.Method='perturb*') searches Range ± 20 % (EasySpin’s SearchRange) and has no level pairs to re-search; slots that still miss knots there go linear per slot, the others stay cubic.

  • Hybrid (Options.Method='hybrid'): the nuclear sub-lines are pruned per solver call, so the hybrid line list is not re-searched; per-slot linear as above.

  • salt (ENDOR) has its own rule and is unchanged: with any missing knot it skips the interpolation altogether.

Powder grid interpolation next to knots without a resonance (fixed 0.9.10)#

When some orientations have no resonance in the field range, pepper and pepper_autograd interpolate the coarse knots linearly (EasySpin gridinterp L1, gridinterp.m:129). Up to 0.9.9 a missing coarse knot also removed the fine knots on the neighboring coarse row or column (0 * NaN in the bilinear sum; MATLAB’s interp2 skips zero-weight corners), and sphgrid’s φ differed from EasySpin’s linspace(0, maxPhi, nPhi) by a few ulp, which decided whether a fine knot lay exactly on a coarse column.

  • Before: S = 1/2, g = [2 2.05 2.1], [325 337] mT, GridSize [31 4]: up to 5.6 % (stick), 2.4 % and 7.1 % (lw 1.5 mT, Harmonic 0/1) of the maximum; S = 5/2 with D and B4 on a D2h grid, [290 390] mT: 0.54 % / 0.96 %. Now 5e-7 / 2e-8 / 1e-7 and 4e-5 (B50’s residual is the same without interpolation). tests/data/ref_interp_nan_edges.mat.

  • sphgrid φ and θ equal EasySpin’s bitwise (12 groups, GridSize 7 and 73). Spectra with a resonance at every knot change by roundoff only (≤ 1.3e-13).

  • EasySpin spectra (0.9.28). The seven spectra here cut transitions at the range ends; since 0.9.28 they are re-searched (§ Field sweeps whose range cuts transitions) and are checked against converged references instead of EasySpin (strict xfails with the measured numbers).

  • Open-φ grids with missing knots still deviate (B58, not fixed). For periodic θ rows EasySpin’s L1 rectify samples the wrapped row (len + 1 values) at linspace(1, len, nc) (gridinterp.m:188, 217), i.e. it stretches the row over the first len knots and leaves out the segment back to φ = 0; torchspin’s _row (pepper.py, xx = np.linspace(1.0, float(n), nc) with n = len + 1) samples the full period. Affects Ci, C2h, C4h, C6h, S6 and C1 grids only when some knot has no resonance. S = 3/2, g = [2 2.05 2.1], D = [3000 500] MHz, Ci grid, [50 400] mT: cosine 0.9925, amplitude 0.954 with EasySpin (0.9923 / 0.953 before 0.9.10). test_gridinterp_l1_vs_easyspin marks the open-φ cases xfail.

C1 grid interpolation of the lower hemisphere: deliberate deviation from EasySpin (fixed 0.9.21)#

The C1 grid’s lower hemisphere is built from the upper knots in reverse order (EasySpin sphgrid.m:320-325; torchspin’s sphgrid does the same and keeps that order, which grid_triangulation relies on), so each lower θ row is stored with φ decreasing. EasySpin’s rectify step (private/gridinterp.m:204-224) reads these rows as φ increasing, so a lower knot at φ takes the value from −φ − Δφ (mirrored and shifted by one coarse φ step Δφ of that row); torchspin’s port (pepper._interp_grid) did the same up to 0.9.20 (B74). Since 0.9.21 torchspin reverses each lower row before resampling it and so deliberately deviates from EasySpin, toward the exact (uninterpolated) result.

  • Affected: pepper, pepper_autograd and salt on a C1 grid with interpolation (GridSize(2) > 1). C1 is chosen by default for low-symmetry systems with Sys.tdm (photoselection), otherwise only with Options.GridSymmetry='C1'. Because of the shift by Δφ, also systems with coaxial tensors move (rhombic g on C1 [20 4] vs D2h: 2.4e-3 → 3.6e-4 of the maximum); only φ-independent (axial about z) data are unaffected. All other grids are unchanged bit for bit.

  • Size (C1 [19 4] vs the same fine knots without interpolation, C1 [73 1]; max deviation of the maximum, EasySpin’s error before → torchspin now): Cu(II) with non-coaxial g and A 0.342 → 0.0075 (Ci grid of the same size: 0.0078); photoselection triplet with non-coaxial g, D and tdm, default grid 0.069 → 0.0018; salt 1H ENDOR 0.021 → 0.00054. Interpolating f = 12x + 15y + 8z + 4xy − 3yz + 2xz (mT) from C1 [19 4] to 73: max error 32.5 → 0.52 mT (L1), 35.7 → 0.064 mT (G3).

  • Proposed upstream fix: read the rows reversed at gridinterp.m:211/213/217/219, i.e. y(idx+len-1:-1:idx) in place of y(idx:idx+len-1), with the periodic wrap element idx+len-1 in place of idx (y([idx+len-1:-1:idx idx+len-1])).

  • EasySpin-reference cases on interpolated C1 grids (photosel_* in ref_pepper_features2.mat and ref_pepper_round3.mat, fullsphere_C1 in ref_pepper_ext2.mat) moved by up to 9e-3 of the maximum (cosine ≥ 0.999989, amplitude within 0.85 %). Their EasySpin comparison is replaced by torchspin on the same fine knots without interpolation (*_c1_vs_no_interpolation). test_gridinterp_l1_vs_easyspin[C1-*] remains xfail (B58 and this deviation).

Centered projection bins: deliberate deviation from EasySpin (0.9.35, B85)#

The SOPHE projection (pepper, pepper_autograd, salt’s fixed-field powder; torchspin._projection) gives axis point x_k the facet density integrated against the hat of half-width dx centered on x_k (linear interpolation / cloud-in-cell); a facet of zero width is split linearly between the two nearest points. EasySpin’s projecttriangles.c/projectzones.c integrate over the box [x_k, x_k + dx), report it at x_k, and truncate facets narrower than one bin into one box.

  • Why. EasySpin’s convention puts every projected spectrum half an increment low (best-fit shift +0.49 dx against a converged reference), while its template paths (isotropic, crystal, Exp.Orientations, lisum1i) are centered; and the truncating sub-bin deposit has no position dependence. Rhombic S = 1/2, 512 points over 40 mT, lw 1 mT: max error against a converged reference 9.4 % -> 0.65 % (lw 0.3 mT: 31 % -> 3.8 %; best-fit shift +0.49 -> -0.005 dx). An isotropic g on a forced/auto D2h grid (three g leaves on the graph): spectrum vs the O3 template 2.8-5.5 % -> 2-5e-4 at 4096 points, and d/ds of g = s[1 1 1] +999.7 (0.9.34; the true value is -13770) -> -11452 at 512 points (dx/sigma = 0.28) and within 3.2 % of the O3 gradient at 4096 points. The position derivative of a point mass split linearly is the chord slope of the sampled line, first order in dx; central differences agree with autograd to 1e-10.

  • Intensity. The hats are a partition of unity: sum(spec)·dx equals the projected intensity to roundoff (<= 2.4e-14 relative; 0.9.34 left 2.9e-12 from its running sums). Mass within one increment beyond the first or last point goes partly to the missing neighbor and is dropped, as mass outside the range was before.

  • Smoothing. The hat has variance dx²/6 against the box’s dx²/12, so narrow lines are broadened by dx²/12 more than in EasySpin; this, not the shift, is what remains against EasySpin mapped onto centered bins.

  • EasySpin comparisons. 168 comparisons moved (spectra built by projection; cosine typically 0.98-0.999, stick spectra and very narrow lines down to 0.95). They stay as they were, strict xfail with the measured numbers (torchspin/tests/_b85.py). Parity moved for two reasons: EasySpin’s projected spectra are half an increment low, and the hat smooths with variance dx²/6 against the box’s dx²/12. Against EasySpin’s spectrum shifted by dx/2 (linear interpolation) 61 of the 168 meet their original tolerances (36 %); against EasySpin mapped onto centered hat bins ((-b[k-2] + 13 b[k-1] + 13 b[k] - b[k+1])/24, test_b85_easyspin_centered.py) 73 do. The other 95 have tolerances calibrated to EasySpin’s box binning (1e-5..1e-9, stick spectra) and are strict xfail there too, with both numbers.

  • Physical accuracy (hat chosen over a centered box, 2026-11-14). Against converged references (field axis 16-32x finer, GridSize [181 1] without interpolation, point values of the converged spectrum at x_k), max error / max (0.9.34 | hat | centered box with a linear split below one bin, branch dev/b85-box):

    case

    0.9.34

    hat

    box

    rhombic S = 1/2, 512 pts / 40 mT, lw 1 mT, 1st harmonic

    1.0e-1

    3.6e-3

    3.2e-3

    same, lw 0.3 mT

    3.3e-1

    3.7e-2

    3.1e-2

    Cu, A = [50 50 500] MHz, lw 0.3 mT, 1024 pts

    3.4e-1

    5.0e-2

    4.8e-2

    isotropic on a forced D2h grid, 512 / 4096 pts

    8.8e-2 / 5.5e-2

    1.3e-2 / 4.7e-5

    same

    case3 (S = 5/2, B4), [181 1]

    3.2e-1

    4.3e-2

    3.8e-2

    salt 1H ENDOR, lw 0.05 MHz

    1.8e-1

    3.7e-2

    3.2e-2

    Best-fit shift: 0.9.34 +0.46..+0.54 dx, hat and box below 0.03 dx. Gradients against converged values (rhombic, 512 points): d/dg_y relative error 3.7e-3 | 3.3e-5 | 2.0e-3, d/dlw 5.3e-2 | 1.1e-3 | 9.8e-4; isotropic direction (three g leaves) at 4096 points: wrong sign | 3.2 % | 3.2 %. The box is 5-30 % closer in the forward spectrum of narrow lines (half the smoothing), but its blend of box and split for facets narrower than one bin gives derivatives 10-60x less accurate in g and a kink at width dx; the hat was chosen. test_projection_accuracy.py keeps the hat numbers.

  • torchspin-only references. ref_missing_knots.npz (same axis as the tests, so it shares their projection bins) was regenerated with the centered bins. The sixteen coarse-grid ([19 4]) checks the centered bins moved now compare with ref_converged_b85.npz (field axis 16-32x finer, point values), bounds measured x 1.05; 0.9.34 exceeds every one of them (by 1.9x for b50_stick_wide’s max deviation, otherwise 4-600x). The lw central-difference step is 2.5e-5 (was 1e-4; case1’s d/dlw is small with the centered bins and the h^2 truncation error at 1e-4 was 1.07e-7), bound unchanged; lw is also checked against the converged gradient.

  • Other binning. pepper’s stick-accumulation branches (unreachable since every non-O3 grid without strain projects) now split linearly too. The template paths were already centered. salt’s field-swept stick paths round to the nearest point (centered, no gradient; the mode raises for grad inputs); its isotropic fixed-field path uses exact-position templates since 0.9.36 (B86). garlic rounds or splits linearly, makespec splits linearly.

Resonance eigenvector interpolation (Options.RediagLimit): deviation from EasySpin (0.9.39, B133)#

pepper’s matrix route (resfields_batch) brackets each resonance between field knots where the Hamiltonian has been diagonalized. For spin systems of dimension 16 or more, a forward run then interpolates the two transition eigenvectors between the knots instead of diagonalizing at the resonance, when

  • both eigenvectors overlap with themselves across the segment by at least Options.RediagLimit (default 0.999), and

  • both levels are separated from every other level by more than 1e-6 of max|E| at both knots.

The interpolation is cubic Hermite, using eigenvector derivatives at the knots from perturbation theory with a phase alignment by overlap. The field is refined by one Rayleigh-quotient Newton step, and Boltzmann energies come from the cubic Hermite model of the levels. Every other resonance is diagonalized as before.

  • Accuracy. Against RediagLimit = 1 (exact), 15 systems of dimension 16 to 216 differed by at most 4.2e-7 of the spectrum maximum (nitroxide biradical with two 14N, [19 4]); 11 of them by less than 5e-8. Of the 34 output-parity cases, the 3 that interpolate changed by 5.5e-7 (Cu(II) + 2 14N, [10 4]), 6.3e-7 (the same with separate transitions) and 1.5e-7 (Mn(II)); the other 31 are identical. Resonance fields agree to ~1e-12 mT; the residual is in the transition intensities.

  • Speed. 1.0-2.0x at 1 thread. Systems whose transition levels are mostly degenerate gain least (symmetric biradical 1.1x), because those resonances are diagonalized.

  • Exact results. Pass Options(RediagLimit=1) (any value >= 1); the result is identical bit for bit to 0.9.38.

  • Not affected. Systems below dimension 16 (one diagonalization costs about as much as the interpolation there), Method='perturb'/'hybrid', and runs on the autograd graph (pepper_autograd with parameters that require grad). Gradient runs therefore return the exact value, which can differ from the forward-only value of the same model by up to the accuracy above.

  • Deviation from EasySpin. EasySpin interpolates linearly with Opt.RediagLimit = 0.95 and takes fields from the energy model. In a prototype of that scheme, Cu(II) + 2 14N was off by 1.3e-3 and Mn(II) by 5e-4. With the cubic scheme at 0.99, Cu(II) + 14N (lwpp 0.3 mT) still reached 1.1e-4, at the same speed as 0.999. Without the degeneracy check, each knot’s diagonalization picks its own basis of a degenerate subspace: Cu(II) + 3 14N reached 4.4e-3 and the symmetric biradical 2.5e-6 (now 4.9e-10 and 3.5e-12).

Tests: torchspin/tests/test_rediag_interpolation.py.

SOPHE triangle projection — near-zero-width triangles on a bin edge (fixed 0.8.4)#

The edge-bin integrals of projecttriangles were written as differences of O(bin index) terms (b − (a + first + 1)/2). For a triangle much narrower than a bin that straddles a bin edge, rounding of those terms was amplified by the 1/width² ramp slope: area errors up to tens of percent per triangle (salt’s zero-field 1H line was 2.6 % too large before a workaround). Fixed in pepper._ramp_bins and pepper_autograd._ramp_bins_t, which now use only the small overlaps with the edge bins. EasySpin’s projecttriangles.c still uses the old expressions; in these geometries torchspin deliberately deviates from it, toward the exact integral. Since 0.9.35 (B85) the projection is torchspin._projection (centered hat bins), which forms every term from the overlap with a half-hat and the relative position inside the facet, and deposits facets inside one axis interval exactly as a point mass at their centroid.

nucspinrmv / nucspinkeep / nucspinadd keep every field (fixed 0.8.2)#

Up to 0.8.1 these rebuilt the spin system from a short list of fields, so ee, ee2, Ham, L/soc/CF*, initState, tdm, dynamics and pulse fields and the nuclear sigma/n/Abund were dropped. pepper Method='hybrid' and saffron’s fast algorithm for S > 1/2 build their exact core with nucspinrmv, so an exchange-coupled dimer, a system with Sys.Ham or a non-equilibrium initState got the wrong core (hybrid on a J = 1000 MHz dimer: cosine 0.0 to the matrix result). Since 0.8.2 they copy the system and filter only the per-nucleus fields, as EasySpin does; hybrid on dimers and Sys.Ham systems matches EasySpin’s hybrid (tests/data/generate_nucspin_core_refs.m). Differences from EasySpin:

  • AStrain belongs to the first nucleus. When that nucleus is removed it is dropped with a UserWarning (EasySpin keeps it, and it then applies to the new first nucleus).

  • initState given for the full spin space (electrons and nuclei) raises when the nuclear dimension changes; electron-space forms (strings, 'xyz', states of the electron spins only) are kept.

  • nn: nonzero couplings raise, as in EasySpin, except when fewer than two nuclei remain (no pair left to couple; saffron’s fast path removes all nuclei).

  • nucspinadd accepts systems with several electron spins (EasySpin raises); a 3-element A is used for every electron.

  • saffron and Sys.Ham. EasySpin’s saffron rejects every Sys.Ham* (saffron.m:130-131). torchspin’s S = 1/2 fast path builds the Zeeman term from Sys.g alone, so up to 0.8.12 it silently dropped nonzero Ham terms (a g given as Ham110/Ham112 gave a signal of exactly zero); since 0.8.13 it raises. The S > 1/2 fast path (since 0.8.2, electronic Hamiltonian from ham()) and the real-pulse engine (Opt.SimulationMode='thyme') include Ham and are kept as torchspin extensions: with the Zeeman term written as Ham110/Ham112 they reproduce the result for the same g to 1e-11 (S = 3/2 3pESEEM, S = 1/2 two-pulse ESEEM with real pulses); there is no EasySpin reference. Open: Ham on the S = 1/2 fast path. Sending S = 1/2 through the general (S > 1/2) path reproduces the fast path’s shape exactly (residual 3e-16 for 14N, 2e-7 for 1H) but at 0.5× its amplitude, so that route needs the normalization worked out first.

Simulator — Lorentzian strain, SpinSystem.HStrainL (0.7.7)#

HStrainL ([3] MHz FWHM, molecular frame) gives every pepper line a Lorentzian profile whose width has HStrain’s form, sqrt(sum_k (HStrainL_k n_k)^2) in frequency and that divided by |dE/dB| in a field sweep.

  • No EasySpin counterpart. EasySpin’s strains are Gaussian. The validation chains to EasySpin through the isotropic case, which equals pepper’s Sys.lw(2) Lorentzian exactly; anisotropic widths are checked against analytic single lines (1e-12) and a brute-force powder sum (0.6 %; the Gaussian HStrain meets the same reference to 0.7 %: the difference is the facet summation with Λ smoothing, shared by both).

  • No Voigt per line. HStrainL together with HStrain, gStrain, AStrain or DStrain raises ValueError. A global Sys.lw (Gaussian and/or Lorentzian) can be added; it is convolved afterwards, as for the Gaussian strains.

  • Linearized in field. As for HStrain, the field width is the frequency width divided by |dE/dB| at the resonance. Where levels curve within a line width (looping transitions, D ≈ hν) this differs from Telser’s field-point line shape; use torchspin.lft.ddpowh(shape='lorentzian') for that.

  • Tails. Lorentzian tails are long. Only resonances inside the sweep window are found, so a line just outside contributes no tail, and the area inside the window is (atan(b) − atan(a))/π of the line’s. A residual Sys.lw is convolved by FFT, which truncates tails at the window edges: with Exp.mwPhase (dispersion decays as 1/x) this is 1.3 % of the maximum in a 40 mT window around a 2 mT line, 0.2 % in 200 mT.

  • Cost. The Lorentzian template is evaluated over the whole axis (a Gaussian’s is windowed), and with Exp.mwPhase per line in NumPy: slower than HStrain on large powder grids.

  • Only pepper and pepper_autograd read HStrainL. resfields returns no Lorentzian widths; salt, garlic, chili and the other simulators ignore the field.

Simulator — user-supplied orientations in pepper (0.7.6)#

Experiment.Orientations ((N, 2) [phi, theta], molecular frame) and Experiment.OrientationWeights (fractions of the sphere, default 1/N, not renormalized) make pepper sum stick spectra over the given field directions with χ-averaged rates.

  • No EasySpin counterpart. EasySpin’s orientation lists are crystal orientations (Exp.SampleFrame), whose rates have B1 along lab x. The validation emulates the χ average with two crystal sample rotations about B0 (SampleRotation={'z',[0 pi/2]}); agreement 1e-4 (Gaussian templates) to 2e-3 (Lorentzian templates, whose tails EasySpin’s finite template truncates).

  • No interpolation, no projection. The spectrum is a plain weighted sum; a quadrature must be fine enough for the line width (a 20000-point Fibonacci sphere reproduces the 1 mT-broadened powder of a rhombic nitroxide to 1e-4 of the maximum).

  • Half-bin offset against the powder (fixed 0.9.35, B85). Before 0.9.35 pepper’s powder projection (like EasySpin’s projectzones/projecttriangles) put bin k on [x_k, x_k + dx) while the template paths centre it on x_k, so a full-sphere quadrature differed from the powder by a shift of dx/2 (3 % of the maximum for an axial S = 1/2 with 1 mT lines at 1024 points over 50 mT). The projection is centered now; a 20000-point Fibonacci sphere matches the powder to 5.9e-5 (absorption) and 1.5e-3 (first harmonic) without any shift. EasySpin keeps the offset.

  • Strain. The powder strain branch (EasySpin’s facet summation with Λ smoothing) is an approximation; a fine quadrature with per-line strain widths differs from it by ~0.7 % of the maximum.

  • Window edges. Only resonances inside the sweep window are found (as for crystals), so a line just outside does not contribute its tail.

  • Raises with Exp.Ordering, SampleFrame, SampleRotation, MolFrame, CrystalSymmetry, Opt.Sites and Opt.separate='transitions'/'sites'. Opt.GridSize/GridSymmetry are ignored without a warning. Only pepper and pepper_autograd read these fields; garlic, salt and the other simulators ignore them.

  • pepper_autograd: field sweeps only (no frequency sweeps, photoselection, initState, mwPhase, hybrid, Opt.separate, as for its powder path). Gradients w.r.t. the orientation angles flow through the resonance search but are not tested. Options.QuadraticZeeman and Options.Transitions apply as in pepper (before 0.9.16 this path ignored both; B64).

Simulator — transition selection, Options.Transitions (0.7.5)#

Options.Transitions (EasySpin Opt.Transitions) replaces pepper’s automatic transition pre-selection by 'all' or a list of 1-based level pairs (u, v). Levels are numbered by ascending energy at each resonance field, so a pair follows the energy ordering through level crossings, as in EasySpin; it does not follow a state label such as mS.

  • Threshold. 'all' switches the Threshold intensity post-selection off. With a list, the post-selection still applies within the list (a transition is dropped when its maximum intensity is below Threshold × the strongest selected one), as in EasySpin. To decompose a spectrum into disjoint sets of transitions whose sum equals the union, pass Threshold=0 (and HybridIntThreshold=0 with Method='hybrid'). The sum then agrees with the union to ~1e-9 relative, not to the last bit: the adaptive field knots of the resonance search depend on the selected pairs.

  • Crystal and O3 paths apply Threshold per orientation (pre-existing behavior), not per transition over all orientations as EasySpin does.

  • Paths that raise. Method='perturb'/'perturb1'/'perturb2' raise ValueError when Transitions is set; EasySpin’s perturbation solvers ignore the option silently. With Method='hybrid' the level numbers refer to the exactly treated core.

  • Validation is stricter than EasySpin. Out-of-range indices, u = v, non-integer indices and an empty list raise; EasySpin silently drops rows above the number of levels and keeps duplicate rows (counting those transitions twice). torchspin removes duplicates.

  • Frequency sweeps. 'all' takes every pair of the full (electron × nuclear) level space. EasySpin’s resfreqs_matrix builds 'all' from the electron levels only and keeps its post-selection threshold; the two agree for systems without nuclei.

  • pepper, pepper_autograd, and since 0.9.14 endorfrq and salt (ENDOR level pairs, see § ENDOR — transition selection) read the field; garlic and the other simulators ignore it. (SaffronOptions.Transitions is a separate, unrelated field.)

  • EasySpin agreement (9 cases: S=3/2 central/outer/all transitions in a powder, with HStrain and in a crystal; the S=1 half-field line; a frequency sweep): cosine ≥ 0.99997, amplitude within 0.05 %. (Before 0.8.5 the frequency sweep was 1–3 % low, at 0.984; that was the narrow-line convolution fixed in 0.8.5, see § Pepper — final line-width convolution.)

Pepper — final line-width convolution (0.8.5)#

pepper and pepper_autograd apply Sys.lw as EasySpin’s pepper.m does (pepper.m:1152-1223), for field and frequency sweeps:

  • A Gaussian or Lorentzian FWHM of at most two increments whose harmonic is 0 is not convolved: the binned spectrum is kept as it is. Before 0.8.5 torchspin convolved it, which lowered peak amplitudes by 1–7 % (the S=1 frequency sweep with lwpp = 10 MHz at 9.8 MHz increments: 0.989, 0.984 for pair (1,2), 0.971 for pair (2,3); now 1.0000).

  • With both widths set, the Lorentzian carries the harmonic and Exp.mwPhase, and is applied first; the Gaussian is an absorption convolution. Before 0.8.5 the Gaussian carried them.

  • Deliberate deviation. For a width of at most two increments that carries a harmonic > 0, EasySpin raises (“smaller than 2 increments - cannot do convolution”); torchspin convolves it with the sampled line shape, as before.

  • Skipping is a discrete decision on the width: in pepper_autograd a skipped width has zero gradient (it stays in the graph), as the spectrum does not depend on it. A fit of lw that starts at or below two increments with Harmonic 0 therefore does not move; use more points. (test_autograd.py::TestNSpinFDAccuracy::test_linewidth_fd_agreement uses 512 points for this reason and asserts a nonzero finite difference.)

  • salt applies the same rule to its ENDOR line width since 0.8.11 (see § ENDOR).

  • EasySpin agreement (tests/data/ref_pepper_narrowlw.mat, 8 cases): amplitude within 2e-7 and cosine 1 − 1e-9 since 0.8.9. Up to 0.8.8 the three field-sweep Voigt cases at Harmonic 1 were 1.002–1.005, from the closed-φ row spline (see § Powder grid interpolation on closed-φ grids).

  • Zero field (Options.ZeroField, 0.7.4). Degenerate levels are merged into clusters, and a transition is labelled by the first (lowest-numbered) level of each cluster; a listed pair selects a zero-field line only when it names those first levels ('all' selects every line).

Pepper and salt — range padding, Options.PaddingMultiplier (0.9.6)#

Before the final line-width convolution (Sys.lw in pepper/pepper_autograd, field and frequency sweeps; lw_mhz in salt), a spectrum that is nonzero at the first or last point of the range is extended at both ends by nPad = round(max(fwhmG, fwhmL) / increment × PaddingMultiplier) copies of the edge values, and cropped afterwards, as in EasySpin (pepper.m:1171-1193, salt.m:858-882). Options.PaddingMultiplier is EasySpin’s Opt.PaddingMultiplier (default 3; 0 switches padding off). Before 0.9.6 torchspin’s convolution padded with zeros, so the points within about two widths of such an end were wrong: a pepper frequency sweep with a Lorentzian lw at Harmonic 1 had end points 0.54 of EasySpin’s, a field sweep with HStrain and a Gaussian lw at Harmonic 1 2.9–3.2 times EasySpin’s.

  • Deliberate deviation: the “nonzero end” test has a tolerance. EasySpin pads when an edge value is exactly nonzero (any(spec(:,1)~=0)). torchspin counts an end as nonzero only when |edge| > 1e-9 × max|row| for some row: its projections leave a round-off floor of about 1e-14 of the maximum in bins that EasySpin’s leave exactly zero, and an exact test would pad spectra that EasySpin does not pad (a rhombic Voigt field sweep cut by the range, lw = [0.5 1.5] mT: end points would move to 1.69 times EasySpin’s). An edge between 0 and 1e-9 of the maximum is therefore not padded where EasySpin would pad; the change padding makes there is of that order.

  • As in EasySpin, one decision covers all rows of a multi-row spectrum (Options.separate, separate transitions): when one row reaches an end, every row is padded by the same count.

  • nPad uses MATLAB rounding (half away from zero) and the widths that reach the convolution step, a skipped one (at most two increments) included, as in EasySpin; on the line-template paths a Gaussian lw is already in the template and is not counted (EasySpin sets Sys.lw(1) = 0, pepper.m:792-804).

  • The decision and nPad are discrete (detached); the edge copies are torch slices, so gradients of pepper_autograd and of fixed-field salt flow through them (checked against central differences with padding active).

  • No padding is applied when no convolution is (only a finite-difference harmonic, or both widths skipped as at most two increments).

Pepper and salt — zero field, Options.ZeroField (0.7.4)#

Options(ZeroField=True) lets pepper frequency sweeps (zero-field EPR/FDMR) and salt fixed-field ENDOR run at Experiment.Field = 0. The default is unchanged in results, with one difference in when the error appears: Experiment(Field=0, ...) now constructs, and the familiar ValueError("Experiment.Field must be positive (mT).") is raised by the simulator call (pepper/salt without the option; garlic, chili and resfreqs_perturb always). A negative field still raises in the constructor.

  • Degenerate levels. At B = 0 the Hamiltonian is the same for every orientation, and inside a degenerate subspace (Kramers doublets, accidental degeneracies) the eigenbasis is arbitrary. The levels are therefore grouped into clusters (neighbors closer than 1e-9 × the level spread, at least 1e-9 MHz, are one cluster). Each transition is a pair of clusters. Its rate·polarization is summed over all level pairs between the two clusters, and its position is the difference of the cluster mean energies. This is done before slot tracking, threshold pruning and pair preselection. Levels that are really split by less than the tolerance are merged. Transitions inside a cluster have zero frequency and are not returned. With separate='transitions' the rows are cluster pairs.

  • Powder average. The B1 average is taken over the powder grid directions: the perpendicular-mode rate (|μ|² − |n·μ|²)/2 averages to Σ|μ|²/3. The one-orientation O3 shortcut is replaced by a D2h grid. The SOPHE quadrature of this quadratic form is accurate to about 1e-4 at GridSize = 19.

  • Strain at B = 0. gStrain scales with B, so it vanishes. HStrain stays direction dependent (HStrain² · n² over the grid directions n, as in EasySpin, even though no static field defines a direction). For DStrain and AStrain each diagonal element ⟨u|∂H|u⟩ is replaced by its cluster mean tr(P_a ∂H)/n_a. This is exact for Kramers doublets, where time-even operators are proportional to the identity. For accidental non-Kramers degeneracies it ignores the splitting the strain itself would cause.

  • Lines between axis points. At B = 0 every orientation puts a line at one frequency, so the powder projection deposits it as one point mass, split linearly between the two nearest axis points (centered hat bins since 0.9.35, B85; a line exactly on x_k goes to x_k, as in EasySpin). Before 0.9.35 the whole line went into the box [x_k, x_k + dx) that contains it, as in EasySpin, and a line exactly on a box edge landed in either neighbor depending on the last bit of round-off (4 % of the maximum for a 300 MHz line at 10 MHz bins); the linear split changes only by ulps there. With an interpolated grid (e.g. GridSize [19 4]) pepper._zf_const_pos gives every interpolated orientation the coarse position, so the facets have zero width exactly. Tested against EasySpin in test_pepper_zerofield_edge.py (0.9.1); a 4000-point Fibonacci sphere matches the zero-field powder to 0.077 % (0.74 % before, on the dx/2-shifted axis).

  • Not supported. Non-equilibrium populations (Sys.initState) raise with ZeroField. Frequency sweeps have no differentiable pepper path (pepper_autograd raises for them, as before). The zero-field resonances from resfreqs_batch (positions, summed intensities) are on the graph and tested against central differences. Pair preselection does not drop “pure nuclear” transitions at zero field: the high-field heuristic would remove the F = 0 ↔ F = 1 hyperfine line.

  • salt. Zero field always uses the matrix path (first-order ENDOR theory needs a quantizing field) and the interpolation/projection powder average. It needs a grid with more than two orientations. Line positions do not depend on orientation, so each line is projected as a delta into one bin. The spectrum is therefore piecewise constant in the line positions: gradients reach the parameters through the intensities, not through the positions. With ExciteWidth, the orientation-selection weight leaves out intra-cluster pairs. EasySpin’s salt is not compared at zero field; the tests use closed forms and a brute-force cluster sum.

  • Validation. pepper matches EasySpin, which accepts Exp.Field = 0 for frequency sweeps and resolves the degeneracies with the eigenvectors of μ_zL in each degenerate block, on 5 cases (ref_pepper_zerofield.mat): cosine ≥ 0.99999999 and amplitude within 4e-6, except the isotropic S = 1/2 + ¹H case (EasySpin keeps the O3 shortcut, so amplitude agrees to 6e-4). Field = 0 agrees with the default path at Field = 1e-4 mT to 1e-11 relative (pepper). For salt the line areas agree to 1e-7; the max-norm difference is a few % because at a small field a line near a bin edge is split over two bins.

  • salt with Options.ZeroField and Options.Enhancement (0.7.3) together raises NotImplementedError: the zero-field cluster path sums nuclear-only rates.

Higher-order Zeeman terms (Sys.Ham*): deliberate deviation from EasySpin (0.6.7, 0.9.8, 0.9.13)#

ham(Sys) returns (H0, mux, muy, muz) with H(B) = H0 − μ·B. The simulators that work from this decomposition (pepper’s resonance search, levels, endorfrq, salt, curry, nucfrq2d) rely on it agreeing with ham(Sys, B0).

  • Linear terms (Ham1xx). EasySpin’s ham.m adds the linear-in-B part dH/dB to the moment operators instead of subtracting it. Its own H0 − μ·B therefore has the opposite sign of these terms to its ham(Sys, B0); the EasySpin reference data show this to machine precision. torchspin up to 0.6.6 copied this. Since 0.6.7 the term enters as −dH/dB, so H0 − μ·B equals ham(Sys, B0). torchspin’s mux/muy/muz differ from EasySpin’s for these systems by design; H0 and ham(Sys, B0) still match EasySpin.

  • Effect on results. Without nuclei, flipping the sign of the entire linear term leaves the energies and transition probabilities unchanged (time reversal), so field-swept EPR spectra were not affected. With nuclei, the term had the wrong sign relative to the nuclear Zeeman interaction, which changes ENDOR and nuclear frequencies and the intensities of forbidden transitions.

  • Quadratic and cubic terms (Ham2xx, Ham3xx) cannot be written as H0 − μ·B. As in EasySpin, they enter only ham(Sys, B0). Simulators that use the decomposition ignore them unless Options.QuadraticZeeman=True (0.7.1, next section).

  • Perturbation theory raises for Ham (0.9.8). endorfrq_perturb, resfreqs_perturb, resfields_perturb/resfields_perturb_batch, and pepper/pepper_autograd with Options.Method='perturb', 'perturb1' or 'perturb2' build the electron Zeeman term from Sys.g alone. With g given as Ham110/Ham112, Sys.g is zero, so up to 0.9.7 they returned NaN frequencies, no resonance fields, or an all-zero spectrum without an error, and other nonzero terms of order lB ≤ 1 were dropped. They now raise ValueError for any nonzero Ham term of order lB ≤ 1, and the message points to Sys.g or the matrix method. Terms of order lB ≥ 2 still pass: every solver drops them unless Options.QuadraticZeeman=True, which the perturbation solvers already reject. pepper raises for every 'perturb*' call with such a system, including frequency sweeps and strained or multi-electron systems, where torchspin quietly ran the matrix solver instead (that run was correct; a frequency sweep in EasySpin goes to resfreqs_perturb, which raises). EasySpin is not uniform here: resfreqs_perturb.m:75-77 rejects every Sys.Ham*, but resfields_perturb.m and endorfrq_perturb.m do not check, so EasySpin’s pepper with Method='perturb' gives an all-zero spectrum for a Ham-only Zeeman term, as torchspin did. torchspin raises deliberately. The default Method='matrix' (and 'hybrid') include Ham and reproduce the same g to 1e-9 or better.

  • Slow-motion and fast-motion codes raise for Ham (0.9.13). chili (and chili_sle), cardamom and fastmotion/fastmotion_t build the Zeeman term from Sys.g only and ignored Sys.Ham without an error; with g given as Ham110/Ham112 they ran with g = 0. They now raise ValueError for any Sys.Ham entry, as EasySpin’s chili (chili.m:160) and torchspin’s garlic do. EasySpin’s cardamom and fastmotion do not check: cardamom runs with g = 0 and fastmotion fails because Sys.g is missing.

  • pepper’s automatic field range (0.9.13). Without Exp.Range/Exp.CenterSweep the range comes from the principal values of Sys.g (EasySpin pepper.m:241-272). For a Ham110/Ham112 Zeeman term g is zero; up to 0.9.12 this raised ZeroDivisionError, and EasySpin fails with an index error (pepper.m:324). torchspin now raises a ValueError asking for Exp.Range or Exp.CenterSweep.

  • gStrain with a Ham110/Ham112 Zeeman term (0.9.13): deliberate deviation. The g-strain widths are gStrain/g; with g = 0 they were infinite and pepper returned an all-zero spectrum without an error, as EasySpin’s pepper does (with a gFrame EasySpin returns a nonzero but wrong spectrum). torchspin now takes g from the g-equivalent matrix of the Ham110/Ham112 terms (ham_ezho.ham_linear_g), in the g frame given by Sys.gFrame. The result equals the same system with that g as Sys.g (to 1e-13) and EasySpin’s spectrum of that system (cosine > 0.9999999; ref_ham_gstrain.mat). If the g-equivalent matrix is not diagonal in Sys.gFrame, torchspin raises ValueError, as for gStrain with a full g matrix. Other lB = 1 terms (Ham13x, …) are not part of this g.

  • salt (0.9.5). EasySpin’s salt rejects every Sys.Ham* (salt.m:132); torchspin simulates them on its matrix paths (§ ENDOR (salt)).

Simulator — field-quadratic Zeeman terms, Options.QuadraticZeeman (0.7.1)#

By default (QuadraticZeeman=False) the simulators use H = H0 − B n·μ and drop the Sys.Ham terms of order lB = 2 and 3, as described above. With Options.QuadraticZeeman=True (or levels(..., quadratic_zeeman=True)) these terms are included as H(B) = H0 − B n·μ + B² n·G2·n + B³ G3[n,n,n], which equals ham(Sys, B·n).

  • Supported: pepper and pepper_autograd with Method='matrix' (powder grids including O3, crystals, Exp.Orientations (pepper_autograd from 0.9.16), field and frequency sweeps, strains), levels, resfreqs_matrix, and resfields_batch/resfreqs_batch (keyword zeeman_ho=).

  • Raise NotImplementedError when the option is on and a nonzero lB ≥ 2 term is present: Method='perturb*' (also where pepper would otherwise fall back to the matrix solver), Method='hybrid', resfields (single orientation), resfields_perturb(_batch), garlic, salt; pepper_autograd with 'perturb*'. Terms of order lB ≥ 4 raise in every path.

  • Not covered by the option: resfields_eig (configured by EigOptions), endorfrq, curry, nucfrq2d and levelsplot still drop lB ≥ 2 terms.

  • Transition moments are those of the linear moment operators μ, as in EasySpin. The B1-linear part of the quadratic term, 2 (B0·G2·B1), is not included in the transition operator; its relative size is about 2|n·G2·n|B/(gμB).

  • dB/dE: torchspin uses the full slope ⟨v|dH/dB|v⟩ − ⟨u|dH/dB|u⟩. EasySpin’s resfields builds its level model from the full ham(Sys, B) but takes dB/dE from the linear moment only. Line intensities therefore differ by the ratio of the two slopes (0.03–0.3 % for the reference cases).

  • EasySpin frequency sweeps with Sys.Ham2xx fail in EasySpin releases before StollLab/EasySpin d46e5ef9 (2026-09-26): their resfreqs_matrix.m looks for fields named ZB* to detect higher-order terms, misses Sys.Ham* and then calls ham with four outputs, which errors. With that fix, torchspin’s frequency sweep matches EasySpin (S1_ham2_freqsweep in ref_pepper_quadzeeman.mat: cosine 1.0000000, amplitude 0.99988; without the Ham terms the cosine to that reference is 0.976).

  • Sys.Ham coefficients are differentiable since 0.9.13 (before, ham_ezho detached them). Gradients flow through ham, levels, pepper_autograd (including the quadratic terms with QuadraticZeeman on powder grids) and pepper, which sends a system with a Ham coefficient that requires grad to its differentiable path. Values are bit-identical to 0.9.12.

  • In the McGavin–Tennant–Weil formalism the field enters as a rank-lB spherical tensor, so a pure B²·identity term cannot be written (Ham200 is ignored by ham_ezho, as in EasySpin). This does not change transition energies.

Simulator — extra field-independent operators (Sys.H0Extra) (0.7.2)#

SpinSystem.H0Extra = [(coeff, op), ...] adds Σ coeff·op (MHz) to H0 inside ham. It is not an EasySpin field, so there is no EasySpin reference: the tests check that a zero-field splitting or a hyperfine S·A·I written as an operator reproduces the native term (levels, resonance fields, pepper spectra), and that a U term matches a hand-built Hamiltonian.

  • Only ham-based solvers. Solvers that assemble the Hamiltonian from the interaction tensors raise ValueError when H0Extra is set: pepper with Method='perturb*' or 'hybrid' (for a component with nuclei), pepper_autograd with 'perturb*', resfields_perturb, resfreqs_perturb, endorfrq_perturb, salt for one electron spin (its EPR and ENDOR steps use perturbation theory), garlic, chili, fastmotion, cardamom, saffron’s fast (ideal-pulse) algorithm, and nucspinrmv/nucspinkeep/nucspinadd (the operator lives on the full spin space and cannot be reduced or extended).

  • No isotopologue expansion. Isotope mixtures in Nucs ('Cu', '(63,65)Cu') and sets of equivalent nuclei (n > 1) are rejected when the spin system is built: the expansion changes the nuclei, so one operator cannot fit every isotopologue. Give explicit isotopes and build one component per isotopologue, scaling the operator yourself if it involves the nucleus.

  • Heuristics ignore it. pepper’s automatic field range, the rule that drops pure nuclear transitions in the transition pre-selection (it reads Sys.A), and the strain widths (HStrain, gStrain, AStrain, DStrain act on the native tensors only) do not see H0Extra. Give Exp.Range explicitly when the extra term moves the lines.

  • Symmetry. hamsymm always uses the eigenvalue probe for these systems (never the O3 shortcut or the geometric analysis). The probe only tests the candidate frames of the native tensors (molecular frame, gFrame, DFrame, AFrame, …), so a term whose symmetry axes lie elsewhere is classified in a lower group (down to Ci). This is safe but can cost grid points; pass Opt.GridSymmetry to override.

  • Units and basis. op must be in the full spin-system basis in sop order (electrons, nuclei, then orbital momenta); coeff * op is in MHz. The operator is checked for shape and Hermiticity (1e-10 relative), and coeff must be real.

  • Gradients. Reverse mode works through levels, ham and pepper_autograd; forward mode (dual numbers) works through ham/levels, not through pepper (known issue).

Automatic grid symmetry — strains are symmetry inputs (deliberate deviation from EasySpin, 0.9.24)#

hamsymm, and with it the automatic GridSymmetry of pepper, pepper_autograd, salt, saffron, saffron_thyme, orisel, nucfrq2d and the broadband autograd model, treats every strain as one more tensor in its own frame, because the strain widths depend on the field direction (B82):

  • HStrain / HStrainL: diag(HStrain²) in the molecular frame.

  • gStrain: per electron G·G with G = R_g2M diag(gStrain/g) R_g2M' (the matrix square the width formula uses since 0.9.33, so strain collinear with g has the symmetry of g, in the g frame; before, the element-wise square G∘G gave Ci for any tilted g frame, B84).

  • AStrain (single electron, first nucleus): A·A and G·A + A·G, A frame (A∘A and G∘A before 0.9.33).

  • DStrain: Dinfh about the D-frame z axis without E strain, otherwise D2h in the D frame (also with DStrainCorr).

The geometric analysis combines them after the Hamiltonian tensors; the eigenvalue analysis also compares the strain widths at its probe directions. Strain-free systems, and strains that share the Hamiltonian’s symmetry, get exactly EasySpin’s group and frame.

EasySpin’s hamsymm.m has no strain term (its p_gridsetup.m only lowers Dinfh to D2h for initState, which torchspin’s pepper keeps). For S = 1/2, g = [2.05 2.05 2.15], lw 0.3 mT, HStrain = [200 20 20] MHz (or gStrain = [0.02 0.002 0.002]), 9.5 GHz, GridSize [31 4], EasySpin picks Dinfh and its spectrum is 78.7 % (76.0 %) of the maximum off its own D2h spectrum, while D2h [31 4] and [91 4] agree to 0.9 % (0.4 %) (EasySpin main, MATLAB R2024b, tests/data/generate_hamsymm_strain_refs.m; torchspin < 0.9.24 behaved the same). torchspin’s default spectrum now matches EasySpin’s forced-D2h one. Consequences:

  • Two test_pepper_dstrain_matlab_validation.py EasySpin cases (two S = 1 spins with axial D and E strain) are strict xfails: EasySpin’s Dinfh spectrum is 5.9 % off a fine D2h grid, torchspin’s default 0.2 %; with Dinfh forced, torchspin still reproduces EasySpin.

  • orisel with a molecular-frame HStrain can return a lower-symmetry (larger) default grid than EasySpin (tilted rhombic g + HStrain: Ci instead of D2h).

  • Systems with strain can take longer (more orientations).

Since 0.9.24 saffron, saffron_thyme, nucfrq2d and the broadband autograd model also apply hamsymm’s symmetry frame (rotate the grid into the molecular frame, as pepper does) and let hamsymm errors propagate; before, a tilted symmetry frame gave wrong results there (B83).

Automatic grid symmetry — differentiated parameters (0.9.26)#

The powder grid is chosen outside the autograd graph, so it must hold along every direction the gradient measures, not only at the current values (B1). Before 0.9.26 an axial g with grad used the Dinfh grid (Cu(II), g = [2.05 2.05 2.25], A = [40 40 550] MHz: dL/dg = [-11.51e6, +0.09e6, -2.78e6] vs converged central differences -5.7189e6 for g_x and g_y), an isotropic g the O3 grid ([4.57e6, 4.57e6, -4.57e6] vs ~1.598e6 each), and salt likewise (14N ENDOR dA = [-0.217, 0, 0.053] vs -0.1079 for x and y).

torchspin.hamsymm.grid_symmetry (used wherever the symmetry is automatic):

  • No symmetry input requires grad (tensors, frames, B, Ham, CF*, H0Extra, strains): exactly hamsymm, bit-identical results, no extra cost.

  • Otherwise: the symmetry of the parameterization. The autograd leaves behind the grad-requiring inputs get a deterministic generic perturbation dp; each input moves along J @ dp (double-backward Jacobian-vector product on the existing graph; the graph is kept and nothing is written to .grad), scaled to 1e-6 relative (Euler angles 1e-2 rad, above the 0.2° collinearity tolerance), and hamsymm runs on that copy. An input that is itself a leaf (a tensor passed straight to SpinSystem) is its own parameterization. Results: a scalar g keeps O3; [g_perp, g_perp, g_par] from two leaves keeps Dinfh; an axial g given as three independent numbers gets D2h, an isotropic one D2h; an axial g with a rhombic A rotated about z C2h; differentiated Euler angles or full-tensor entries Ci.

  • Frame check. Two independent perturbations are compared; if their groups differ or their frames are not the same axes up to order and sign (the symmetry frame moves with the parameters), the grid is Ci, which is exact for any Hamiltonian.

  • Fallback. If the graph does not support double backward, every grad-requiring input is perturbed on its own (field-level), which is never less safe but may cost a lower group (a scalar g would get D2h).

  • Cost. The decision itself takes ~0.5 ms (two hamsymm runs and one JVP; the first call in a process ~0.2 s for autograd set-up). A gradient run on an axial system given as three independent numbers uses D2h: forward + backward 0.33 s vs 0.016 s on Dinfh (Cu(II), GridSize [31 4], 1024 points).

  • Spectra. A gradient run whose parameterization breaks an accidental symmetry differs from the forward-only spectrum by the grid discretization error: 0.1 % of the maximum for that Cu(II) case, but for an isotropic g given as three numbers the projection deposits every line as one point mass (all orientations resonate at one field) where O3 draws an exact template: 2-3 % (first harmonic, lw 1 mT, 512 points over 60 mT; 2-5e-4 with 4096 points; 17 % and 2.6 % before the centered bins of 0.9.35, B85), as pepper with a forced D2h grid. salt’s isotropic fixed-field path uses templates too since 0.9.36 (B86); three A leaves (D2h) give the O3 gradient to 4.1e-2 (512 points over 10 MHz, lw 0.3 MHz) and 4.2e-3 (2048 points). Set Options.GridSymmetry explicitly to compare gradient and forward-only runs, or parameterize the symmetry you mean (a scalar g, shared leaves).

  • The gradient is the exact derivative of the forward model on the chosen grid. Along directions that keep the accidental symmetry (g_z of an axial g given as three numbers) the forward-only model stays on its own grid, so its finite difference differs by the same discretization error.

  • At exactly isotropic g the pepper_autograd gradient on any fixed non-O3 grid (D2h, Ci) is off the central difference by ~8e-4 relative (coincident resonance fields in the projection); 1e-4 away from isotropy it is exact.

orisel — differences from EasySpin (0.9.0)#

Since 0.9.0 orisel runs EasySpin’s model (full diagonalization at Exp.Field, orisel.m:110-153; weights agree to 7e-13 in test_orisel.py) for any number of electron and nuclear spins. Before 0.9.0 it used one-electron perturbation theory over Exp.Range with a field-domain Lorentzian at the g = 2.0023 field, and its weights did not follow Exp.Field (bug B26). Deliberate differences:

  • Return values. EasySpin’s output depends on nargout; torchspin returns (weights, phi, theta), or (Weights, Transitions, phi, theta) with per_transition=True. Transitions keeps EasySpin’s 1-based level numbering. There is no plot (EasySpin’s nargout = 0 / Opt.Display).

  • Inputs. Exp.Field must be positive (EasySpin also runs at 0 mT, where degenerate levels make the per-pair rates basis-dependent), and a negative ExciteWidth is rejected. Exp.Orientations is (N, 2) [phi, theta]; EasySpin’s 3 x N form (whose third angle it ignores) is not accepted.

Pepper — absolute intensity (fixed 2026-09-01)#

Until 2026-09-01 pepper() multiplied the spectrum by one of four empirical factors (8.48, 6.29, 4.27, 3.806) chosen by accumulation path. These are gone. The intensity chain now follows EasySpin exactly: resonance-field intensities carry the Aasa–Vänngård factor dBdE = 1/|⟨v|μ_z|v⟩−⟨u|μ_z|u⟩| and the 1/∏(2I+1) share per hyperfine line, orientation weights sum to 4π, the χ integral contributes 2π, and stick/line accumulations are converted to a spectral density by 1/ΔB. Verified against EasySpin’s own checks: the isotropic-powder closed form ∫spec dB = 8π²·TransitionRate·dBdE (matrix and perturbation methods, 1e-4), nuclei-independent double integrals (1e-6), per-line intensities from resfields (7 digits), and amplitude ratios of 1.00 ± 0.02 against every MATLAB pepper reference. The only path still off is the Ci/C1 scattered-interpolation path (≈5 % low), tracked in the round-2 entry in CHANGELOG.md.

Pepper — tilted axial symmetry frames (fixed 2026-09-01)#

hamsymm reproduces EasySpin’s point-group and symmetry-frame detection exactly. Until 2026-09-01 pepper interpolated the rotated grid in the molecular frame, which broke every Dinfh system whose unique axis is not the molecular z (tilted gFrame/DFrame, x- or y-axial tensors: cosine 0.34 or an all-zero spectrum). Interpolation and zone weights now use the symmetry-frame grid; these cases match MATLAB to cosine 0.99996–1.0 (test_pepper_matlab_validation_ext.py).

Pepper — strain broadening (validated 2026-09-01)#

Strain widths are validated per transition and orientation against EasySpin resfields (≤1.3e-3 relative; the residual is EasySpin’s linear eigenvector interpolation between field knots), except g/A strain with a tilted g or A frame, where torchspin deviates deliberately since 0.9.33 (§ Field sweeps — gStrain/AStrain widths with tilted frames). Powder spectra with H/g/A/D strain, including several electron spins, tilted D frames and correlated D/E strain, match EasySpin to cosine ≥0.999 and amplitude within 3 % on 24 MATLAB cases (test_strain_*_matlab_validation.py, test_pepper_dstrain_matlab_validation.py). pepper follows EasySpin’s summation scheme for anisotropic widths (per-facet Gaussians on the interpolated grid with Lambda smoothing) and its level-pair transition bookkeeping.

Pepper — strain broadening with non-equilibrium populations (fixed 0.9.40)#

Up to 0.9.39, Sys.initState together with any HStrain, gStrain, AStrain or DStrain lost all emissive intensity: the strain summation discarded facets of negative intensity, so a polarized triplet spectrum kept only its absorptive lines (silently, with a too-large integral). Spectra without strain, and every spectrum with thermal populations, were correct. Since 0.9.40 signed intensities are kept, as in EasySpin; test_pepper_initstate_strain.py holds four EasySpin references (cosine >= 0.9996) and two self-consistency checks (vanishing strain equals no strain; mirrored populations negate the spectrum). Polarized spectra fitted with strains on 0.9.39 or earlier should be refitted.

With a tilted DFrame and populations in the 'xyz' basis, EasySpin’s default [19 4] grid is not converged (its own [91 4] result differs by 2.3 % of the maximum), so the comparison with it at the default grid is cosine ~0.9996 rather than 0.99999; torchspin at [19 4] is within 0.7 % of its converged result. The same holds without strain (noneq_xyz in ref_pepper_features2.mat).

Chili — slow-motion SLE (rewritten 2026-09-01)#

chili() is now a function-by-function port of EasySpin’s general Liouvillian method (torchspin/chili_sle.py): LjKKM basis with the same pruning switches (jKmin, evenK, highField, pImax, MpSymm), ISTO interaction coefficients, rotational-basis operators, the Liouville Hamiltonian, the diffusion superoperator with orienting potentials of any (L, M, K), the equilibrium starting vector, the Lanczos/Lentz continued fraction (and direct / eigenvalue solvers), EasySpin’s field-sweep methods and output scaling, post-convolution nuclei and multi-component input. Every intermediate was checked against EasySpin’s Opt.Diagnostics dump (basis identical, H and Γ to machine precision). On 60 MATLAB cases mirroring EasySpin’s chili tests, 59 match to cosine ≥0.999 and amplitude within 2 %. The other, simple_tc1e-07 (cosine 0.998, amplitude 1.066), is a strict xfail: its reference is EasySpin’s default fast output, which stopped its continued fraction early (with Opt.Threshold=1e-10 EasySpin’s own output moves by cosine 0.9979 / amplitude 1.069 and matches torchspin to cosine 0.9999966, tested separately).

M–pS–pI symmetry basis (MpSymm; derived rule since the B114/B115 fix, replacing the empirical rule of 2026-09-02). Without director tilt, and with an orienting potential that has only M = 0 terms, the Liouvillian conserves pS + pI − M (Meirovitch et al., J. Chem. Phys. 77, 3915 (1982), Eq. A47). The S_x starting vector then splits into two decoupled halves, pS + pI − M = +1 and −1, and the −1 block is the complex-conjugate mirror of the +1 block, so the plain-basis spectrum is exactly I(z) = ½[I₊(z) + conj(I₊(conj z))]. torchspin computes only the +1 block (about 6× fewer functions) and adds the mirror term (the same tridiagonalization evaluated at the mirrored frequencies). With highField=True (pSmin = +1) there is no −1 half and the factor is 1. MpSymm=None (default), True and False therefore give the same spectrum (measured against the plain basis solved directly: 1e-15 for a nitroxide and ⁶³Cu, 5e-11 for S = 1 with D = 100 MHz, 2e-8 with D = 500 MHz). Deviations from EasySpin, by design:

  • MpSymm=None prunes for every untilted system (any spin system, potential with M = 0 only, GridSize=1 or an untilted SampleFrame); under tilt or with M ≠ 0 potential terms it uses the plain basis.

  • An explicit MpSymm=True raises ValueError under director tilt (powder grid with a potential, tilted SampleFrame) or with M ≠ 0 potential terms, where the symmetry does not hold. EasySpin’s general method prunes anyway (0.9.32 did the same: cosine 0.67, 6.9× amplitude for a nitroxide with Potential=[2 0 0 1], GridSize=5).

  • With MpSymm=True EasySpin’s general method drops the −1 half and returns twice the plain-basis amplitude; torchspin returns the plain-basis spectrum. EasySpin’s fast builder (its default for one S = 1/2 electron with ≤ 2 nuclei and no potential) prunes nothing and computes the plain-basis spectrum, which is what torchspin’s default matches (MATLAB: highField fast vs general direct, ratio 1.00000; 0.9.32 returned 0.5× with highField=True, B114).

Lanczos stopping rule (B116). EasySpin stops at the first check step (every min(10, ⌈N/20⌉) steps) whose Lentz change is below Opt.Threshold. In the pseudo-norm (complex-symmetric) recursion a near-breakdown makes that one-step change small while the continued fraction is far from converged: for the ¹⁴N nitroxide at τc = 100 ns (default LLMK, plain basis, 256 points) EasySpin’s general Lanczos and torchspin 0.9.32 both stop at step 40 with cosine 0.9648 against the direct solve, and EasySpin’s default fast output stops early in the same way (cosine 0.9647 against general-direct; with Opt.Threshold=1e-10 it converges to cosine 0.999998). torchspin accepts a Lentz-converged spectrum only if it then moves by less than 100 × Threshold (relative to its maximum) over the next interval, and returns that spectrum, so converged results are unchanged. A full-length tridiagonalization (the Krylov space is the whole basis) or an exact breakdown counts as converged. If the Lanczos does not converge, EasySpin returns ones(nPoints) with a message; torchspin warns once (RuntimeWarning) and uses the direct solver. On the stored EasySpin cases that use the plain basis on a powder grid (simplepotential_grid19, momdsimple) the more converged result moves by up to 0.1 % in amplitude relative to EasySpin’s (early-stopped) reference.

Not ported: the fast C builder (chili_lm.c), Sys.Exchange, Exp.Ordering, Opt.useLMKbasis, and the automatic sweep range. The basis size (Opt.LLMK) must be chosen by the user, exactly as in EasySpin (there is no adaptive basis selection in EasySpin either).

Rescale per orientation (0.9.39, B129, deliberate deviation). EasySpin’s chili.m rescales each orientation’s Liouvillian by its own max|L| but divides the summed powder spectrum by the scale of the last orientation only (and, for an explicit field sweep, of the last field point), so every other orientation is weighted by scale_i/scale_last. torchspin divides each solve by its own scale, which makes Rescale a pure numerical device: on and off agree to the solver tolerance. Powder spectra with an orienting potential or strongly anisotropic interactions move by up to about 1 % against EasySpin (Cu(II), potential, 5 ns: 7.5e-3).

ENDOR (salt)#

Since 2026-09-01 salt() implements EasySpin’s fixed-field, rf-swept powder ENDOR (Experiment.Field + RF Range, optional ExciteWidth orientation selection) and is validated on an 8-case suite mirroring EasySpin’s salt tests (test_salt_matlab_validation.py). Since 2026-09-03 the powder average uses EasySpin’s scheme (grid interpolation with GridSize=[N, Ninterp] followed by triangle/zone projection) instead of stick binning, so the reference Opt.GridSize = [20 5] case reproduces MATLAB to cosine 0.999998. The three orientation-selected (ExciteWidth) cases remain at cosine 0.993–0.998; the residual there is in the orientation weights, not the grid. Since 2026-09-06 the fixed-field path is differentiable (torch interpolation / projection / convolution shared with pepper_autograd; gradients vs finite differences 1e-6–1e-8 for g, A, Q, lw, test_salt_autograd.py); the field-swept (multi-field) mode is not and raises for grad tensors. Isotropic systems (O3 grid, one orientation) were binned as sticks (.item(), nearest point) and returned a detached spectrum until 0.9.36 (B86); they now take bin-integrated Gaussians of width lw at the exact line positions from the on-graph transitions (pepper’s O3 template path; lw = 0: linear split between the two nearest points). Gradient vs central differences 3e-11; forward error on 512 points over 10 MHz 2.6 / 7.8 / 15 % -> 0.10 / 0.88 / 3.4 % of the maximum (lw 0.3 / 0.1 / 0.05 MHz) against a 32x finer axis. EasySpin (salt.m:657-668) still builds sticks with lisum1i at width dx/100 and convolves; it skips a Gaussian lw of at most two increments, which the template does not.

  • Method choice. salt ignores Options.Method. For one electron without Q and without Sys.Ham it uses first-order perturbation theory (EasySpin Opt.Method='perturb1'), otherwise the matrix path; EasySpin’s default is always 'matrix'. Since 0.8.1 both give the same intensity scale (|⟨i|μ⊥|j⟩|² in (MHz/mT)²); the first-order path matches EasySpin perturb1 to round-off and EasySpin’s default to the first-order error (0.3 % in area for 1H and 1H+14N with |A| ≤ 7 MHz at 326.5 mT, about 1 % for 1H with |A| up to 16 MHz).

  • Field-swept mode (Experiment.Range). EasySpin’s salt has no such mode (salt.m:199); torchspin weights each ENDOR spectrum by the EPR intensity at its resonance field. Since 0.9.9 the perturbation (one electron) and matrix EPR solvers share the infinite-temperature 1/prod(2I+1) nuclear-sublevel polarization, as EasySpin’s resfields and resfields_perturb do; before, the matrix path was prod(2I+1) times too large (6x for 1H + 14N). The ENDOR step sums the nuclear transitions of all levels, so a spectator electron spin doubles them.

  • Absolute scale vs EasySpin. The fixed-field spectrum is the per-bin, orientation-averaged amplitude: EasySpin’s salt output times Δx/(8π²) (Δx = rf bin width in MHz; EasySpin integrates over χ with 2π and returns a density), for every path.

  • Bin positions (deliberate deviation since 0.9.35, B85). The triangle/zone projection centers axis point k on f_k (hat bins; a line at 13.408 MHz with Δx = 0.01 goes 20 % to 13.40 and 80 % to 13.41). EasySpin’s salt assigns it to the bin whose lower edge is at or below it (13.40), half a bin low on average, as torchspin did before 0.9.35. See § Centered projection bins.

  • gnscale. The first-order path (frequencies and intensities) ignores Sys.gnscale, as EasySpin’s endorfrq_perturb.m does; the matrix path applies it (via ham_nz).

  • Equivalent nuclei. salt raises for Sys.n > 1, as EasySpin does (salt.m:135-136). Before 0.8.10 it ignored n and returned the spectrum of a single nucleus. Give equivalent nuclei as separate entries of Nucs.

  • Higher-order Zeeman terms (Sys.Ham*), deliberate deviation (0.9.5). EasySpin’s salt rejects them (salt.m:132). torchspin sends every system with a Sys.Ham entry to the matrix paths: resonance fields by resfields_batch in the field-swept mode, ENDOR transitions by diagonalizing ham() (zero-field and linear-in-B Ham terms included exactly), also for one electron without Q. The first-order paths build the Zeeman term from Sys.g only, which is zero when Ham110/Ham112 carry it; before 0.9.5 such a system gave a fixed-field spectrum 12.8x too large with Larmor-only lines (8.9x with ExciteWidth) and an all-zero field-swept spectrum (B35). Now Ham110/112 equal to g gives the g spectrum of the matrix path to 2e-12 (test_salt_ham.py). Field-quadratic and cubic terms (lB >= 2) are dropped, as in pepper with Options.QuadraticZeeman=False; QuadraticZeeman=True raises. An explicit Options.Method='perturb*' with Sys.Ham raises ValueError. In 0.9.5 Ham coefficients carry no gradient (ham_ezho detaches them; § Higher-order Zeeman terms); B53 keeps them on the graph, after which fixed-field salt gives d spc/d Ham110 equal to a central difference (-1.46337e-9 vs -1.46399e-9 for the 1H case above). The field-swept mode is not differentiable: a Ham coefficient that requires grad raises NotImplementedError there, as for g, A, D, Q and ee. In the field-swept mode the Ham spectrum comes from resfields_batch and the same system given with g from resfields_perturb_batch; in 0.9.5 their scales differ (Ham 1.99x the g spectrum for the 1H case above, 6.0x with an added 14N; B44). With the B44 fix (0.9.9, 1/prod(2I+1) nuclear-sublevel polarization) they agree to the first-order error: amplitude 0.994, cosine 0.99989 (1H); 0.992, 0.99997 (1H + 14N). Fixed-field spectra are not affected.

  • Orbital angular momentum. salt raises for Sys.L, as EasySpin does (salt.m:133). Before 0.9.5 the first-order path ignored it (B45).

  • Line width (0.8.11). lw_mhz is a Gaussian FWHM, applied as EasySpin’s salt.m applies Sys.lwEndor(1) (salt.m:899-911): a width of at most two rf increments is not convolved, as the line is delta-like. Before 0.8.11 torchspin convolved it, which lowered peaks of under-resolved spectra (1H, g = [2 2.05 2.1], A = [5 8 12] MHz, 0.02 MHz increments: 0.933 of EasySpin at 1.5 increments, 0.900 at 2.0); all five cases of salt_narrowlw_refs.mat (0, 1.5, 2.0, 2.5, 10 increments) now agree to 4e-13 of the peak. The field-swept (Experiment.Range) mode, which EasySpin’s salt does not have, uses the same rule. A skipped width that requires grad stays in the graph with zero gradient, so a fit of lw_mhz that starts at or below two increments does not move; use more points. The default lw_mhz = 0.1 with the default axis (0 to 2·mwFreq, 512 points, about 37 MHz increments at X band) is therefore a stick spectrum.

  • Not supported: a Lorentzian ENDOR width (Sys.lwEndor(2)) and Exp.Harmonic for salt. torchspin’s salt returns the absorption spectrum with one Gaussian width.

  • Range padding (0.9.6). When the spectrum is nonzero at an end of the rf range, it is extended by edge copies before the lw_mhz convolution and cropped afterwards, as in EasySpin (salt.m:858-882, Options.PaddingMultiplier; see § Pepper and salt — range padding). Before 0.9.6 torchspin’s convolution padded with zeros, so the points within about two widths of that end came out low: 1H as above on 10–19 MHz, lw 0.2 MHz, end points 0.56 and 0.55 of EasySpin’s (0.44 of the peak); 1H + 14N with Q (matrix path) on 1.5–19 MHz, 0.45 and 0.56. Both now agree with EasySpin at PaddingMultiplier 3, 1 and 0 (tests/data/range_padding_refs.mat).

ENDOR — endorfrq_perturb (0.8.8)#

endorfrq_perturb matches EasySpin’s endorfrq_perturb.m element by element: frequencies within 7.4e-16 and intensities within 4.9e-16 relative (tests/data/endorfrq_perturb_refs.mat: 1H with AFrame, 14N with Q/QFrame, 1H+14N, 55Mn with Q, strongly coupled 1H, 14N with a full Q, 1H+14N with full non-symmetric A and full Q, S = 3/2 with D; 4 orientations, PerturbOrder 1 and 2). Before 0.8.8 the intensities were wrong (lowest transition 0, ∏(2I+1) missing), the elements were in a different order and a full 3×3 Q was misread (B20, B27; see CHANGELOG).

  • Kept as in EasySpin. The second-order quadrupole term uses P2² = 2·tr(P)² + (kPk)² − 4kPPk (.m:281) with P already made traceless, so its first term is always 0 (tr(P²) was presumably meant). With nuclei=[...] the intensities still carry ∏(2I+1) over all nuclei of the system, as with EasySpin’s Opt.Nuclei. Sys.gnscale is ignored (see § ENDOR (salt)).

  • Deliberate deviation (0.9.29, B79): zero hyperfine principal values. A zero principal value or a singular full A gives the exact A -> 0 limit; EasySpin’s endorfrq_perturb.m has no check, and inv(A) (.m:176) warns and the frequencies are NaN. See § Perturbation theory — zero hyperfine principal values (0.9.29). (0.9.23 raised ValueError; before that torchspin used a zero matrix for inv(A) and returned wrong second-order frequencies.)

  • Not ported. One orientation per call (no orientation list), no Transitions or Info.Selectivity output, no Exp.ExciteWidth orientation selection (.m:310-339). The function is not differentiable: values pass through float() and a tensor that requires grad gives an output without grad. Use endorfrq (matrix diagonalization) or salt for these.

Perturbation theory — zero hyperfine principal values: deliberate deviation from EasySpin (0.9.29)#

resfields_perturb, resfields_perturb_batch, resfreqs_perturb and endorfrq_perturb accept a zero hyperfine principal value, several zeros, or a singular full Sys.A, and return the exact A -> 0 limit at every order. The second-order invariant A2 = det(A) u’·inv(A)·k needs only det(A)·inv(A) = adj(A), and torchspin computes the adjugate directly (a polynomial in A, so the result is continuous and differentiable in A there).

  • EasySpin. resfields_perturb.m and resfreqs_perturb.m (lines 120-127) raise ‘All hyperfine coupling constants must be non-zero.’ for any zero entry of a diagonal Sys.A, at every order; a singular full A is not checked. endorfrq_perturb.m has no check: inv(A) (.m:176) warns and the frequencies are NaN.

  • Accuracy. The result at A_z = 0 differs from A_z = eps by at most 4.6e-4·eps mT (fields), 1.3e-5·eps GHz (resfreqs_perturb) or 0.98·eps MHz (endorfrq_perturb), eps in MHz (1H, 14N, 63Cu, S = 1/2 and 1). It agrees with matrix diagonalization as well as perturbation theory does for a non-zero A: within 1.6·Amax³/E0² at S = 1/2. For non-singular A the results are those of det(A)·inv(A) up to roundoff (max relative change 4.8e-16 on a random sweep).

  • Where A2 matters. In the EPR modules k = A·u/|A·u|, so A2 = det(A)/|A·u| vanishes for a singular A, and it enters the fields only for S > 1/2 (factor 1 − 2mS). In endorfrq_perturb k is the direction of the field at the nucleus and A2 is non-zero for S = 1/2.

  • History. Up to 0.9.22 resfreqs_perturb and endorfrq_perturb used a zero matrix for inv(A) (wrong endorfrq_perturb frequencies, B79) and resfields_perturb raised torch’s raw LinAlgError (B65); 0.9.14 (resfields_perturb) and 0.9.23 (the other two) raised ValueError with EasySpin’s message. With an AFrame the rotated matrix is singular only to roundoff, so inv did not raise, but gradients with respect to A were wrong.

ENDOR — hyperfine enhancement (Options.Enhancement, 0.7.3)#

Options.Enhancement=True (default False, as in EasySpin) makes the rf operator of endorfrq and of salt’s matrix paths the total moment (electron + nuclear, ham()’s mux/muy/muz) perpendicular to the field, chi-averaged over lab x and y. Agreement with EasySpin endorfrq/salt (Opt.Enhancement='on') is 1e-13 of the strongest line per level pair (endorfrq) and, since 0.9.14, a residual of at most 5e-12 of the maximum for the fixed-field salt references (4.6e-3 for 14N+1H before).

  • Selection. As in EasySpin, threshold / Opt.Threshold selects on the nuclear-only rates whether Enhancement is on or off; see § ENDOR — transition selection.

  • Moment operator. torchspin uses ham()’s moments. These also contain orbital Zeeman (Sys.L) and linear higher-order Zeeman (Sys.Ham1xx) terms. EasySpin uses ham_ez + ham_nz only. The two agree for ordinary spin systems. There is no Opt.Nuclei subset: all nuclei contribute.

  • Perturbation theory. endorfrq_perturb(..., opt=Options(Enhancement=True)) raises. EasySpin skips enhancement there with a log message. salt normally picks first-order perturbation theory by itself for one electron without Q. With Enhancement=True it uses the matrix path instead, which is slower (one eigh per orientation).

  • Intensity scale. Since 0.8.1 (bug B16) the first-order path gives each line EasySpin endorfrq_perturb.m’s intensity, |⟨i|μ⊥|j⟩|² in (MHz/mT)², the scale of the matrix path. Before, its lines had unit intensity, so switching Enhancement on changed the overall scale by about 2200× for 1H. For the 1H system of endor_enhancement_refs.mat (A up to 16 MHz) the on/off area ratio is now EasySpin’s to 1.1 %; the rest is first-order theory against diagonalization (EasySpin’s 'off' uses the matrix path). Systems with Q, or more than one electron, are on the matrix path either way, and their on/off ratio matches EasySpin to 1e-3.

ENDOR — transition selection (0.9.14)#

endorfrq and every salt matrix path (fixed field, zero field, field sweep) select the level pairs with EasySpin endorfrq’s rule (endorfrq.m:258-341), in one place (torchspin.endorfrq._endor_tps_select): on the coarse grid sphgrid(Options.TPSGridSymm, Options.TPSGridSize) (defaults 'D2h', 4, EasySpin’s undocumented Opt.TPSGridSymm/TPSGridSize), the nuclear-moment rates are summed with the grid weights; pairs whose frequency is outside the rf range at every grid point are dropped; electronic pairs are removed; a pair is kept if its rate is > Threshold * max. The selection does not depend on GridSize or on the orientation, and runs without autograd (positions and intensities keep their gradients). EasySpin’s level pairs (Transitions, info.Transitions) are reproduced exactly for 1H, 14N+1H and 63Cu+14N (tests/data/endor_tps_selection_refs.mat). Before 0.9.14, salt kept a pair if it was strong at any orientation of the simulation grid, endorfrq thresholded per orientation, electronic pairs were kept without Enhancement, and the field-swept path thresholded each (orientation, field) entry against the maximum of its memory batch.

  • Electronic pairs. “Electronic” is EasySpin’s rule: levels sorted by energy, grouped into blocks of nStates / prod(2S+1), pairs across blocks removed (always, as EasySpin). This is right when the electron Zeeman (or zero-field) splitting exceeds all nuclear splittings. Near level crossings or at very low field the block assignment, and with it the line list, can be wrong, as in EasySpin; Options.Transitions='all' keeps every pair.

  • Options.Transitions (EasySpin Opt.Transitions, passed by salt to endorfrq): 'all' or 1-based level pairs replace the selection, with no threshold. In salt it forces the matrix path; with Options.ZeroField it raises NotImplementedError.

  • endorfrq range. freq_range acts on the selection only, as EasySpin’s Exp.Range: the selected pairs are returned at the requested orientation even if their frequency there is outside the range. Rows are ordered by frequency (EasySpin: by selection rate).

  • Zero field (Options.ZeroField, torchspin only): the rule acts on pairs of degenerate level clusters, without the electronic-pair removal (at B = 0 the levels are not grouped by electron spin projection).

  • Field sweeps (torchspin only; EasySpin’s salt has no field-swept mode): the pairs are selected at 5 fields spanning the resonance fields of the sweep and a pair is kept if it is selected at any of them. With Threshold = 0.01 and 0-40 MHz, 2.57 % of the integral is dropped, close to the fixed-field 2.56 % (EasySpin’s rule); before 0.9.14, 0.60 %, depending on the batch size.

  • Not explained: for 63Cu (A = [60 60 600], Q = [-5 -5 10] MHz) at 320 mT on a 0-19400 MHz axis (4001 points, lwEndor 30 MHz) salt differs from EasySpin by up to 1e-2 of the maximum below ~600 MHz with identical level pairs (also before 0.9.14); the 14N+1H references agree to 1e-12.

Garlic — what is and is not ported#

Line positions use EasySpin’s algorithm exactly (per-nuclear-group Breit–Rabi fixed-point solver by default, or Options.Method='perturbN'), including sets of equivalent nuclei (SpinSystem.n), frequency sweeps (Field + mwRange), CenterSweep, field modulation (ModAmp), Boltzmann polarization, full g/A matrices, automatic sweep ranging (one component; with several components, including natural-abundance isotope mixtures, Experiment.Range or CenterSweep is required, as in EasySpin), natural-abundance isotope mixtures and multi-component input (compisoloop), and Options.separate. (Before the 0.9.38 docs this paragraph listed the last four as not ported; they had been ported earlier.) Equivalent nuclei are not allowed in the fast-motion regime (same as EasySpin). When no broadening is given, a requested derivative harmonic falls back to the absorption stick spectrum (EasySpin’s auto-harmonic). In the fast-motion regime the Kivelson–Freed widths use gFrame, AFrame and full g/A/Q matrices, and Diff/logDiff (isotropic) select the regime with tcorr = 1/(6 Diff); before 0.9.39 the frames and Diff were ignored and a full Q matrix crashed (B105–B107).

Pulse EPR — saffron, spidyan and saffron_thyme are MATLAB-validated#

saffron() is cross-validated on 25 MATLAB reference cases: predefined 2p/3p/4p ESEEM, HYSCORE and MimsENDOR, S>1/2 systems, custom sequences, ProductRule (with and without TimeDomain), single crystals (CrystalSymmetry/MolFrame, all 230 space groups via sitetransforms) and two-component input. Cosine ≥0.98 throughout (crystal HYSCORE 0.989, two components >0.98, everything else ≥0.999). HYSCORE remains much slower than EasySpin.

A cosine similarity is a weak oracle for pulse EPR, and these 25 cases should not be read as tight agreement. A predefined ESEEM/HYSCORE trace is dominated by its DC offset, so the modulation — the entire physical content of the experiment — can be ~100% wrong at cosine >0.999. Six defects were found in exactly that blind spot after 0.4.0 (tau phase conjugation, S=1/2 manifold assignment, 2D bin dimension order, OriThreshold reference level, and the Expand/EndorMethod conditional defaults); see the CHANGELOG. Agreement on the routes covered by torchspin/tests/test_saffron_phase_matlab_validation.py is now 1e-16 to 1e-14 on both the raw and the mean-centered signal. New pulse-EPR comparisons should assert the mean-centered relative error, not a cosine. Custom user sequences, ProductRule x TimeDomain, multi-component input and S=1 systems have since been re-checked at roundoff as well.

Two things remain open in the pulse-EPR routes:

  • ~~spidyan multi-spin phase drift.~~ Resolved, and it was never a library defect. The residual reported in 0.5.0 was a test transcription error: generate_spidyan_refs.m sets Sys.g = gfree and the Python tests had rounded it to 2.00232. That 3.5e-7 error in g shifts the precession frequency by 11.6 kHz, which accumulates as phase over the 0.5 µs delay. torchspin reproduces the analytic Larmor frequency exactly. Every spidyan case now agrees to 1e-14..1e-12.

  • ~~Real pulses do not reproduce EasySpin, and have a different output contract.~~ Resolved. The route is now EasySpin-equivalent and validated on 18 MATLAB cases at 3e-13..3e-12 on both the raw and the mean-centered signal. The 0.5.0 diagnosis was right that no reduction of the old per-increment transients could recover EasySpin’s trace, and the reason was that both the detection stage and the propagation were wrong: Exp.mwFreq never reached the sequencer (so the pulses were DC fields in the lab frame and nothing was excited), the Hamiltonian was built in the molecular frame while the state and operators stayed lab-frame, the orientation sum was divided by the total grid weight where EasySpin leaves the 4*pi in, and the detection phase, Exp.DetIntegrate, down-conversion and Exp.DetWindow axis were all absent. See the CHANGELOG for the full list.

  • ~~Predefined sequence + real pulses is an unvalidated extension.~~ Resolved, and it was the fast path that was wrong. EasySpin rejects a predefined sequence with nonzero Exp.tp in fast mode only; in thyme mode s_predefinedexperiments.m builds the sequence from rectangular pulses, and 2pESEEM, 3pESEEM and HYSCORE through the real-pulse engine are now MATLAB cases. torchspin previously ignored Exp.tp for a predefined sequence and returned an ideal-pulse result; it now raises EasySpin’s error in fast mode and runs the real-pulse engine when Opt.SimulationMode='thyme'. 4pESEEM and MimsENDOR have no thyme template in EasySpin either, and raise.

  • ~~Shaped pulses are still not implemented.~~ Resolved, and nothing had to be implemented. torchspin/pulse.py already built shaped pulses for spidyan, and a pulse dict in a list-valued Exp.Sequence passes through to it unchanged; what had kept EasySpin’s own saffron_thyme_* cases from running was the propagation and detection. All ten of them now agree at 3e-13..8e-12 (tests/data/generate_saffron_thyme_shaped_refs.m), covering quartersin/linear chirps with trise and a swept Frequency, relaxation during a chirp, an explicit Opt.SimFreq, a pulse-parameter sweep along an indirect dimension, Sys.gFrame/Sys.AFrame tilts, and a predefined sequence detected over a transient window. Shaped pulses are expressed through the list-valued Exp.Sequence (EasySpin’s own syntax); saffron’s Exp.Flip/Exp.tp array shorthand builds rectangular pulses only, as it does in EasySpin.

  • The ideal-pulse and real-pulse routes do not converge as Exp.tp -> 0, and are not meant to be compared. This was expected to work as a reference-free check on the normalization; it does not, and that is EasySpin’s behavior, not torchspin’s — at matched settings torchspin reproduces EasySpin’s own ideal-vs-real mismatch to 1e-7 in scale. Three reasons: with single-point detection EasySpin does not down-convert, so the detected point carries the simulation-frame carrier phase (~50 cycles per 20 ns increment); a single detected point contains coherence pathways the ideal route excludes analytically, which the two-step cycles in EasySpin’s own templates do not remove for this observable; and as tp -> 0 at fixed flip angle the required B1 eventually exceeds the carrier frequency, so the rotating-wave picture breaks down. Moving the simulation frame onto the carrier to remove the first effect is not neutral — it removes the carrier from the pulse too, doubling the effective field. Use the two routes for what each is for, and compare either against EasySpin rather than against each other.

  • Two EasySpin behaviors the real-pulse route cannot reach. saffron.m line 1937 reads Exp.DetWindow(1) unconditionally once detection is not single-point, so a transient Exp.DetSequence errors in EasySpin itself (Unrecognized field name "DetWindow"); torchspin accepts it, and that combination is therefore not cross-validated. Exp.DetOperator is ignored by EasySpin’s saffron (only spidyan transfers it); torchspin warns rather than ignoring it silently, and always detects S+.

The pulse-EPR suites no longer score agreement with a cosine. saffron, spidyan and the spidyan tp sweep all assert the relative L2 error against their MATLAB references, and agreement is 1e-16..1e-7 throughout.

Getting there meant fixing three kinds of harness fault that the cosine had hidden, none of them a library fault: twelve tests ran TimeDomain=True against references generated without Opt.TimeDomain (direct evolution vs EasySpin’s own binned approximation, a real 7–60% difference in the modulation); six compared unnormalized output against references their generator had normalized with y = y/max(abs(y)); and three used a GridSize that did not match their generator (181 vs 91, and EasySpin’s default 31 vs 20). GridSize is now explicit in every case so the two codes’ defaults cannot drift apart unnoticed.

One committed fixture is known to be stale rather than wrong-in-code: regenerating saffron_orientation_selective.mat from the local EasySpin gives a reference torchspin matches to 4.4e-15, while the stored one differs by 1.4e-6 in overall scale. That test checks its amplitude at 1e-5 and its peak-normalized shape strictly, and says so, rather than loosening everything.

The former saffron_2psimple xfail (14N + quadrupole) is resolved: the test had used a quadrupole coupling ten times smaller than EasySpin’s own test, and SpinSystem.Q now converts EasySpin’s [e2qQ/h eta] shorthand (cosine 0.99995).

spidyan() is cross-validated on 7 MATLAB cases (cosine > 0.99) after the simulation-frame port (ZeemanFreq→g translation, SimFreq, pulse carriers via pulse()/rfmixer, phase cycling, DetFreq down-conversion, Dim sweeps of pulse parameters including the pulse length tp; 8 MATLAB cases).

saffron_thyme() (real-pulse engine) is cross-validated on 28 MATLAB cases — 18 rectangular (test_saffron_thyme_matlab_validation.py) and EasySpin’s own 10 saffron_thyme_* cases with shaped pulses (test_saffron_thyme_shaped_matlab_validation.py) — in addition to its internal-consistency tests. Every case states Opt.SimulationMode, Opt.GridSize, Opt.IntTimeStep, Exp.DetWindow, Exp.DetPhase and (where used) Opt.SimFreq and Exp.DetIntegrate explicitly in both codes, and test_thyme_references_present / test_shaped_references_present fail rather than skip if a reference file is missing, so a skipped comparison cannot look like a passing one.

Three relations hold without any reference and guard the normalization: a single-site P1 crystal equals 4*pi times the independently validated spidyan result (1e-12), an isotropic powder equals a single crystal, and a nominal Pulse.Flip of pi/2 delivers full transverse magnetization while pi delivers none.

One caveat on reading those numbers: the references pin Opt.IntTimeStep = 1e-4 µs, which is coarse enough that EasySpin warns about it (its own default for this sequence is 4.3e-6 µs). What is validated is that the two codes do the same calculation, not that 1e-4 µs is converged; eseem2p_fine repeats one case at 2e-5 µs and agrees equally well.

Relaxation with complex (S+) detection was wrong until this round, in spidyan as well. The Liouville-space commutator superoperator used EasySpin’s column-major kron() ordering against numpy’s row-major flattening, so the relaxation path propagated conj(rho). An Sz trace is real and so unaffected, which is why the existing spidyan relaxation reference — Exp.DetOperator = {'z1'}, compared on its real part only — could not see it. There is now a reference that detects S+ under relaxation and is checked on its imaginary part too.

A sample tilt and the equivalent tensor tilt agree to ~1e-12, not to machine precision. Sys.gFrame/Sys.AFrame and an equal Exp.SampleFrame describe the same physics, and EasySpin’s own test asserts the two signals agree to 1e-12 absolute. torchspin reaches them by different arithmetic: EasySpin rotates the interaction tensors, while torchspin conjugates the molecular-frame Hamiltonian into the lab-frame basis, which is the identity for an untilted sample and two matrix exponentials for a tilted one. The two Hamiltonians agree to 2e-16 relative, but integrating that over a detection window turns it into a phase error growing linearly in time — 2e-11 absolute on a signal of magnitude 12 after 0.3 µs. Both sides are separately validated against MATLAB at ~1e-12 relative L2, so this is a round-off floor and not a frame-handling error; it is worth knowing only if you compare the two setups to each other over a long transient.


Cardamom — validated against EasySpin (2026-09-02)#

tests/generate_cardamom_matlab_refs.m (EasySpin 6 parameter names) was run with rng(42); test_cardamom_matlab_validation.py compares three cases (nitroxide diffusion/fast, two-site jump/fast, diffusion/ISTOs) and reaches cosine 0.9998, ≥0.97 and 0.9992 with amplitude ratio 1.00 — the residual differences are the random-number streams, which cannot be matched across MATLAB and NumPy.

Three EasySpin conventions were adopted to get there: field-swept cardamom spectra are the imaginary FFT of the time-weighted FID and ignore Exp.Harmonic; the spectrum scale is 1/nOrients of the weighted orientation sum (EasySpin weights and then averages again); the jump model takes its dynamics from Sys.TransRates/Sys.Orientations and needs no correlation time.

Remaining caveats audited in v0.1.0:

  • The SzFilter secular projection used in MATLAB cardamom ISTOs is not yet applied in torchspin; for hyperfine systems this can cause subtle pseudo-secular differences.

  • The stochtraj_diffusion Wigner-potential torque is computed via Euler- angle finite differences, which is exact only for axial L=2,M=0,K=0 potentials. Generic potentials produce a known approximation.


Pepper — round 3 (2026-09-02)#

Added and MATLAB-validated (test_pepper_round3_matlab_validation.py, 32 cases): Experiment.mwMode (tilted linear, unpolarised and circular excitation for powders and crystals on the matrix, frequency-sweep and perturbation paths), photoselection with perturbation theory, Options.separate='transitions', automatic field and frequency sweep ranges, ordering in frequency sweeps.

Two EasySpin-side approximations surfaced and are documented rather than copied: (1) EasySpin’s matrix path interpolates eigenvectors across the field segment; for 63Cu+14N its intensities are 3–4 % off the exact value and its spectrum disagrees with its own perturb2 (cosine 0.951), while torchspin’s exact intensities agree with EasySpin perturb2 at 0.988 (septrans_CuN_matrix xfail). (2) For S=5/2 in parallel mode torchspin and EasySpin agree exactly on the coarse grid. With the default [19 4] interpolation they differed (cosine 0.9959) because torchspin splined the positions of transitions that resonate everywhere while EasySpin interpolates all of them linearly once any transition misses a knot; matched in 0.9.4 (cosine 0.99989, threshold 0.9998). Since 0.9.28 the range-cut transitions are searched again and only the slots that never resonate at some orientations go linear (B88): cosine 0.99582 with EasySpin (strict xfail), but 1 − cosine 7.0e-4 against a converged reference, where 0.9.27 and EasySpin were 5.1e-3 (see § Field sweeps whose range cuts transitions).

Internals aligned with EasySpin in the process: global transition pre-/post- selection (Opt.Threshold) instead of per-orientation thresholds, a Hermite-cubic tangent test that finds paired resonances of looping transitions, linear (L1) / local-cubic (L3) interpolation of intensities and widths, and hamsymm equality at 1e-12 relative so finite-difference steps break symmetry.


Pepper — features validated in round 2 (2026-09-01)#

All of the following are MATLAB-validated (test_pepper_crystal_*, test_pepper_parallel_*, test_pepper_features_*, test_pepper_features2_*): single crystals (SampleFrame/CrystalSymmetry/MolFrame/SampleRotation, Options.Sites, separate='orientations'|'sites'), parallel-mode detection, natural-abundance and custom isotopologues ('Cu', '(63,65)Cu' + Abund, Options.IsoCutoff), non-equilibrium populations (SpinSystem.initState in the zero-field/eigen/xyz/coupled/uncoupled bases, density matrices, 'T0', 'singlet'), partial ordering (Experiment.Ordering, λ or callable), photoselection (lightBeam, lightScatter, tdm), field modulation (ModAmp), dispersion (mwPhase), separate='components', and frequency sweeps with strain/interpolation/projection through the same code path as field sweeps. Not ported: separate='transitions', unpolarised/circular excitation, ordering in frequency sweeps, photoselection with perturbation theory, automatic sweep ranging in pepper (garlic auto-ranges).


eprload — EasySpin oracle and native units (behavior change, 2026-09-01)#

eprload is validated against EasySpin’s output for every readable file in tests/eprfiles (75 files). To achieve parity the Bruker readers now return the abscissa in the file’s native units (Gauss for BES3T/ESP, MHz for ENDOR, seconds for time sweeps) instead of converting to mT, multi-dimensional data are returned as arrays with one abscissa per dimension (a list), several data values per point (IKKF 'CPLX,CPLX') give a list of datasets, and JEOL / specman axes follow EasySpin’s conventions. Callers that relied on mT must divide by 10. The eprload docstring now states the units per format and shows that conversion in a worked example, and eprload_info prints the unit and flags a gauss axis, so this no longer has to be found here first.


esfit — uncertainties of parameters on a bound (0.9.40)#

The error estimate (pstd, ci95, cov, corr) comes from the curvature of the objective at the optimum. A parameter that ends on a bound is not at a minimum in that direction, so the estimate does not apply to it: since 0.9.40 esfit reports pstd = nan for it with a warning, holds it fixed in the covariance of the others, and takes the Jacobian with one-sided differences that stay inside the bounds. Up to 0.9.39 the central differences probed ~1e-7 beyond the bound, which crashed models that reject the value there (a negative line width) and gave a meaningless error bar. A parameter on its bound is unresolved by the data under that constraint: widen the bound if it is not a physical limit, or report the bound.

Stochastic trajectories — reproducibility#

DiffusionPar and JumpPar now expose a seed: Optional[int] field that threads through all RNG calls. Setting seed=42 produces bit-reproducible trajectories across runs. Without a seed, output is non-deterministic.

This was added in v0.1.0 to support reproducible benchmarks; users porting from earlier development snapshots should pass seed= explicitly.


Single-orientation resfields and compute_strain_widths (0.9.20)#

  • Same solver as pepper. resfields (one orientation) and strainwidth.compute_strain_widths are thin wrappers over resfields_batch and compute_strain_widths_batch with one orientation. Before 0.9.20 they had their own code (Python-float Brent search, .item()), which gave no gradient or, for S = 1 with DStrain + HStrain, a wrong one (B76), found at most one resonance per level pair, and gave an infinite width for full g + gStrain (B5).

  • Differentiable with respect to the Hamiltonian (g, A, D, J, Sys.Ham), the strains (HStrain, gStrain, AStrain), the angles and, for compute_strain_widths, B0. DStrain magnitudes are constants, as in pepper. Gradients match central differences to 1e-6 relative above the finite-difference round-off (test_resfields_single_autograd.py). Gradients with respect to frame angles (gFrame, AFrame, DFrame) are not covered here.

  • Behavior as resfields_batch: a looping transition returns all its resonances; Exp.mwMode is honored; Options.Threshold is relative to the largest |I|; gStrain/AStrain with a full g matrix raise ValueError (as EasySpin); with strains but no resonance in range the widths are an empty tensor (None only without sys or without strains). Fields agree with the old Brent search to its 1e-5 mT tolerance (≤ 2e-6 mT on the test systems).

  • Options.QuadraticZeeman with lB ≥ 2 terms still raises in resfields (single orientation); use resfields_batch(..., zeeman_ho=...).

AStrain — EasySpin’s effective-mI model, followed deliberately (0.9.25)#

  • Convention. The AStrain width of a transition (u, v) is dBdE * |(G + gAStrainCorr * mI_uv * AStrainMatrix) zL| with mI_uv = (mI_u + mI_v)/2, as in EasySpin resfields.m 766-788 and 1297-1306 except that EasySpin squares the matrix element-wise (zL' (...).^2 zL; the same for untilted frames, see § Field sweeps — gStrain/AStrain widths with tilted frames). Each level’s mI (<Iz> of the first nucleus) is computed once per call, from the eigenvectors of H0 - centerB*muz with the field along the molecular z axis and centerB = mean(Exp.Range), and is attached to the level index (levels sorted by energy). The same mI is used at every orientation (strainwidth.astrain_level_mI). Before 0.9.25 torchspin used <Iz> at each orientation’s own resonance field, which gave perpendicular lines no AStrain width (B68; EasySpin and an explicit A ensemble agree with the model above).

  • Limitation (EasySpin’s too). Because mI goes with the level index, an orientation at which the energy order of the levels differs from their order at centerB along molecular z (level crossings with orientation or field: strong nuclear Zeeman or quadrupole terms, several nuclei with comparable couplings, zero-field splitting comparable to the hyperfine levels) assigns a transition the mI of a different state. The labels also depend on Exp.Range through centerB. In the regime AStrain is meant for (one dominant hyperfine coupling, hyperfine levels ordered by mI) the order does not change and the model matches an explicit ensemble.

  • Scope. First nucleus only, one electron spin (more than one electron spin raises ValueError in field and frequency sweeps since 0.9.31, as EasySpin; before, field sweeps without gStrain dropped AStrain silently, B89); the same mI for every orientation in pepper, pepper_autograd, Opt.Method='hybrid' (core system) and resfields/ resfields_batch. compute_strain_widths_batch requires mI_levels with AStrain; compute_strain_widths (single orientation) takes Range or mI_levels, and without either labels the levels at its B0. Frequency sweeps do not use mI, like EasySpin’s resfreqs_matrix.m: they evaluate the operator derivatives dnu/dA_k per orientation, along the AFrame axes (§ Frequency sweeps — AStrain along the AFrame axes).

  • Not rotation covariant. The labels are taken along the molecular z axis, so with anisotropic A (or anisotropic g with a tilted g frame) the same physical system described in a tilted frame gets other mI labels and other widths (B96, open; EasySpin behaves the same). With isotropic g and A the widths are covariant (0.9.33).

  • Validated: per-orientation widths against EasySpin resfields to 1e-5 relative (incl. θ = 90°; with a tilted AFrame up to 0.9.32 only, see § Field sweeps — gStrain/AStrain widths with tilted frames) and pepper/pepper_autograd spectra to cosine ≥ 0.999996 (test_astrain_mi_model.py). A 63Cu system with a tilted AFrame has a separate, strain-independent spectrum difference from EasySpin (strict xfail there).

Field sweeps — gStrain/AStrain widths with tilted frames: deliberate deviation from EasySpin (0.9.33)#

The g-strain model is a Gaussian distribution of the principal g values in the g frame. For a field direction z (molecular frame) its width² is Σ_i (R z)_i² (gStrain_i/g_i · mwFreq)² (R = erot(gFrame)), which is z' G G z = |G z|² with G = R' diag(gStrain/g · mwFreq) R. torchspin evaluates exactly that, and |(G + gAStrainCorr·mI·A) z|² with AStrain (A = R_A' diag(AStrain) R_A), for one and several electron spins (strainwidth.py), and hamsymm uses the matching quadratic forms (G·G, A·A, G·A + A·G).

  • EasySpin (resfields.m 787/792/1309, resfields_perturb.m 523/532, resfreqs_perturb.m 504) squares the rotated matrix element-wise, z' (G.^2) z. That equals the model only when G is diagonal (frame 0, or axes swapped); with a tilted frame the widths depend on how the same physical system is described. S = 1/2, g = [2.0 2.0 2.2] (rhombic: [2.0 2.1 2.3]), gStrain = [0.01 0.01 0.05] ([0.01 0.03 0.06]), 9.5 GHz: gFrame = [0.4 0.9 -0.3] against the untilted system at the rotated field direction, per-orientation widths up to ~100 % apart, powder spectra 9-27 % of the peak. torchspin before 0.9.33 did the same (B84).

  • Now: the tilted and the untilted description agree to 1e-14 (widths) and 3e-14 (pepper powder spectra, with the strain symmetry now Dinfh/D2h in the g frame instead of Ci); gFrame = 0 and diagonal strain matrices are unchanged bit for bit. The torchspin field-sweep paths with strain all use the matrix path; the perturbation-theory paths compute no strain widths. Frequency sweeps use the linear form z' G z and were already covariant.

  • Consequence: EasySpin reference cases with a tilted g or A frame and g/A strain are strict xfails: test_strain_validation.py tilted_frame (RMS 0.0996, peak ratio 1.25; before 0.0874, 0.944), test_strain_widths_matlab_validation.py two_spinhalf_gstrain_both (widths up to 17 % apart; before 3.4e-4) and the two Cu63_AFrame width tests in test_astrain_mi_model.py (up to 45 %; before 9.2e-6). Each has an objective replacement: the tilted system against the untilted one (or EasySpin’s untilted reference), a global rotation of a two-electron system, and the width model written out (test_gstrain_covariance.py and the files above).

  • AStrain with anisotropic A is still not fully covariant because of the mI labels (§ AStrain, B96).

Frequency sweeps — AStrain along the AFrame axes: deliberate deviation from EasySpin (0.9.31)#

In a frequency sweep the AStrain width of a transition (u, v) is sqrt(Σ_k (AStrain_k · m((R'S)_k (R'I)_k))²), m(op) = <v|op|v> − <u|op|u>, R = R_A2M = erot(AFrame)’ (first electron, first nucleus): AStrain_k times dnu/dA_k, the derivative of the transition frequency with respect to the hyperfine principal value A_k (Hellmann-Feynman). The term is differentiable in AStrain and AFrame (compute_strain_widths_freq_batch).

  • EasySpin. resfreqs_matrix.m (567-583) builds I_k = Σ_c R(c,k) I_c but S_k = Σ_c R(k,c) S_c (the transpose). This is dnu/dA_k only when R is symmetric up to signs (AFrame = 0, a swap of two axes); a cyclic axis permutation or a general tilt gives other widths. EasySpin (GitHub main, MATLAB R2024b) for S = 1/2, g = 2, 63Cu A = [30 60 200] MHz, AFrame = [0.4 0.9 -0.3], AStrain = [10 20 40] MHz, 340 mT, field along [0.6816 0.5741 0.4536] (φ = 0.7, θ = 1.1; Exp.SampleFrame = [0 -1.1 -0.7]): 21.44, 21.86, 7.20 and 7.24 MHz for the two outermost and the two next allowed lines; eigenvalue derivatives and torchspin: 56.85, 56.48, 18.92 and 18.87 MHz. With AFrame = [π/2 π/2 0] (cyclic) EasySpin’s formula is off by up to 7.3 MHz on the same system.

  • History. Before 0.9.31 torchspin used the molecular axes (AStrain_c I_c S_c), i.e. ignored AFrame (19.0, 18.5, 6.5 and 6.0 MHz for the lines above), and float(AStrain) cut the gradient (B90). AFrame = 0 gives the same values as before.

  • Validated (test_freq_astrain_frame.py): widths of all transitions against eigenvalue central differences to 8e-8 MHz at a generic tilt; a pepper frequency sweep with AFrame = [0 π/2 0] against the untilted system with A and AStrain permuted to 1.4e-13 relative; AStrain and AFrame gradients against converged central differences.

  • gStrain or AStrain with more than one electron spin raises ValueError, as in EasySpin (resfreqs_matrix.m 102-106; before 0.9.31 the first electron’s strains were used, B89).

Autograd — differentiable pepper#

Since 2026-09-05 differentiable_spectrum() builds a SpinSystem from the parameter tensors and evaluates it with pepper_autograd(), which is pepper’s own forward path (resonance-field search with transition tracking, EasySpin grid interpolation, SOPHE triangle/zone projection, EasySpin convolution and harmonic) written on the autograd graph. Forward output equals pepper() to 1e-11 relative for every grid symmetry, GridSize (int or [N, Ninterp]) and harmonic; gradients through the resonance-field search come from the converged Newton step (implicit-function theorem), no custom backward.

Gradient validation against central finite differences of pepper() (test_pepper_autograd.py): A, D, Gaussian and Lorentzian lw and Temperature agree to ~1e-8 relative norm error; g gradients agree to the finite-difference limit set by the piecewise-linear projection (a vertex crossing a field bin is a kink): relative norm error 6e-2 / 8e-3 / 1.5e-4 / 2e-8 for steps 1e-4 / 1e-5 / 1e-6 / 1e-7 in g, identically for pepper and pepper_autograd. Optimizers see an almost-everywhere exact gradient of a piecewise-smooth model.

Isotropic systems (grid symmetry O3, automatic or GridSymmetry='O3') have one orientation and no facets: pepper_autograd draws every line with an exact template at its position, as pepper does (Gaussian for Sys.lw(1) or a strain width, Lorentzian for Sys.lw(2) alone, the rest convolved), so line positions, intensities and widths are differentiable in g, A, lw, HStrain and Temperature. Before 0.9.18 it sent the single orientation to the triangle projection, whose O3 triangulation is empty, and returned an all-zero spectrum with zero gradient, also through pepper() with an isotropic parameter that requires grad (B66). A powder grid that yields no usable facets now raises RuntimeError instead of returning zeros; no grid that Options accepts (GridSize ≥ 2) does so. Sets of equivalent nuclei (Sys.n > 1) still raise NotImplementedError on every grid, O3 included.

The earlier stand-alone models remain as method='broadband' and method='analytical' (deprecated). They sum discrete orientations without interpolation or projection and carry orientation-grid ripple at GridSizes where pepper is converged: for a Cu(II) hyperfine system at GridSize 31 the cosine to EasySpin is 0.985–0.999 (absorption) and 0.73–0.88 (first derivative), against 0.9998–1.0000 / 0.999 for pepper; the ripple only falls below 1 % of the signal around GridSize 91. Do not train models on their output.

Strains are differentiable (HStrain, gStrain, AStrain; DStrain magnitudes are constants). Euler frame angles of the spin system (gFrame, AFrame, DFrame, QFrame, eeFrame, nnFrame, sigmaFrame, BFrame) are differentiable since 0.9.17 (before, they were detached silently). The automatic grid follows the differentiated parameterization (0.9.26, § Automatic grid symmetry — differentiated parameters): with differentiated frame angles the symmetry frame moves with them, so the grid is Ci, and the spectrum can differ from the forward-only one (detached values, possibly a higher group) by the grid discretization error; fix GridSymmetry to compare the two. The crystal frames Exp.SampleFrame and Exp.MolFrame are not differentiable (crystals raise, below). Exp.ModAmp (pseudo-modulation) is differentiable on every torch version (0.9.27, B92): torch.special.bessel_j0/bessel_j1 have no derivative before torch 2.15, so dataproc._bessel_j01 supplies the backward (J0’ = -J1, J1’ = J0 - J1/x). Before 0.9.27 a grad ModAmp raised at Harmonic 1 and gave a silently wrong gradient at Harmonic 2 on torch <= 2.14 (the Bessel recurrence kept only its 2k/x path). A grad ModAmp <= 0 raises: ModAmp = 0 switches to the plain field-derivative harmonic, so the spectrum is not continuous there. The kernel’s accuracy is bounded by torch’s own bessel_j0/bessel_j1 forward values, about 4e-7 absolute for x in 5-10 (torch 2.10 and 2.15; scipy jv reference), so fieldmod_t and the gradients through it agree with the scipy-based dataproc.fieldmod to that level, not to roundoff. dataproc.fieldmod_t with harmonic >= 3 (not reachable through pepper, which caps Harmonic at 2) uses the J_n power series for |x| < n and the upward recurrence only for |x| >= n (0.9.37, B93; before, the recurrence was used down to |x| = 1e-3, where it is unstable: J_4(1e-3) was 7.9e-9 instead of 2.6e-15 and Harmonic >= 4 gradients did not match central differences); harmonic > 30 raises (the series cancels near |x| = n). Not yet differentiable (pepper_autograd raises NotImplementedError, pepper() itself is unchanged): Exp.mwPhase, partial ordering, photoselection, crystals, frequency sweeps, Sys.initState. salt (fixed-field mode) and garlic (all modes) are differentiable through the same approach (test_salt_autograd.py, test_garlic_autograd.py); garlic switches its nearest-bin stick spectrum to the two-bin linear split for grad tensors (sub-bin quantisation difference). saffron is differentiable for ESEEM/HYSCORE with grad tensors (returns tensors and uses TimeDomain=True accumulation; Mims-ENDOR raises). chili has no differentiable path yet (needs a torch SLE solve); curry is pure torch and differentiable.

Platform and dependency support#

pyproject.toml declares Python >= 3.10, torch>=2.0,<3, numpy>=1.23,<3, scipy>=1.10. Two combinations are exercised directly:

development host

clean-room host

OS

Ubuntu 22.04 (x86-64)

Ubuntu 22.04 (x86-64)

Python

3.12

3.12

NumPy / SciPy

2.4 / 1.17

2.5 / 1.18

PyTorch

2.5 (CUDA 12.1)

2.14 (CUDA 13.0)

GPU

2× RTX 4090

2× RTX 3090

CI additionally runs the suite on Linux, macOS and Windows across Python 3.10-3.13 on every push, which is the full range the package claims support for (requires-python = ">=3.10").

The clean-room host installs the package into an empty environment from the declared dependencies alone and runs the full suite; it is what the release is gated on. NumPy 1.x is still supported (the np.trapezoid / np.trapz fallbacks) but is not routinely exercised.

Platform-specific breakage is real and worth testing for rather than assuming away: the first CI run the project ever completed found that eprload could not pair Bruker .SPC/.PAR files on a case-sensitive filesystem, which no amount of testing on macOS would have surfaced.

CUDA is used opportunistically. Batched eigendecompositions of matrices larger than 32×32 are routed to the CPU thread pool (the cuSOLVER syevjBatched limit), and pepper’s grid interpolation, triangle projection and strain accumulation are host-side regardless of device; see the device audit in benchmarks/results/workstation_20260904_verified/BENCHMARK_VERIFICATION.md. chili and cardamom have no CUDA path at all.

Expensive tests are opt-in#

Two cases in test_pepper_cupc_matlab_validation.py are exact diagonalizations of a 72-dimensional Hilbert space over a converged grid, and one of them takes about ten minutes (EasySpin needs 630 s for the same case). CI’s full-suite job has no marker filter, so they are skipped unless TORCHSPIN_RUN_EXPENSIVE=1 is set rather than merely marked slow. They are kept because cupc_matrix_aframe is the largest exact comparison run to completion in both codes — torchspin 590 s against EasySpin’s 630 s — which is the evidence that torchspin’s matrix path is not the slower of the two.


Test counts (v0.3.0, 2026-10-04, clean-room host)#

Outcome

Count

Passed

2659

Failed

0

Skipped

4

xfailed (documented known issues)

3

The documented xfails are:

  1. test_pepper_round3_matlab_validation.py::[septrans_CuN_matrix] — EasySpin’s matrix-path eigenvector interpolation (see § Pepper — round 3)

  2. test_potential_biases_distribution — stochastic Wigner-potential biasing requires longer equilibration than the test budget

  3. test_cardamom.py::test_fast_motion — stochastic fast-motion narrowing needs more trajectories than the test budget

The 4 skips are environment-dependent, not unimplemented behavior:

  • test_fitgui.py used to skip because ipywidgets shipped only in the gui extra; it is now in test and dev as well, so those tests run. A missing GUI dependency also no longer surfaces as a bare ModuleNotFoundError — the panel raises an ImportError naming the module and the extra that provides it.

  • 1 in test_gpu_consistency.py — it exercises the CPU fallback taken when CUDA is missing, so it skips on a machine that has a GPU.

Counts come from the clean-room host described above, with pip install -e ".[test]" and both GPUs visible. On a CPU-only machine the CUDA-variant tests skip instead of running, so the skip count rises and the pass count falls correspondingly; no test fails.


How this document is maintained#

This file is updated as caveats are addressed or new ones are discovered. Each release notes which limitations changed in CHANGELOG.md.

This document is the distilled public record of an internal audit (~50 pages of findings and synthesis notes) carried out during the port. The raw audit notes are not distributed; everything they established that bears on using torchspin is stated here, and the evidence is the test suite plus the stored EasySpin references in tests/data/.