Changelog#

All notable changes to torchspin will be documented in this file. Format follows Keep a Changelog. This project adheres to Semantic Versioning.

[Unreleased]#

[0.9.40] — 2026-11-27#

Fixed#

  • pepper: strain broadening dropped every emissive line with non-equilibrium populations. With Sys.initState and any HStrain, gStrain, AStrain or DStrain, the strain summation kept only facets of positive intensity, so the polarized (emissive) half of a trEPR/triplet spectrum vanished silently and the absorptive half remained. A photoexcited triplet (S = 1, D = [1500 300] MHz, initState = ([0.1 0.3 0.6], 'xyz'), 9.7 GHz) had minimum -6.02 and integral 281 without strain and minimum ~0, integral 1790 with HStrain = 1e-6 MHz. Signed intensities are now kept, as in EasySpin; the stick binning on non-projectable grids had the same filter and is fixed too. The tiny-strain spectrum now equals the strain-free one (0.6 % of the maximum: summation and projection are different discretizations), populations mirrored about 1/3 negate the spectrum to 1e-9, and four new EasySpin references (HStrain in the xyz basis at harmonics 0 and 1, DStrain in the zero-field basis, gStrain with a tilted D frame) match at cosine >= 0.9996 and amplitude within 0.02 %. Thermal populations are unaffected (their intensities are never negative), so outputs without initState are bit-identical.

  • esfit: the uncertainty step evaluated the model outside the bounds. The central-difference Jacobian behind pstd, ci95, cov and corr probed ~1e-7 beyond a bound when a parameter ended on it, which crashed models that reject the value there (a negative line width) and gave a meaningless error bar. The Jacobian now uses the second-order one-sided difference into the interior where a probe would leave the bounds, and never evaluates the model outside them. A parameter that ends within one step of a bound gets pstd = nan and a warning (the curvature-based error bar does not apply at a constrained optimum), and is held fixed in the covariance of the others. Fits that end inside their bounds are unchanged.

Changed#

  • esfit: the warning for residuals that depend on no parameter names the likely cause. When every Jacobian column is zero, the warning now points to a flat model, usually the lsq scale clipped to 0 after a start more than a line width from the data, instead of garlic’s AccumMethod='binning' alone. A single dead parameter keeps the binning hint.

[0.9.39] — 2026-11-24#

Changed#

  • Resonance eigenvectors interpolated between field knots (B133; Options.RediagLimit, default 0.999; pepper matrix route, spin systems of dimension >= 16, forward runs). At a resonance whose two transition levels overlap with themselves across the knot segment by at least RediagLimit and are non-degenerate at both knots, the eigenvectors are interpolated (cubic Hermite, derivatives at the knots by perturbation theory) and the field is refined by a Rayleigh-quotient Newton step instead of diagonalizing the Hamiltonian there. Spectra change by <= 6.3e-7 of their maximum in the 18 cases checked (15 systems plus 3 output-parity cases; S = 1/2 to 7/2, dimensions 16 to 216, dimers, strain, 5 K populations); speed at 1 thread 1.0-2.0x (Cu(II) + 2 14N [19 4] 2.86 -> 1.45 s, Mn(II) Q band 1.96x, Gd(III) 1.54x, Mn(II) at 5 K 1.48x). RediagLimit >= 1 restores the exact path bit for bit. Systems below dimension 16 and runs on the autograd graph always diagonalize, so gradients do not change. EasySpin’s Opt.RediagLimit defaults to 0.95 with linear interpolation (1.3e-3 for Cu(II) + 2 14N in a prototype); the cubic scheme at 0.95-0.99 still reached 1.1e-4 (§ Resonance eigenvector interpolation).

  • Gradients through the resonance search without replaying it (B14; pepper_autograd, resfields, pepper with graph inputs). The knot search and the model roots now run off the autograd graph; every candidate field is diagonalized once without the graph (pooled, as in the forward-only path) and the graph is attached by first-order perturbation theory: the resonance field gets the implicit derivative dB/dθ = -(∂f/∂θ)/(∂f/∂B), level energies their Hellmann-Feynman derivatives and the two transition eigenvectors the sum-over-states derivative with _linalg’s degeneracy rule (the derivative eigh’s backward computes). Resonance fields are bit-identical with and without grad; gradients change by <= 6e-10 relative (the field derivative is now the implicit one at the candidate instead of the Hermite-model root’s, which agrees with it to the model accuracy) and agree with central differences of pepper as before. Where the slope difference of a transition vanishes (turning point of a looping transition) its field gets no derivative; before, it got the Hermite-model root’s. Cu(II) + 2 14N gradient, GridSize [10 4]: forward + backward 19.2 -> 9.9 s at 1 thread (backward 10.7 -> 2.1 s) and 13.9 -> 4.8 s at 8 threads; peak process memory 8.3-9.8 -> 7.3-8.2 GB. Small systems: backward 1.1-1.6x faster. Forward-only pepper computes the slopes of the two transition levels only: Cu(II) + 2 14N 1.12-1.15x, Mn(II) 1.06-1.08x, small systems unchanged; outputs bit-identical.

  • Real-pulse engine (thyme/spidyan): less work per acquisition point (B11). The chronological event order is cached on the exact event lengths (every orientation repeats the same per-point sequences), free-evolution propagators are cached per orientation on the exact step (a 32 x 32 sweep needs about 65 distinct ones instead of 3000), and a detected free evolution is evaluated in the eigenbasis of the static Hamiltonian, all time points at once, instead of one U sigma U^dagger product per step. The caches are bit-identical; the closed form agrees with the step loop to 7e-13 (it does not accumulate roundoff). Nitroxide two-pulse sweep 0.43 -> 0.34 s, three-pulse 32 x 32 1.83 -> 1.00 s, transient echo detection 2.2 -> 0.29 s (1 thread).

  • Real-pulse engine: pulse propagators from the waveform’s period (B10b). A lab-frame carrier sampled on the simulation grid repeats its amplitude levels exactly every period: the undetected pulse propagator is now (one period)^k times the remainder instead of one product per time step (4000 for a 32 ns pulse), runs of a constant level become matrix powers, and complex excitations compute one matrix exponential per distinct level. Roundoff only (within 8e-13 end to end). Together with B11: nitroxide two-pulse sweep 0.43 -> 0.15 s, three-pulse 32 x 32 1.83 -> 0.82 s, transient echo 2.2 -> 0.24 s.

  • cardamom Method='ISTOs': batched over steps and trajectories (B9). One SciPy expm call for all step propagators and one batched product per time step for all trajectories, instead of a Python loop over every (step, trajectory) pair (5 million expm calls for 50 trajectories x 1000 steps). Roundoff only (within 3e-16; the trajectory average sums in another order). Nitroxide 20 x 400: 8.9 -> 4.8 s; Cu(II) 10.9 -> 7.0 s.

  • mdload: spin-label frames, global-rotation removal and protein-relative frames for all MD frames at once (B18) instead of per-frame Python loops (batched cross products, one batched SVD for the Kabsch fits). Rotations bit-identical, frames within 6e-15. 5000 frames: label frames 0.21 -> 0.0005 s, rotation removal 0.08 -> 0.008 s.

  • saffron ProductRule=True: time signals from the occupied frequency bins only (B12). Each zero-filled peak buffer (512 x 512 for a 128-point HYSCORE) used to go through a full ifft2 for every orientation; the first nPoints are now taken as E1 @ B[rows][:, cols] @ E2.T over the few occupied rows and columns, with exact twiddle phases (FFT when more than a quarter is occupied). Roundoff only (within 1e-12). Product-rule HYSCORE (14N + 1H, 128 points) 0.47 -> 0.06 s; the default (no product rule) path is unchanged.

  • esfit levmar with n_workers > 1 evaluates its trial point and the Jacobian column-refresh probe in one pool round (B4); results are bit-identical to the serial fit. On cheap models the serial default is still as fast; the gain is for expensive ones.

  • chili powder spectra build the orientation-dependent Liouvillian from fixed pieces (B7). The Hamiltonian is linear in the Wigner D-matrix of the orientation, so its 1 + 9 + 25 orientation-independent pieces are built once (from 8 orientations on) and each orientation is one weighted sum on their union sparsity pattern, instead of 50 Hilbert-to-Liouville conversions and 25 Kronecker products. Roundoff only in the Liouvillian (within 4e-16; direct-solver spectra within 7e-15). The Lanczos solver amplifies last-digit changes, and at its default Threshold (1e-6) one can move the step at which it stops: default chili powder spectra change by up to 4e-5 relative (Cu(II) with a potential), below the solver’s own tolerance; with Threshold=1e-9 the two routes agree to 5e-9.

  • Projection kernel: both half-hats in one pass (A4, _projection.hat_segments_t). The edge bins of every linear piece are integrated in one (m, 8) pass with fewer operations (Simpson as L/6 (Lp (2wp + wq) + Lq (2wq + wp)), signed weights, one scatter). Roundoff only: outputs within 9.2e-16 relative of the previous kernel on the parity cases, gradients within 1.1e-15; zero-length overlaps (the derivative at exact bin boundaries) are kept. Kernel 1.3-1.6x faster; end to end up to 1.16x (Cu rhombic, default grid), 1.03-1.06x for most pepper and fit cases.

  • esfit default target is 'fcn' (EasySpin 6’s default) instead of 'auto' (B131). 'auto' picked 'int' for derivative-like data; integrating the residuals turns white noise into a random walk, so on synthetic nitroxide fits the parameters landed up to 8 sigma from the truth (within about 2 sigma with 'fcn'). 'int' and 'auto' stay available for rugged fits from a poor start.

  • Experiment.Harmonic default by sweep mode only (B101): 1 for field sweeps, 0 for frequency sweeps and fixed-field experiments. A frequency sweep that also set mwFreq used to come back as a first derivative.

  • Experiment.Temperature <= 0 raises ValueError (B102). pepper, salt and the perturbative paths treated it as infinite temperature (no Boltzmann factor) while garlic raised; None or inf is infinite temperature.

  • torchspin.isotopologues is the EasySpin port from torchspin.isotopologues (all isotope combinations, natural or custom abundances; returns SpinSystems carrying weight) (B104). The old export was a legacy helper that returned one (weight, sys) pair for the given isotopes and failed for element names such as 'Cu'; it stays available as torchspin.spinsystem.isotopologues.

  • esfit checks its options and bounds before any model evaluation (B111-B113): an unknown method, autoscale ('LSQ' used to mean no scaling), lsq_negative_scale, target, workers, n_workers or baseline raises ValueError; so does an infinite bound with a method that needs finite ones (all but 'lbfgsb', 'powell', 'trf'; they returned NaN parameters, raised mid-run, or, for 'grid', returned p0 with success=True).

  • esfit grid search evaluates the whole grid or raises (B110): a grid larger than max_iter used to be cut to its first max_iter points, which never leave the lowest values of the leading parameters.

  • pepper’s matrix method simulates sets of equivalent nuclei as total-spin blocks (B139; new Options.EquivalentNuclei, default True; deviation from EasySpin, see KNOWN_LIMITATIONS.md). Nuclei with the same isotope, hyperfine tensor and frame and no quadrupole coupling enter the Hamiltonian only through their total spin, so three 14N are four systems of nuclear spin 3, 2, 1 and 0 (dimension 7, 5, 3, 1 times the rest, in place of 27) whose spectra are summed. This is exact (levels equal to 1e-10 MHz, single-crystal spectra with all transitions to 5e-6 on three systems) and removes the exactly degenerate levels of the full space, where 0.9.38 summed intensities over inconsistent bases: three equivalent 1H on a single crystal gave 93.0 % of the intensity (now 100.000 %), and Cu(II) + 3 14N changed by 5.5 % of its maximum with Options.BatchSize (now 5e-7). Default spectra of systems with equivalent nuclei change: Cu(II) + 2 14N by up to 23 % of the maximum in the perpendicular region on GridSize [19 4], where the blocks keep 97.1 % of the complete intensity and the full space kept 91.9 % (error against the all-transitions spectrum on 181 knots: 15 %, from 33 %); S = 3/2 + 2 1H and triplet + 2 14N are unchanged to 1e-8. Cu(II) + 3 14N on GridSize [4 4] takes 2 s, from about 250 s. The synthetic Cu(II) + 2 14N levmar fit of B135 ends at RMSD 0.0110, from 0.0208 (noise 0.0097), in 68 s, from 155 s; its steps remain. EquivalentNuclei=False restores the full space. Not applied with quadrupole coupling, nn, H0Extra, a full-space initState, Transitions level pairs or separate other than 'components', nor in pepper_autograd and salt.

  • pepper’s matrix method accepts SpinSystem.n > 1 through the same blocks (it raised); it still raises where the set cannot be reduced.

  • pepper’s matrix method searches large grids in smaller orientation batches (B138). The orientations of a batch share one set of field knots, and the automatic batch assumed 10 knots per orientation where a large batch of a large spin system reaches 100 or more. It now budgets 200: 96 orientations per batch at Hilbert-space dimension 36, 24 at dimension 72 (it was 1929 and 482). S = 5/2 + 55Mn on a 1013-orientation Ci grid: 414 s to 105 s at one thread (0.9.38: 221 to 228 s); Cu(II) + 2 14N on GridSize [19 4]: same time, peak memory 10 to 15 GB down to 2.9 GB. Spectra of nine test systems agree to 2.3e-8 of the maximum (seven are bit-identical). Options.BatchSize still overrides the automatic choice; hybrid, pepper_autograd and salt are unchanged.

Fixed#

  • Coarse grids of two or three knots (B137). pepper with Options(GridSize=[2, n]) returned an all-zero spectrum, without an error or a warning, whenever the grid had two orientations: every axial system (Dinfh grid; matrix and perturbation methods, strains, frequency sweeps) and the C4h and C6h grids. Transitions with fewer than three knots were dropped before the interpolation. On the open-phi 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 instead. All of these now interpolate: the spline through two knots is the zero-slope cubic (axial) or the straight line, through three the parabola, as in EasySpin’s esspline1d; pepper equals pepper_autograd, which already handled the axial case, to 1e-9. Such grids are far from converged (use grid_convergence), and EasySpin’s pepper rejects GridSize(1) < 10 (§ Coarse grids of two or three knots). Outputs of grids that worked before are unchanged (34 output-parity cases identical).

  • esfit uncertainties for target='int' and 'diff' (B131). The HC1 sandwich treated the transformed residuals as independent and understated pstd 2-25x for 'int' (Monte Carlo, 300 noise realizations of a three-line derivative spectrum); its middle term is now J' T diag(r^2) T' J with the untransformed residuals r. 'fcn' uncertainties are unchanged.

  • FitResult.r_squared (B100) is 1 - SS_res/SS_tot about the mean of the data. It used to rebuild the data as fit + residuals (= 2 fit - data) and could be far off for poor fits (reported -1.5e12 where the true value was 0.7); nan for constant data.

  • SpinSystem.Ham accepts EasySpin’s 'Ham112' keys (B103), stored as '112'; the prefixed form used to pass construction and crash in the Hamiltonian. Malformed or duplicate keys raise.

  • Fast-motion garlic line widths use gFrame and AFrame (B105). The widths depend on the relative orientation of g and A and ignored both frames (a 90 degree A tilt on a nitroxide changed nothing, now 58 % of the peak). Checked: rotating g and A together leaves the widths unchanged to 4e-15, an AFrame equals the rotated full A matrix exactly, and the tilt effect on the line heights agrees with chili in the fast limit (low-field/center height ratio changes by 0.59x in both).

  • Fast-motion garlic with a full 3x3 Q (B106) crashed; the quadrupole width uses the rotation invariant sum of Q_ij^2 and equals the principal-value result exactly.

  • garlic reads Diff/logDiff and mwMode (B107). Diff (isotropic) selects the fast-motion regime with tcorr = 1/(6 Diff), as in EasySpin, instead of being ignored (an 85 % different spectrum); mwMode overrides Mode ('parallel' gives the zero spectrum of S = 1/2), other geometries raise NotImplementedError.

  • differentiable_spectrum with A but no Nucs raises (B108) instead of dropping A.

  • grid_convergence with parameters that require grad (B109) crashed in np.asarray.

  • chili powder spectra with Rescale=True (the default) (B129): every orientation (and, for an explicit field sweep, every field point) is divided by the scale of its own Liouvillian. The powder sum used to be divided by the last orientation’s scale, as EasySpin’s chili.m does, which weighted each orientation by scale_i/scale_last: Rescale on vs off differed by 2.7e-4 (nitroxide, ordering potential, 20 ns) and 7.5e-3 (Cu(II), potential, 5 ns); now 9e-8 and 3.8e-5 (Lanczos threshold). Deliberate deviation from EasySpin (KNOWN_LIMITATIONS).

  • saffron time-domain signal for 2D incrementation schemes [1 2 1], [1 2 2 1] and [1 1 2 2] (B130; Opt.TimeDomain=True, and every saffron gradient, which forces the time domain). The free evolutions were applied in the wrong order (and [1 2 2 1]/[1 1 2 2] kept only the diagonal phases of the second dimension), so the ESEEM modulation was 50-155 % wrong. Now one routine chains the evolutions and mixing steps in sequence order with the frequencies of EasySpin’s sf_peaks.c. Checked: on an exact frequency grid the time signal equals the inverse DFT of the frequency-domain peaks to 4e-14 for every 2D scheme ([1 2], [1 1 2] included); end to end (14N and 1H, custom sequences) the frequency-domain result converges to the time-domain one as Opt.Expand grows (1-2 % at Expand 7, as for HYSCORE), where before it stayed 50-155 % off. EasySpin has no time-domain route for these schemes.

Documentation#

  • Matrix-method spectra with several nuclei are not smooth in the parameters (B135). New section in KNOWN_LIMITATIONS.md and a note in the fitting guide: for S = 1/2 systems with a large metal hyperfine coupling and ligand nuclei the spectrum changes in steps (up to 7.9 % of its maximum for a 6e-6 change of g∥ in a Cu(II) + 2 14N example), so least-squares fits can stall above the noise level. Present in 0.9.38 and, inside the total-spin blocks, in this release (see the equivalent-nuclei entry under Changed).

[0.9.38] — 2026-11-15#

Added#

  • Documentation site (https://follmerlab.github.io/torchspin/), built with Sphinx from docs/ (pydata-sphinx-theme, MyST Markdown, notebooks rendered without execution).

    • Navigation, user-first: Getting started, a User guide of task pages with checked examples, Tutorials, Installation, the API reference, and Troubleshooting and reference.

    • The API reference documents every public name (198) at its public path. A local extension adds repository links, the tutorial notebooks, a constants directive and a warning for any undocumented public name.

    • The docs workflow builds the site for every pull request and deploys it from main to GitHub Pages. pip install -e ".[docs]" and make -C docs html build it locally.

    • The development notes (roadmap, real-pulse plan, acceleration notes) stay in the repository but are not published.

  • Standardized docstrings (NumPy style) for the core API (SpinSystem, Experiment, Options, pepper, garlic, esfit/FitOptions/FitResult, differentiable_spectrum, grid_convergence) and all 22 public torchspin.lft modules, with cross-references between public names. Code is unchanged (checked file by file with docstrings stripped); some docstrings that disagreed with the code were corrected (e.g. the Harmonic default, ModAmp readers, esfit target='auto', the claim that Euler frames carry no gradient). The site builds with no warnings.

  • Doctests in the default test suite: torchspin/tests/test_doctests.py runs the docstring examples of 29 modules.

  • Physics and validation pages: docs/physics_validation.md (one row per simulator: what it computes, method, what it is validated against, strongest evidence, main caveat; the five kinds of evidence) and one page per simulator in docs/physics/ (model, method, validation with the test files, limitations). docs/chili_empirical_rules.md derives chili’s symmetry basis. Developer pages, not on the site: docs/physics/coverage_gaps.md, docs/physics/manuscript_claims.md.

  • Installation guide (docs/installation.md): pip and uv routes for CPU and CUDA builds of PyTorch, keeping an existing PyTorch, conda, contributors, and platform notes. Every route says whether it creates the environment for you. docs/installation_validation.md records what was tested (macOS arm64, Python 3.10–3.13, pip and uv, all nine tutorial notebooks executed); Linux, Windows and CUDA routes are not yet validated by hand.

  • notebooks extra (pip install "torchspin[notebooks]"): Jupyter plus everything the shipped tutorials import (matplotlib, ipywidgets, ipympl, cloudpickle).

  • install-docs workflow: checks the documented installation routes against a wheel of the commit in clean Linux, Windows and macOS environments (on pull requests that touch them, and weekly). It cannot exercise CUDA.

Changed#

  • PyTorch floor raised to torch>=2.3,<3. The published floor torch>=2.0 was wrong: torch 2.0.1 and 2.1.2 fail (torch.any(dim=tuple) in resfields_batch), and 2.2.2 works only with numpy < 2. Intel Macs, whose last PyTorch is 2.2.2, are no longer supported.

  • torchspin.__all__ lists ham_ezho once (it was listed twice); the public names are unchanged.

  • README: links the documentation site; corrected accuracy claims (salt > 0.99 with orientation selection, curry 0.5–1 %, the speed numbers measured on v0.2.2); a shorter install section; an acknowledgment that torchspin was developed with help from Claude (Anthropic).

  • KNOWN_LIMITATIONS: the garlic paragraph listed automatic sweep ranging, isotope mixtures, multi-component input and separate as not ported; they are ported.

  • The docs and docstrings refer to Josh Telser by the name he uses.

Fixed#

  • chili: the M–pS–pI symmetry basis is derived, exact, and no longer halves highField spectra (B114, B115). Without director tilt, and with a potential that has only M = 0 terms, the Liouvillian conserves pS + pI − M. The S_x starting vector then splits into +1 and −1 blocks, and the −1 block is the complex-conjugate mirror of the +1 block: I(z) = ½[I₊(z) + conj(I₊(conj z))]. MpSymm now keeps the +1 block and adds the mirror term, so MpSymm=None, True and False return the plain-basis spectrum. Measured against the plain basis solved directly: 5e-16 for a nitroxide, 6e-16 for ⁶³Cu, 5e-11 for S = 1 with D = 100 MHz, 2e-8 with D = 500 MHz.

    • The default (MpSymm=None) now prunes every untilted system. Before, an empirical rule applied only to one S = 1/2 electron with ≤ 2 nuclei, no potential and a rhombic LLMK. Pruning shrinks the basis about 6×.

    • highField=True with the default returned 0.5× the plain-basis spectrum (B114). The factor is now 1, as in EasySpin (fast vs general direct: ratio 1.00000).

    • An explicit MpSymm=True raises ValueError under director tilt (powder grid with a potential, tilted Exp.SampleFrame) or with M ≠ 0 potential terms, where the symmetry does not hold (B115). Before, it returned a wrong spectrum (cosine 0.67, 6.9× amplitude for a nitroxide with Potential=[2 0 0 1], GridSize=5), as EasySpin’s general method still does.

    • An explicit MpSymm=True no longer returns twice the plain-basis amplitude. EasySpin’s general method still does; see KNOWN_LIMITATIONS § Chili.

  • chili: the Lanczos no longer stops at a near-breakdown (B116). EasySpin’s rule accepts the first check step whose Lentz change is below Opt.Threshold. In the pseudo-norm recursion a near-breakdown can pass that test while the continued fraction is far from converged. For the ¹⁴N nitroxide at τc = 100 ns (default LLMK, plain basis) it stopped at step 40, with cosine 0.9648 against the direct solve.

    • A passing check is now accepted only if the spectrum then moves by less than 100 × Threshold over the next interval. The accepted spectrum is the same one, so converged results are unchanged.

    • A full-length tridiagonalization counts as converged.

    • A Lanczos that does not converge warns once and falls back to the direct solver. Before, it silently returned ones(nPoints), as EasySpin does.

    • EasySpin’s own default (fast) output has the same early stop for this nitroxide at 256 points (cosine 0.9647 against its general method solved directly). It also explains the loosened ext case simple_tc1e-07: with Opt.Threshold=1e-10, EasySpin’s output matches torchspin to cosine 0.9999966. That case’s comparison with EasySpin’s default output is now held to the default 0.999 / 2 % as a strict xfail (it was loosened to 0.997 / 8 %); the converged comparison is the objective check.

    • Default outputs on the stored EasySpin cases change by at most 0.06 % in amplitude (simplepotential_grid19, plain basis on a powder grid). No tolerance was loosened.

Tests#

  • The torchspin.lft parity tests against telser-tools now run without telser-tools. CI does not install telser-tools, so 618 tests in the lft files were skipped there. Now 1405 run and pass without telser-tools. The 5 that still skip are the 2 dpnfit cases with no free parameter and the 3 magnetometry tests, which stay live-only (their oracle, telser_tools_diff, runs on torch).

    • The telser-tools values the tests use (results, parsed inputs, constants) come from oracle functions in the test modules. They run live when telser-tools is importable; otherwise the tests use the copies in torchspin/tests/data/telser/refs/*.npz (13 files, 2.6 MiB). TORCHSPIN_TELSER_REFS=frozen forces the stored copies.

    • torchspin/tests/data/telser/generate_telser_refs.py writes those files with their provenance (tests/data/DATA_PROVENANCE.md).

    • Tolerances are unchanged, with two changes for the frozen copies:

      • Bit-for-bit checks of BLAS-order-dependent products, such as L2 = Re(Σ L_i L_i), are evaluated from the stored factors in the test’s own process.

      • Term projectors, stored factored, are compared at 1e-12 - 1e-13.

      • The engine-copy identity checks (dsoxf zero_field/spin_spin, the dlsd5 tetragonal solutions, the ddnpow igloo grids) stay exact against live telser-tools. Against a frozen copy, made on another platform, they allow 4 ulp of the largest entry: Linux and Windows libm/BLAS round some of these values 1 ulp (1.1e-16) differently from macOS. The dlsd5 tetragonal solutions, whose closed forms amplify round-off (up to 1.55e-15 seen), allow 1e-13 × max(|value|, 1).

    • Exception (d1_skipdeg_field): g(obs) at its 1 mG field (level splitting ~1.8e-9 cm⁻¹) is ill-conditioned: it moved by up to 2e-3 between torch 2.10 and 2.15, even against live telser-tools. It is compared at rtol 2e-2 (10× that), instead of 1e-9.

    • test_lft_telser_refs.py checks that the stored keys match the oracles. With telser-tools importable, it also checks that the stored values still equal live telser-tools to round-off.

    • No code change.

  • EasySpin reference for frequency sweeps with field-quadratic Sys.Ham2xx terms. EasySpin’s resfreqs_matrix.m could not run them before StollLab/EasySpin d46e5ef9 (it tested for obsolete ZB* fields), so Options.QuadraticZeeman frequency sweeps were checked only against the full Hamiltonian. ref_pepper_quadzeeman.mat now has an S = 1 frequency sweep from the fixed EasySpin: cosine 1.0000000, amplitude 0.99988. No code change.

[0.9.37] — 2026-11-14#

Fixed#

  • dataproc.fieldmod_t: wrong Bessel kernel for harmonic >= 3 at small arguments (B93). _besselj_t computed J_n for n >= 2 by the upward recurrence J_{k+1} = 2k/x J_k - J_{k-1} from torch’s J_0/J_1 for every |x| >= 1e-3, with (x/2)^n/n! below. The recurrence is unstable for |x| < n: J_3 jumped 6.4 % at the 1e-3 switch (2.2157e-11 vs 2.0833e-11), J_4(1e-3) was 7.94e-9 (true 2.60e-15), J_6 was off by up to 0.22 absolute, and Harmonic >= 3 central differences of fieldmod_t with respect to ModAmp did not converge (H = 6 autograd vs CD off by 99 %). n >= 3 now uses the power series (summed until the first omitted term is below 1e-18 at |x| = n: 14 terms at n = 3, 41 at n = 30) for |x| < n, exact parity for x < 0, and the recurrence only for |x| >= n. n = 3-6 match scipy.special.jv/jvp to 3.6e-7/2.4e-7 absolute (the torch J_0/J_1 floor, recurrence branch) and to 1.8e-14 relative on the series branch; the jump at |x| = n is <= 2.7e-7. Harmonic 3 CD now converge (h = 1e-3 to 1e-4 agree to 1e-10 relative) and match autograd to 4.2e-8. Orders above 30 raise ValueError (series cancellation: 1.3e-11 absolute at n = 30, 9.6e-10 at n = 40; before, n >= 21 raised OverflowError). Only direct fieldmod_t(..., harmonic >= 3) calls were affected: pepper, pepper_autograd and garlic cap Harmonic at 2. Orders 0-2 are unchanged (bit-identical fieldmod_t values and gradients for Harmonic 0-2).

Documentation#

  • KNOWN_LIMITATIONS: the ModAmp kernel is bounded by torch’s bessel_j0/bessel_j1 accuracy (about 4e-7 absolute for x in 5-10 on torch 2.10 and 2.15).

[0.9.36] — 2026-11-14#

Fixed#

  • salt, fixed field: isotropic systems (O3 grid) were not differentiable (B86). A system whose grid is O3 (a scalar-leaf A keeps O3) went through the stick paths (B_res_all = [B_fixed] * n_orient, .item() per line, nearest-point rounding) and returned a detached spectrum: RuntimeError: element 0 of tensors does not require grad. The transitions at the single orientation are now computed on the graph (_fixed_field_transitions, as on the projection path) and every line enters as a bin-integrated Gaussian of FWHM lw at its exact position (pepper’s O3 template path); lw = 0 splits each line linearly between the two nearest points (the centered convention of B85). Gradient vs central differences 3e-11 (1H, A = a[1 1 1]; also with Options.Enhancement and for lw). Forward on 512 points over 10 MHz against a 32x finer axis: 2.6 / 7.8 / 16 % -> 0.10 / 0.88 / 3.4 % of the maximum (lw 0.3 / 0.1 / 0.05 MHz). Three A leaves (auto D2h, projection path) give the O3 gradient to 4.1e-2 (512 points) and 4.2e-3 (2048 points); on 0.9.34 that sum was 5.4e-23 (truncated sub-bin facets, fixed by B85).

  • Deliberate deviation from EasySpin (salt.m:657-668 builds sticks with lisum1i at width dx/100 and convolves, skipping a Gaussian lw of at most two increments): the template always carries lw. No existing test moved.

Tests#

  • test_salt_o3_grad.py: O3 gradient vs converged central differences (lw 0.3 and 0.05 MHz), three-leaf D2h gradient vs O3 (512 and 2048 points), forward vs a converged reference (three line widths), lw = 0 linear split, Enhancement (matrix path) and lw gradients. 8 of its 10 tests fail on 0.9.35.

[0.9.35] — 2026-11-14#

Fixed#

  • Projected powder spectra sat half an increment low, and sub-bin facets had no position derivative (pepper, pepper_autograd, salt; B85). The SOPHE projection (EasySpin projecttriangles.c/projectzones.c convention) integrated each facet over [x_k, x_k + dx) and reported it at x_k, and dropped facets narrower than one bin into one bin by truncation. Every projected spectrum was shifted by -dx/2 (best-fit shift +0.49 dx against a converged reference), while the template paths (isotropic, crystal, Exp.Orientations) are centered; and for an isotropic g on a D2h grid (the automatic grid for three g leaves on the graph) the gradient along g = s[1 1 1] was +999.7 (equal to central differences of that spectrum) against the true -13770. The projection is now torchspin._projection, shared by the numpy (pepper) and torch (pepper_autograd, salt) paths: axis point k carries the facet density integrated against the hat of half-width dx centered on x_k (a zero-width facet is split linearly between the two nearest points). The result is continuous in every vertex position for any facet width; the hat-weighted integral of each linear piece is exact (Simpson on each half-hat, from overlaps and relative positions only), facets inside one axis interval are deposited exactly as a point mass at their centroid, and uncovered bins stay exactly 0 (B47). Numbers: 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 %); isotropic on a forced D2h grid vs the O3 template 2.8-5.5 % -> 2.3-5.2e-4 (4096 points) and 4.7-34 % -> 2.0-3.2 % (512 points); isotropic-direction gradient -11452 at 512 points (O3 -13770; dx/sigma = 0.28) and within 3.2 % of the O3 gradient at 4096 points, equal to central differences to 1e-10; integrated intensity conserved to 2.4e-14 (2.9e-12 before); pepper vs pepper_autograd 1.5e-12 as before; Exp.Orientations (20000-point Fibonacci sphere) vs the powder 5.9e-5 without the former -dx/2 axis shift, zero-field 0.077 % (0.74 %).

  • Deliberate deviation from EasySpin (KNOWN_LIMITATIONS.md § Centered projection bins): every projected pepper/salt spectrum moves by dx/2 and is smoothed by the hat (variance dx²/6 against the box’s dx²/12). pepper’s unreachable stick-accumulation branches now split linearly too; int(frac) there truncated toward zero for lines just below the range.

Tests#

  • test_projection_centered.py: best-fit shift < 0.1 dx (0.9.34: +0.49), forced-D2h isotropic vs O3, isotropic-direction gradient vs converged central differences and the O3 gradient, zero-width triangle/zone linear split and gradient, continuity in width, intensity conservation, numpy == torch, pepper vs pepper_autograd. 21 of its 24 tests fail on 0.9.34.

  • 168 EasySpin comparisons moved by the centered bins are strict xfail with their measured numbers (_b85.MOVED, applied in conftest); test_b85_easyspin_centered.py re-runs them against EasySpin mapped onto centered bins: 73 pass with their original tolerances, 95 (box- binning-calibrated tolerances, stick spectra) are strict xfail there with both numbers.

  • ref_missing_knots.npz regenerated with the centered bins. The sixteen coarse- vs converged-grid checks the centered bins moved (case3/d4h_d2hgrid_wide/s52_b4_D2h_h1, s52_b4_C2h_h1, s52_rhombic_h1, b50_h1, b50_stick_wide, oh_auto; pepper and pepper_autograd) now compare with ref_converged_b85.npz (generate_converged_b85_refs.py: field axis 16-32x finer, GridSize [181 1], point values at x_k), bounds = measured x 1.05; 0.9.34 fails all of them (e.g. case3 max deviation 0.337 vs bound 3.70e-2). The lw central-difference step in test_missing_knots.py is 2.5e-5 (was 1e-4): case1’s d/dlw is small (6.16) with the centered bins, and the h^2 truncation error at 1e-4 was 1.07e-7 relative (7.7e-9 at 2.5e-5); bound 4e-8 unchanged.

  • test_projection_accuracy.py: rhombic lw 0.3 mT, 512 points vs a converged reference (max error 3.73e-2, 0.9.34 0.321), d/dlw and d/dg_y vs converged values (1.1e-3 and 3.3e-5; 0.9.34 5.2e-2 and 3.3e-3), isotropic-direction gradient at 4096 points vs converged O3 (3.2e-2; 0.9.34 wrong sign). All four fail on 0.9.34.

  • Kernel choice: a centered box with a linear split below one bin (branch dev/b85-box, not merged) was compared against converged references: 5-30 % lower forward error for narrow lines, but d/dg_y 2.0e-3 (hat 3.3e-5) and a gradient kink at facet width dx; the hat was kept (KNOWN_LIMITATIONS.md).

  • Rewritten for the new kernel: test_projecttriangles_edge_bins.py (exact rational hat reference), the B47 helper tests of test_pepper_exactzero.py (the _ramp_bins source patches are gone; uncovered bins exactly 0 vs the loop reference), the reference loops _projecttriangles_loop/_projectzones_loop (two-point Gauss-Legendre per piece). The -dx/2 compensations in test_pepper_orientations.py, test_endor_enhancement.py and test_lft_telser2torchspin.py are removed (same tolerances).

[0.9.34] — 2026-11-14#

Fixed#

  • DCD trajectories with a CHARMM unit-cell record are read correctly (B97). _read_dcd took the unit-cell flag from bit 0 of the int32 at file offset 84, which is the CHARMM VERSION (24 in NAMD files, so the flag was always off). Every frame’s 56-byte unit-cell record was then read as coordinates, and both bundled trajectories came out shifted: the first x value of A10R1_polyAla.dcd was 0.0 instead of -14.474 (max error 60.5 Å over the EasySpin atom subset), A10TOAC_polyAla.dcd gave values up to 1.8e34. The frame count (20 and 4) was right only because the leftover bytes were too short for another frame. The reader now follows md_readdcd.m: VERSION > 0 means CHARMM, the int32 at offset 48 == 1 marks the unit-cell record and the one at offset 52 == 1 a fourth coordinate record; VERSION == 0 means X-PLOR, with no extra records and DELTA read as a float64 (it was read as a float32). Deviation from EasySpin: md_readdcd.m treats the 4-dims flag as a unit-cell flag (skipping 56 bytes before x); torchspin skips the fourth coordinate record after z instead. Coordinates of both bundled files now equal EasySpin’s md_readdcd exactly, and mdload’s FrameTraj, FrameTrajwrtProt and RProtDiff match EasySpin’s mdload_files_R1/TOAC.mat to 4e-16 (errors up to 1.95 before). mdhmm and the cardamom MD tests use the pre-processed MTSSL_polyAla_traj.mat and are unaffected.

Tests#

  • New ref_md_readdcd.mat (tests/data/generate_md_readdcd_refs.m, EasySpin md_readdcd). test_mdload.py checks the bundled DCD coordinates against it, that the reader consumes the files exactly to EOF with one unit-cell record per frame, that the fixed protein atoms equal the PDB coordinates in every frame, the mdload label frames against EasySpin’s mdload_files_*.mat, and synthetic CHARMM files with and without the unit-cell and 4-dims records plus an X-PLOR file. 12 of the 13 new tests fail before the fix.

[0.9.33] — 2026-11-14#

Fixed#

  • Field-sweep gStrain/AStrain widths are rotation covariant (B84). The g-strain model is a distribution of the principal g values in the g frame, width² = Σ_i (R z)_i² (gStrain_i/g_i · mwFreq)² = z’ G G z with G = R’ diag(gStrain/g · mwFreq) R. compute_strain_widths_batch used the element-wise square z’ (G∘G) z (one electron, each electron of a multi-electron system, and |(G + c·mI·A) z|² with AStrain), which equals the model only for a diagonal G. It now uses the matrix square G @ G (and SM @ SM). hamsymm’s strain-symmetry tensors (B82) follow: G·G, A·A and G·A + A·G instead of G∘G, A∘A and G∘A, so strain collinear with a tilted g frame now has the symmetry of g in that frame (Dinfh/D2h) instead of Ci. Numbers (S = 1/2, 9.5 GHz, gFrame = [0.4 0.9 -0.3] against the untilted system at the rotated field direction): per-orientation widths for g = [2.0 2.0 2.2] / [2.0 2.1 2.3] with gStrain = [0.01 0.01 0.05] / [0.01 0.03 0.06] differed by up to 104 % / 108 % and now agree to 1e-15; two electrons with the same tilt 82 % -> 7e-15; g+A strain and AStrain alone (isotropic g and A, AFrame tilted with g) 92 % -> 2e-15; pepper powder spectra ([19 4] grid) 27 % / 9.2 % of the peak -> 2.5e-14 / 8.3e-15 (same grid now). Gradients: pepper_autograd at user orientations gives the same d/dgStrain for the tilted and the untilted description (before: 1.26 relative apart); gStrain and gFrame gradients on a fixed Ci grid match converged central differences (1.2e-8 and 1.2e-6 relative at h = 1e-6). Untilted frames (diagonal G) give bit-identical widths and spectra. Frequency sweeps (linear z’ G z) were already covariant and are unchanged; the perturbation-theory paths compute no strain widths.

  • Deliberate deviation from EasySpin. EasySpin has the same element-wise square (resfields.m 787/792/1309, resfields_perturb.m 523/532, resfreqs_perturb.m 504), so its widths with a tilted g or A frame and g/A strain depend on the frame description. Four EasySpin comparisons are now strict xfails, each with an objective replacement test: test_strain_validation.py tilted_frame (RMS 0.0874 -> 0.0996, peak ratio 0.944 -> 1.252; replacement: the tilted system equals the untilted one to 1e-10 and passes against EasySpin’s untilted reference), test_strain_widths_matlab_validation.py two_spinhalf_gstrain_both (max relative width deviation 3.4e-4 -> 0.17; replacement: a global rotation of the two-electron system leaves every width unchanged, 0.54 -> 2.3e-15) and the two Cu63_AFrame width tests in test_astrain_mi_model.py (9.2e-6 -> 0.45; replacement: both width functions equal the explicitly written model with the matrix square to 4e-16, and the same model with EasySpin’s element-wise square reproduces EasySpin’s widths). See KNOWN_LIMITATIONS.md.

  • Not covered: the AStrain mI labels (EasySpin’s model, taken along the molecular z axis) are not rotation covariant with anisotropic A or with anisotropic g in a tilted frame (B96, open).

Tests#

  • New torchspin/tests/test_gstrain_covariance.py (13 tests; 12 fail before this change): per-orientation widths of tilted vs untilted systems (axial, rhombic, two electrons, g+A strain and AStrain with isotropic g and A) at 1e-12; pepper powder spectra at 1e-10; hamsymm Dinfh/D2h for tilted collinear strain; pepper_autograd spectrum and d/dgStrain covariance at user orientations; gStrain/gFrame gradients against converged central differences on a fixed Ci grid (step-size table in the test; passes before the fix too).

  • New objective tests in test_strain_validation.py, test_strain_widths_matlab_validation.py and test_astrain_mi_model.py (see above).

  • test_ham_handling.py::test_pepper_gstrain_ham_gframe_converged_reference (Ham110/Ham112 + gStrain with a gFrame): the default grid is now D2h [19 4] in the g frame instead of Ci, and its 1 - cos against the C1 [91 1] reference is 9.5e-7 (as for the untilted system) instead of 1.07e-7. The bound 1.2e-7 is kept on a D2h [31 4] grid (8.8e-8); the default spectrum is now checked against the untilted system (1e-13) and EasySpin’s untilted spectrum (cosine 0.9999999966, max deviation 9.2e-5, the ‘diag’ case tolerances). Before the fix the tilted default differed from the untilted one by 0.25 of the maximum.

[0.9.32] — 2026-11-14#

Fixed#

  • Errors that were swallowed silently now raise or warn (B80). Results for valid inputs are unchanged.

    • spidyan / saffron (thyme): overlapping pulses raise ValueError("Pulse overlap detected between events [...]"), as EasySpin s_reorder_events.m errors ‘Pulse Overlap’. Before, the ValueError of _reorder_events was caught and the unreordered sequence simulated, so [{tp 0.016, π/2}, -0.010, {tp 0.016, π}, 0.2] returned a signal.

    • spidyan / saffron (thyme): a non-finite Hamiltonian, relaxation superoperator (Sys.T1, Sys.T2, e.g. a T2 so small that 1/T2 overflows) or equilibrium state (Sys.eqState) raises a ValueError that names the input. Before, the steady state was set to zero, so a NaN in Sys.eqState gave a finite signal relaxing toward ρ = 0. The steady-state solve keeps its pseudo-inverse fallback for a singular −L (e.g. T2 = ∞ with degenerate levels; the right-hand side has no null-space component, so σ_ss = ρ_eq exactly), now only on LinAlgError, and without the inner fallback to zero.

    • ham_ee(sys, eSpins) and ham_nn(sys, nSpins): out-of-range (including 0-based), duplicate or non-integer spin indices raise ValueError, as in EasySpin ham_ee.m:52-60 and ham_nn.m:57-63. Before, invalid pairs were skipped, returning a zero or partial Hamiltonian (ham_ee(sys, [1, 5]) was 0 for two electrons). ham_nn with fewer than 2 indices raises too (it returned zeros). As in EasySpin, both still return zeros before checking the indices when there is nothing to couple (one electron / fewer than 2 nuclei, or ee / nn all zero).

    • esfit: a model evaluation that raises ValueError, RuntimeError or LinAlgError is still penalized with RMSD 1e10, but the first one in a fit issues a RuntimeWarning with the error text, and the new FitResult.n_failed_evals counts them (also for evaluations in worker threads or processes: the penalty value carries the error back to the parent). An exception in FitOptions.callback or in a FitOptions.progress callable no longer disappears: the fit continues and the first one per fit is reported with a RuntimeWarning. An exception in FitOptions.stop_when now propagates out of esfit (before, it was ignored and the fit ran to its normal end): a stop condition that cannot be evaluated cannot be honored.

    • eprload: a file whose header matches a JEOL process type but that the JEOL loader cannot read raises ValueError("JEOL file '...' (process type '...') could not be read: ...") chained to the loader error. Before, the error was discarded and the message was “Unsupported file extension”.

    • mdhmm: a singular state covariance is still regularized with +1e-6·I, now with a RuntimeWarning.

    • mdload (DCD and TRR readers): when frame reading stops before the end of the file (a truncated last frame, or bytes the reader cannot decode as a frame), a RuntimeWarning gives the number of frames read and of bytes ignored. Before, the trailing bytes were dropped silently. The warning fires for both bundled DCD files (tests/mdfiles/A10R1_polyAla.dcd, A10TOAC_polyAla.dcd): _read_dcd takes the CHARMM unit-cell flag from header word 80:84 (the CHARMM version, 24) instead of 44:48 (EasySpin md_readdcd.m:107-110), so it does not skip the 56-byte unit-cell block of each frame and the coordinates are shifted by 14 atoms. That reader bug is not fixed in this release.

Added#

  • FitResult.n_failed_evals (int, default 0): objective evaluations at which the model raised and was penalized with RMSD 1e10.

Tests#

  • New torchspin/tests/test_no_silent_fallbacks.py (33 tests; 26 fail before this change): the cases above, plus guards that pass before and after: the pseudo-inverse steady state for T2 = ∞ with a degenerate Hamiltonian (solve raises LinAlgError, σ_ss = ρ_eq to 1e-14, residual < 1e-14), the regular steady state bit-identical to scipy.linalg.solve, a non-overlapping negative delay, valid ham_ee/ham_nn indices, the EasySpin zero returns of ham_nn, and a non-JEOL unknown extension.

[0.9.31] — 2026-11-14#

Fixed#

  • Frequency-sweep AStrain widths follow AFrame and are differentiable in AStrain (B90). compute_strain_widths_freq_batch built the AStrain operators as float(AStrain[c]) * I_c S_c along the molecular axes: AFrame was ignored, and float() cut the gradient with respect to AStrain (an AFrame gradient came only through the eigenvectors). The term of principal value k is now AStrain_k * m((R'S)_k (R'I)_k) with R = R_A2M = erot(AFrame)’ (as in the field sweep), i.e. AStrain_k times dnu/dA_k, the derivative of the transition frequency with respect to the principal value, with AStrain and AFrame on the graph. Numbers (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, φ = 0.7, θ = 1.1): the outermost allowed lines had 19.0 and 18.5 MHz instead of 56.9 and 56.5 MHz, the next allowed lines 6.5 and 6.0 instead of 18.9 MHz; now every transition equals sqrt(Σ_k (AStrain_k dnu/dA_k)²) from eigenvalue central differences to 8e-8 MHz. A pepper frequency sweep (A = [30 60 450], AStrain = [10 20 80] MHz) with AFrame = [0 π/2 0] equals the untilted system with A and AStrain permuted to 1.4e-13 relative (before: 0.31); with AFrame = [0.4 0.9 -0.3] the spectrum changes by 0.17 relative. Gradients with respect to AStrain and AFrame match converged central differences to 3e-11 and 7e-10 relative. AFrame = 0 is unchanged (the same operators; pepper spectra with H/g/A strain identical to 3e-16). A width that is exactly zero now has a finite gradient (sqrt guarded at 0) instead of NaN.

  • Deliberate deviation from EasySpin. EasySpin’s resfreqs_matrix.m (567-583) rotates I with R(c,k) but S with R(k,c), the transpose. That equals dnu/dA_k only when R is symmetric up to signs (AFrame = 0, a swap of two axes such as [0 π/2 0]); a cyclic axis permutation ([π/2 π/2 0]) is already off by 7.3 MHz on the system above, the tilt above by up to 35 MHz. EasySpin (GitHub main, MATLAB R2024b), resfreqs_matrix for the system above with Exp.SampleFrame = [0 -1.1 -0.7] (field along [0.6816 0.5741 0.4536] in the molecular frame, as φ = 0.7, θ = 1.1), gives 21.44 and 21.86 MHz for the outermost allowed lines and 7.20 and 7.24 MHz for the next, against 56.85, 56.48, 18.92 and 18.87 MHz from eigenvalue derivatives; torchspin returns the latter. See KNOWN_LIMITATIONS.md.

  • AStrain (field and frequency sweeps) and gStrain (frequency sweeps) with more than one electron spin raise ValueError (B89), as EasySpin does (resfields.m 89-92, resfreqs_matrix.m 102-106). Before, a field sweep raised only together with gStrain and otherwise dropped AStrain silently (also pepper_autograd), and a frequency sweep applied the first electron’s gStrain and AStrain. The check is in resfields_batch (also when no line is in range), compute_strain_widths_batch and compute_strain_widths_freq_batch. Multi-electron gStrain in field sweeps (per-electron model) is unchanged.

Tests#

  • New torchspin/tests/test_freq_astrain_frame.py (15 tests; 12 fail before this change): widths of all transitions against eigenvalue central differences at a generic AFrame; a pepper frequency sweep with an axis-swap AFrame against the permuted untilted system; AStrain and AFrame gradients against converged central differences of an independent Hellmann-Feynman implementation (step-size table in the test); AFrame = 0 against the molecular-axis formula; a finite gradient at zero width; the B89 ValueError in every path.

[0.9.30] — 2026-11-14#

Fixed#

  • lft.ddnpow.simulate: wrong spectrum gradients on the default Rayleigh-Ritz path (subspace=True) (B94). The sweep is solved in a detached basis Q (low eigenvectors at three fields and at zero field). The eigenvectors were differentiated inside the fixed Q only, so their components outside Q were dropped, and the Ritz problem coupled the low states to the SVD-mixture directions of Q (not eigenvectors) with spurious gaps. Transition energies were right (Hellmann-Feynman on accurate Ritz vectors); transition probabilities were not, whenever a parameter moves the low states’ admixture of states outside Q. d^7 Co(II) (120 states, four AOM ligands, X band, reported from the YangHolonomy co_kramers_epr survey): d/d e_sigma +27.7 % and +9.9 % at 160 and 240 mT against the full basis (which agrees with central differences); at one orientation dP/d e_sigma -2.18e-5 against -4.157e-4. The derivatives now come from first-order perturbation theory around the detached Ritz pairs, as zero-valued graph terms: energies by Hellmann-Feynman on the kk low Ritz vectors (level mean at degeneracies, as eigh_gauge), eigenvectors from the couplings inside that cluster plus a reduced-resolvent solve in its complement, at the (orientation, field) points that enter the spectrum. Probe: 6.6e-10 and 2.9e-9 relative to the full-basis gradient, reverse and forward mode. Jacobians (e_sigma, zeta, Racah B, k) of a d^7 test case, scaled error against the full basis: absorption 1.6e-1 -> 1.7e-9, field derivative 6.5e-2 -> 3.5e-9, Lorentzian at 4 K 2.8e-2 -> 1.7e-9. The module docstring’s error estimate (O((Ritz error/gap)^(1/2)), measured on d^8 only) was wrong and is replaced.

  • Spectra are unchanged: bit-identical with and without parameters on the graph, and to 0.9.29. Runs without graph inputs skip the extra work (same cost); with graph inputs the probe sweep (igloo 6, 781 fields) takes 6.1 s against 1.5 s before (wrong) and 55 s with subspace=False. fdmr and subspace=False are not affected.

Tests#

  • test_lft_ddnpow.py: test_d7_ritz_gradients_match_full_basis (absorption, field derivative, Lorentzian 4 K; bound 1e-7), test_d7_ritz_gradients_vs_central_differences (Richardson, bound 1e-5; central differences of this spectrum bottom out at ~1e-6) and test_d7_ritz_values_identical_on_and_off_graph (bit identity, reverse = forward mode). The first two fail on 0.9.29.

[0.9.29] — 2026-11-13#

Fixed#

  • Zero hyperfine principal values give the exact A -> 0 limit in all three perturbation modules (B65, B79). The second-order invariant A2 = det(A) u’·inv(A)·k (Iwasaki 1974) needs only det(A)·inv(A) = adj(A), a polynomial in the entries of A. resfields_perturb, resfields_perturb_batch, resfreqs_perturb and endorfrq_perturb now use the adjugate (new private torchspin/_adjugate.py, _adjugate3) instead of torch.linalg.inv and torch.linalg.det, so a zero principal value, two zeros or a singular full Sys.A is defined, continuous and differentiable. This replaces the ValueError of 0.9.23 (#69, resfreqs_perturb/endorfrq_perturb) and the one of 0.9.14 (#63, B65, resfields_perturb); before that, resfields_perturb(_batch) raised torch’s raw LinAlgError (“linalg.inv: The diagonal element 1 is zero”) for Sys.A = [0 5 10]. Numbers (S = 1/2, g = [2 2.05 2.1], 1H A = [5 8 0] MHz, 340 mT, φ = 0.3, θ = 0.7): endorfrq_perturb first line 15.593819600 MHz, the same as A_z = 1e-9 MHz to 1e-9 MHz (0.9.22 and earlier: 15.59326 from a zero matrix for inv(A); 0.9.23: ValueError). Over 1H, 14N and 63Cu, one zero, two zeros and a rotated rank-2 full A, S = 1/2 and 1, |f(0) − f(eps)| ≤ 4.6e-4·eps mT for the fields, 1.3e-5·eps GHz for resfreqs_perturb and 0.98·eps MHz for endorfrq_perturb (eps in MHz, 1e-6 and 1e-8). In the EPR modules k = A·u/|A·u|, so A2 = det(A)/|A·u|, which vanishes for a singular A and enters 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 at S = 1/2. Gradients of resfields_perturb(_batch) with respect to A at a zero principal value match central differences to 3e-10 (S = 1, 63Cu). With an AFrame, R·diag(50, 30, 0)·R’ is singular only to roundoff and inv did not raise, but the det·inv gradient was wrong (dB/dA_z 5.8e-4 against 3.9e-5 mT/MHz from finite differences). Results for non-singular A change by roundoff only: a sweep of 60 random systems (1-3 nuclei of 1H/2H/13C/14N/55Mn/63Cu, diagonal A with frames and full non-symmetric A, S = 1/2, 1, 3/2 with tilted D, orders 1 and 2, 4 orientations, all four functions; 88176 values) is bit-identical except 24 endorfrq_perturb values, max relative change 4.8e-16; A2 itself, on 20000 random matrices, changes by at most 2.7e-13 relative.

  • Deliberate deviation from EasySpin. EasySpin’s 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; endorfrq_perturb.m has no check, and inv(A) (.m:176) warns and the frequencies are NaN. torchspin returns the A -> 0 limit in all three. Matrix diagonalization agrees at A = 0 to the usual perturbation accuracy (S = 1/2, the systems above: within 1.6·Amax³/E0², E0 = 9700 MHz). See KNOWN_LIMITATIONS.md.

Removed#

  • _check_nonzero_hyperfine in resfreqs_perturb.py and endorfrq_perturb.py (0.9.23) and its ValueError.

Tests#

  • New torchspin/tests/test_zero_hyperfine_limit.py (118 tests; 84 fail before this change): continuity at eps = 1e-6 and 1e-8 for the four functions (1H, 14N, 63Cu; one zero with and without a frame, two zeros, rank-2 full A; S = 1/2 and 1); agreement with resfields, resfreqs_matrix and endorfrq at A = 0; gradients at a zero principal value against central differences; _adjugate3 against det·inv, at singular matrices and with gradcheck.

  • test_perturb_zero_hyperfine.py: the five tests that asserted the 0.9.23 ValueError now check the A -> 0 limit (A_z = 1e-9) instead; the first-order and non-zero-A reference tests are unchanged (non-zero A still matches the stored values to rtol 1e-13).

[0.9.28] — 2026-11-12#

Fixed#

  • Field sweeps whose range cuts transitions at some orientations were far from converged (B88, B75, B91). The matrix resonance search covers Exp.Range only, so such transitions have knots without a resonance (NaN). pepper and pepper_autograd then interpolated the positions of every transition linearly, as EasySpin does (pepper.m:701, 763-772; 0.9.4, B31), which reproduces the coarse-grid facets, and dropped every triangle with a NaN vertex, so triangles crossing the range ends were lost even without interpolation (B75; EasySpin too). Now 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, so looping transitions keep consistent occurrence indices) and replaced wholesale (pepper._research_missing_knots); a pair’s new resonances are kept only if fewer are missing and no orientation loses one, and pairs that improved but are still incomplete are searched again over a doubled window, up to ± 4 W; projection stays on Exp.Range and clips their out-of-range vertices. Only slots that still miss knots are interpolated linearly (L1; L3 on axial grids), all others keep the global cubic G3; the global switch in pepper._interp_slot and pepper_autograd._interp_slots_t is gone. Against converged references (no interpolation, GridSize [181 1], wide sweep cropped; tests/data/ref_missing_knots.npz), 1 − cosine / max|dev| relative to the maximum on the interior of the range (ends ± 5 FWHM dropped), pepper and pepper_autograd alike:

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

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

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

    • B75: a narrow sweep without interpolation (Cu, [31 1]) vs the crop of a wide one at the same grid 0.044 → 2.6e-11 (stick spectrum, whole range but the first bin: 0.059 → 1.6e-11).

    With the range-edge padding of 0.9.6 (Options.PaddingMultiplier) the full-range numbers equal the interior ones: Cu [19 4] cosine 0.7987 → 0.9475, Cu [181 1] 0.99569 → 1.000000 (max dev 0.18 → 3e-4), 91Zr 0.94289 → 0.99987, S = 5/2 0.95664 → 0.99990. pepper and pepper_autograd agree to 1.3e-11 (B91); gradients through the re-searched slots (d/dA, d/dg, d/dlw) agree with converged central differences to 1e-6 / 4e-8 / 1e-8. Spectra in which every level pair resonates equally often at every orientation take the old path unchanged (29-spectrum sweep over 9 grid symmetries, strain, perturbation theory, frequency sweeps, pepper and pepper_autograd: bit-identical). Frequency sweeps are not affected (resfreqs_batch has no window). Cost: one extra search of the partly missing pairs per doubling (S = 5/2 [19 4] 0.04 → 0.2 s). Deliberate deviation from EasySpin, which keeps the NaNs, interpolates every slot linearly and drops range-edge triangles: on its references whose ranges cut transitions 1 − cosine up to 0.06 (Oh grid 0.54), each farther from the converged reference than torchspin (Oh 0.579 → 2.0e-3; S = 5/2 parallel mode, whose looping pairs still miss knots, 5.1e-3 → 7.0e-4). See KNOWN_LIMITATIONS § Field sweeps whose range cuts transitions.

Tests#

  • test_missing_knots.py (new): the three cases against converged references (interior bounds at measured × 1.05), narrow vs wide-crop at the same grid (B75 with and without interpolation, stick and HStrain), pepper vs pepper_autograd, gradients vs central differences, the re-search window and per-slot interpolation, and that a range holding every resonance never re-searches. References tests/data/ref_missing_knots.npz from tests/data/generate_missing_knots_refs.py (torchspin, no interpolation, wide sweep; checked to need no re-search).

  • test_pepper_nanlinear_matlab_validation.py (4 cases), test_interp_nan_edges_matlab_validation.py (7 spectra), test_sphgrid_maxphi_matlab_validation.py (4 cases) and test_pepper_parallel_matlab_validation.py (S52_parallel): the EasySpin comparisons of spectra whose ranges cut transitions are strict xfails with the measured deviation; each case is now checked against a converged reference (bounds measured × 1.05), which it is closer to than the EasySpin-identical 0.9.27 spectrum. test_interp_nan_edges_...::test_autograd_vs_central_differences[b50_D]: d/dE at E = 0 is 0 by x ↔ y symmetry (AD −1.8e-14, CD −8e-11, ≤ 3.3e-10 of d/dD) and is now asserted to be 0; 0.9.27 gave −1.07e-3 in both because its missing-knot interpolation broke the symmetry.

  • Tests merged in after #53 (range padding, 0.9.6) and #72 (AStrain mI model, 0.9.25): the 63Cu AStrain case of test_astrain_mi_model.py cuts transitions at 290 mT, so its EasySpin comparison is a strict xfail (cosine h0 0.997448, h1 0.946325) and test_cu63_vs_converged_reference checks it against a wide-sweep no-interpolation reference (1 − cos 4.97e-4 / 1.35e-2; EasySpin 1.87e-3 / 3.75e-2). test_voigt_field_sweep_not_padded became test_voigt_field_sweep_padded_since_b88: with clipped range-end triangles the padding applies (cosine vs a wide sweep 0.9946 padded, 0.908 unpadded, 0.857 EasySpin). The B48 gradient test runs with PaddingMultiplier=0 (padding copies the clipped end bins 225 times and limits central differences to ~1e-6; without it they converge to 1e-8).

[0.9.27] — 2026-11-12#

Fixed#

  • Exp.ModAmp gradients are correct on every torch version; at Harmonic 2 they were silently wrong on torch <= 2.14 (B92). The pseudo-modulation kernel (dataproc.fieldmod_t, used by pepper_autograd and pepper with grad inputs) is a Bessel function of ModAmp, and torch.special.bessel_j0/bessel_j1 have no derivative before torch 2.15: their outputs left the graph without an error. A grad ModAmp therefore raised “does not require grad” at Harmonic 1 on torch <= 2.14, and at Harmonic 2 the upward recurrence J2 = 2/x J1 - J0 kept only its 2/x path: S = 1/2, g = [2.0 2.05 2.1], lw 0.5, ModAmp 0.5, loss sum(y^2): autograd -90.59 against central differences 10.004 on torch 2.10 and 2.14.1 (CI’s py3.10 torch). On torch 2.15 the gradient was already right. dataproc._bessel_j01 now supplies the backward itself (J0’ = -J1, J1’ = J0 - J1/x, 1/2 at x = 0) on every version; the forward values are torch’s, so spectra are unchanged (bit-identical). Gradients against central differences: rel 1e-9..1e-7 for Harmonic 1 and 2, ModAmp below the bin width, overmodulated, powder and Exp.Orientations, on torch 2.10, 2.14.1 and 2.15. A grad ModAmp <= 0 now raises ValueError (ModAmp = 0 switches off field modulation; the spectrum is not continuous there). Only ModAmp was affected: every other float-read input raises on all three torch versions, and torch.special is used nowhere else.

[0.9.26] — 2026-11-12#

Fixed#

  • Gradients on systems with an accidental grid symmetry (B1). The automatic grid was chosen by hamsymm at the current values, outside the autograd graph, so a symmetry that the differentiated perturbation breaks was used anyway: an axial g/A given as independent numbers got 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], converged central differences -5.7189e6 for g_x and g_y; now [-5.7189e6, -5.7189e6, -2.8021e6]), an isotropic g given as three numbers the O3 grid ([4.57e6, 4.57e6, -4.57e6] vs ~1.598e6 each), an axial g with a rhombic A rotated about z D2h (now C2h), differentiated Euler angles a grid whose frame does not move with them (now Ci). salt likewise (14N ENDOR: dA = [-0.217, 0, 0.053], now -0.1079 for x and y, as the central differences).

Changed#

  • The automatic grid follows the differentiated parameterization (B1). New torchspin.hamsymm.grid_symmetry, used by pepper, pepper_autograd, salt, saffron, saffron_thyme, orisel, nucfrq2d and the broadband autograd model. Without grad on a symmetry input nothing changes (bit-identical, no extra cost). With grad, the autograd leaves get a generic perturbation and each input moves along J @ dp (double-backward JVP on the existing graph; field-level perturbation if double backward is unsupported); two independent perturbations must agree on group and frame, else Ci. A scalar g keeps O3 and [g_perp, g_perp, g_par] from two leaves keeps Dinfh; an axial g given as three independent numbers now uses D2h (0.33 s vs 0.016 s forward + backward for the Cu(II) case), and its spectrum differs from the forward-only one by the grid discretization error (0.1 % there; up to ~17 % for an isotropic g given as three numbers, whose lines the projection bins). Set Options.GridSymmetry explicitly to compare the two. In test_pepper_autograd.py two pepper == pepper_autograd checks had a grad g given as three numbers (axial values): test_perturbation_order_follows_method now names GridSymmetry='D2h' on both sides; the isotopologue check builds g from two leaves ([g_x, g_perp, g_perp]), which keeps the automatic Dinfh grid about x (no explicit GridSymmetry reproduces that frame). Tolerances unchanged.

[0.9.25] — 2026-11-12#

Fixed#

  • AStrain widths use EasySpin’s effective nuclear mI (B68). EasySpin (resfields.m 766-788) labels every level once with the mI of the first nucleus: eigenvectors of H0 - mean(Exp.Range)*muz with the field along the molecular z axis, levels sorted by energy, mI = <Iz>; a transition uses the mean over its two levels at every orientation (resfields.m 1297-1306). torchspin took <Iz> at each orientation’s own resonance field (strainwidth.py:201-214, 256 on 0.9.20), which vanishes for the field perpendicular to a large A, so perpendicular lines got no AStrain width: 14N, A = [20 20 90] MHz, AStrain 10 MHz, φ = 0.3, θ = 90°: 0.000 mT against EasySpin’s 0.357 mT (an explicit ensemble with A sampled gives 0.32-0.38 mT). New strainwidth.astrain_level_mI; resfields_batch computes it once per call and passes it to compute_strain_widths_batch(..., mI_levels=...). Differentiable (degeneracy-safe eigendecomposition). Every field-sweep result with AStrain changes (pepper, pepper_autograd, Opt.Method='hybrid', esfit, resfields, resfields_batch): spectra vs EasySpin (Harmonic 1, cosine / amplitude, before → after) 14N 0.923 / 1.46 → 0.999999 / 0.9995; 1H 0.9987 / 1.024 → 1.000000 / 1.0001; 63Cu A = [50 50 500], AStrain [10 10 50] 0.972 / 0.945 → 0.999996 / 1.0000; 14N + gStrain 0.920 / 0.616 → 1.000000 / 1.0004; the same with gAStrainCorr = -1 0.926 / 1.027 → 1.000000 / 0.9989. Per-transition widths agree with EasySpin’s resfields to 1e-5 relative. Frequency sweeps are unchanged (EasySpin’s resfreqs_matrix uses a different AStrain model, without mI).

  • Zero strain widths give finite gradients. compute_strain_widths_batch took sqrt(lw2) with an infinite derivative at lw2 = 0 (e.g. HStrain = [h h 0] along z; strainwidth.py:271 on 0.9.20), and pepper_autograd’s facet smoothing computed gam = 1/sqrt(c1 Λ² + c2 Λ⁴) = inf for a facet with zero mean width (Λ = 0; pepper_autograd.py:685), then 0 * inf: NaN spectra or gradients. Both now use a double torch.where; the value at zero width is unchanged (gam = 0, as pepper’s NumPy path and EasySpin).

Changed#

  • compute_strain_widths_batch raises ValueError for AStrain without the new mI_levels argument (callers outside the package: pass astrain_level_mI(sys, H0, muz, mean(Range))); without AStrain nothing changes. compute_strain_widths (single orientation) takes optional Range and mI_levels; without either it labels the levels at B0.

Tests#

  • New torchspin/tests/test_astrain_mi_model.py (51 tests; 38 fail on 0.9.20, 2 strict xfail) with EasySpin references tests/data/ref_astrain_mi.mat (generate_astrain_mi_refs.m): per-orientation widths incl. θ = 90° (6 systems, one with a tilted AFrame), single-orientation compute_strain_widths, pepper and pepper_autograd spectra (Harmonic 0 and 1, 5 systems), zero-width facets, and gradients in AStrain, A and gStrain vs converged central differences.

  • Tightened: test_pepper_matlab_validation_ext2.py pt_broadenings_matrix / pt_broadenings_perturb2 (cosine 0.9888 → 1.000000; threshold 0.985 → 0.99999, amplitude 2 % → 0.2 %); test_strain_validation.py gstrain_astrain (RMS 0.0308 → 0.0002; tolerance 0.10 → 0.001, peak ratio 20 % → 0.2 %). test_resfields_single_autograd.py::test_compute_strain_widths_equals_batch passes the mI labels to the batch call (same tolerance).

[0.9.24] — 2026-11-12#

Fixed#

  • Strains are part of the automatic grid symmetry (B82, deliberate deviation from EasySpin). hamsymm ignored HStrain, gStrain, AStrain and DStrain, so an axial g with a rhombic strain got the Dinfh grid, one meridian: S = 1/2, g = [2.05 2.05 2.15], lw 0.3, HStrain = [200 20 20] MHz (or gStrain = [0.02 0.002 0.002]), 9.5 GHz, GridSize [31 4] was 79 % (76 %) of the maximum off the D2h spectrum, while D2h [31 4] and [91 4] agree to 0.9 % (0.4 %). EasySpin’s hamsymm has the same gap (78.7 % / 76.0 % in MATLAB, tests/data/ref_hamsymm_strain.mat). Each strain now enters as one more tensor in its own frame (HStrain molecular, gStrain g, AStrain A, DStrain D), in both the geometric and the eigenvalue analysis, for every consumer of the automatic symmetry; strain-free systems keep EasySpin’s group and frame (bit-identical spectra). Two EasySpin DStrain references (multidstrain, multidstrain_31) are now strict xfails: EasySpin is 5.9 % off a fine D2h grid there, torchspin 0.2 % / 0.07 %. orisel’s default grid for a tilted g with molecular-frame HStrain is Ci instead of EasySpin’s D2h (the EasySpin weight check in test_orisel.py runs that case on EasySpin’s own orientations).

  • saffron, saffron_thyme, nucfrq2d and the broadband autograd model used hamsymm’s grid in the wrong frame (B83). They dropped the symmetry frame (pepper rotates the grid into the molecular frame) and replaced a hamsymm error by a silent C1 grid. A tilted system now gives the result of the untilted one (saffron 3pESEEM: was 1.9 % off; saffron_thyme 2pESEEM 111 %; nucfrq2d missed part of the frequency range; broadband, axial g along x vs z: 78 %); hamsymm errors propagate. New torchspin.hamsymm.grid_angles_to_molecular.

  • gStrain with a g given as Ham110/Ham112 (0.9.13, B56) in the strain tensor of the grid symmetry. SpinSystem sets g = 0 for such systems, and the gStrain tensor divided by it (inf, a wrong grid; with a gFrame eigh failed before the strain widths’ own check). It now uses the g-equivalent principal values (ham_linear_g, diagonal in the g frame) that the strain widths use. With a gFrame the Ham and the g system both get Ci, in different frames (spectra 1.0e-3 of the maximum apart; on the same Ci grid 7.8e-14). Against EasySpin’s g spectrum (EasySpin’s grid ignores the strain) that case is a strict xfail (cosine 0.997209); against a converged C1 [91 1] grid 1 - cos is 1.07e-7 (EasySpin 2.78e-3).

[0.9.23] — 2026-11-12#

Fixed#

  • resfreqs_perturb and endorfrq_perturb raise a clear ValueError for a zero hyperfine principal value at second order (B79). The second-order hyperfine terms use inv(A); torchspin caught the failing torch.linalg.inv with except Exception and used a zero matrix, so the result was silently wrong. endorfrq_perturb (S = 1/2, g = [2 2.05 2.1], 1H A = [5 8 0] MHz, 340 mT) gave 15.59326 MHz for the first line; the A_z -> 0 limit is 15.59382 MHz. The message is EasySpin’s (resfreqs_perturb.m and resfields_perturb.m:120-127): “All hyperfine coupling constants must be non-zero”, with the nucleus named. A singular full A raises the same. EasySpin endorfrq_perturb.m has no check and returns NaN; torchspin raises there too. First order needs no inverse and still runs. Results with non-zero A are bit-identical. Same check as resfields_perturb (B65). See KNOWN_LIMITATIONS.md. Tests in test_perturb_zero_hyperfine.py.

[0.9.22] — 2026-11-12#

Fixed#

  • pepper_autograd and salt with no resonance in range stay on the autograd graph (B77). When no line of a system fell inside Exp.Range, pepper_autograd returned a detached zero spectrum (the powder early return, pepper_autograd.py:621; the Exp.Orientations path built its zeros from the orientation weights only), and a component without lines in range was not used in the graph of a multi-component sum. torch.autograd.grad then raised (“does not require grad” or “appears to not have been used in the graph”), so a fit whose lines drifted out of the window crashed; a grad Sys.lw was lost as well, because the early return skipped the convolution. salt’s fixed-field mode did the same with no ENDOR line in freq_range. New torchspin.autograd.connect_inputs subtracts 0.0 * sum((t - t.detach()).sum()) over the inputs each function keeps on the graph (pepper_autograd: g, A, D, Q, ee, nn, sigma, lw/lwpp, HStrain, HStrainL, gStrain, AStrain, gAStrainCorr, weight, Exp.mwFreq, Exp.Temperature, Exp.Orientations/OrientationWeights; salt: g, A, Q, sigma, HStrain, lw_mhz). Such an input now gets an exact zero gradient of its own shape, pepper (which routes grad inputs to pepper_autograd) included. The term is exactly +0.0, so every spectrum value, -0.0 included, and every in-range gradient are bit-identical to 0.9.0; without grad inputs nothing is added (about 4 µs per call). Inputs the forward path reads as floats (Euler frames, gnscale, DStrain, Exp.ModAmp, Exp.Range, salt’s Exp.Field/mwFreq/ExciteWidth) are not connected: they still raise instead of getting a silent zero gradient. Frequency sweeps still raise NotImplementedError. With 0.9.17 (B3, frame angles on the graph) and 0.9.27 (B92, Exp.ModAmp gradients) the spin-system Euler frames (gFrame, AFrame, DFrame, QFrame, eeFrame, nnFrame, sigmaFrame; pepper_autograd and salt) and Exp.ModAmp (pepper_autograd) are connected as well.

[0.9.21] — 2026-11-12#

Fixed#

  • C1 powder grids interpolated the lower hemisphere mirrored (B74). sphgrid builds the lower hemisphere of the C1 grid from the upper knots in reverse order (as EasySpin’s sphgrid.m:320-325 does), so each lower θ row is stored with φ decreasing. The rectify step of the grid interpolation (pepper._interp_grid, port of private/gridinterp.m:204-224) read those rows as φ increasing, so a lower knot at φ took the value from −φ − Δφ (mirrored and shifted by one coarse φ step Δφ of that row); through the global bicubic spline (G3) this also disturbed the upper hemisphere. Each lower row is now reversed at the rectify step; the sphgrid order is unchanged (grid_triangulation depends on it). This reaches pepper, pepper_autograd and salt whenever a C1 grid is interpolated (GridSize(2) > 1): by default for low-symmetry systems with Sys.tdm (photoselection), or with Options.GridSymmetry='C1'. Only C1 has lower rows; the other grids are unchanged bit for bit. Interpolating f = 12x + 15y + 8z + 4xy − 3yz + 2xz (mT) from C1 [19 4]: max error 32.5 → 0.52 mT (linear, L1) and 35.7 → 0.064 mT (cubic, G3). Spectra on C1 [19 4] against the same fine knots without interpolation (C1 [73 1]), max deviation of the maximum: Cu(II) with non-coaxial g and A 0.342 → 0.0075 (a Ci grid of the same size: 0.0078); a photoselection triplet (default grid C1) 0.069 → 0.0018; salt 1H ENDOR 0.021 → 0.00054. The rhombic-invariance test (C1 vs D2h, [20 4]) 2.4e-3 → 3.6e-4; its C1 tolerance is tightened from 2.5e-3 to 1e-3. Deliberate deviation from EasySpin, which has the same defect (gridinterp.m:211/213/217/219 read y(idx:idx+len-1)); torchspin now follows the exact, uninterpolated result (KNOWN_LIMITATIONS.md). The EasySpin-reference cases on interpolated C1 grids (9 photoselection cases, fullsphere_C1) therefore move away from EasySpin by up to 9e-3 of the maximum (cosine ≥ 0.999989, amplitude within 0.85 %); against the same fine grid without interpolation fullsphere_C1 goes from 9.0e-3 to 6.0e-4. Tests: torchspin/tests/test_c1_lower_rows.py.

Tests#

  • Those 10 EasySpin-reference cases on interpolated C1 grids are no longer compared with EasySpin (a known-wrong reference there) but with torchspin on the same fine knots without interpolation, at bounds just above the measured deviations (3.7e-4 to 4.3e-3 of the maximum). The check that the other open-φ grids (Ci, C2h, C4h) are unchanged uses error bounds against exact symmetric test functions and the NaN pattern instead of output hashes.

[0.9.20] — 2026-11-12#

Fixed#

  • Single-orientation resfields and compute_strain_widths are differentiable (B76). Both had their own per-orientation code with a Python-float Brent search and .item() (resfields.py:117-118, 124, 148, 174-184, 228; strainwidth.py:168, 552, 608, 665, 669), so fields, intensities and widths carried no gradient. For S = 1 with DStrain + HStrain the widths kept a partial graph through the eigenvectors and returned a wrong gradient without warning (dW/dg0: +0.771 against -0.807 from finite differences). They are now thin wrappers over resfields_batch and compute_strain_widths_batch with one orientation; public signatures and return types are unchanged. Gradients with respect to g, A, D, J, gStrain, AStrain, HStrain, the angles and B0 match 4-point central differences to 1e-6 relative above their round-off floor.

  • gStrain with a full g matrix raises in the single-orientation path (B5). compute_strain_widths read Sys.g[0, :] (the first row of the full matrix) and returned an infinite width (strainwidth.py:619 on 0.9.13). It now raises ValueError (“gStrain and AStrain are not supported when full g matrices are given!”), as resfields_batch, pepper and EasySpin do.

  • Looping transitions return all their resonances in resfields (single orientation). The two-point bracket at the range ends found at most one resonance per level pair. Example: S = 1, D = 10 GHz, 9.5 GHz, θ = 0.3, 5-1000 mT: the lowest pair now gives both lines (18.8 and 622.8 mT); before, only 18.8 mT.

Changed#

  • resfields (single orientation): resonance fields move by up to 2e-6 mT (the old Brent tolerance was 1e-5 mT; S = 1/2 6e-14 mT), intensities and widths by ≤ 3e-8 relative. Exp.mwMode is now honored (it was ignored), and Options.Threshold is applied to |I| relative to the largest |I|, as in resfields_batch. With strains but no resonance in range the widths are an empty tensor instead of None.

  • strainwidth.compute_strain_widths: the dtype argument is accepted but unused (the arithmetic follows H0). The per-orientation helpers _compute_hstrain_width_squared, _compute_gstrain_astrain_width_squared, _compute_dstrain_width_squared, _orientation_vector and resfields._brent/_nuc_states are removed.

Tests#

  • New torchspin/tests/test_resfields_single_autograd.py (44 tests; 42 fail on 0.9.13).

[0.9.19] — 2026-11-12#

Fixed#

  • levelsplot(..., mwFreq=...) draws the resonance transitions again; errors in the resonance computation propagate (B78). levelsplot.py:167-176 called resfields(sys, exp, dict), but resfields takes (H0, mux, muy, muz, phi, theta, exp, opt); the TypeError was swallowed by a bare except Exception: pass (levelsplot.py:244), so no transition line, stick spectrum or “no EPR resonances” note was ever drawn. Now as EasySpin levelsplot.m:244-272: the resonances of the one orientation (resfields_batch, Threshold 0, lab axes erot([phi, theta, chi]) as EasySpin’s Exp.SampleFrame = [-chi -theta -phi], B1 along lab x), intensities without the dB/dE factor (Freq2Field 0), relative to the largest, lines below PlotThreshold skipped, each drawn between its two levels at the resonance field and colored between the allowed and forbidden colors by relative intensity. Against EasySpin’s own levelsplot figure (5 cases, S = 1/2 with 14N, S = 1, S = 3/2): same lines, fields within 2.9e-5 mT (torchspin’s are exact roots; EasySpin’s are spline-model roots), relative intensities within 1.9e-4 (EasySpin interpolates eigenvectors between knots; against its resfields with RediagLimit 2 the difference is 6e-9). The try/except is gone. The level diagram itself is unchanged. EasySpin references: tests/data/ref_levelsplot.mat.

[0.9.18] — 2026-11-11#

Fixed#

  • pepper_autograd no longer returns an all-zero spectrum for isotropic systems (B66). On the O3 grid (automatic for isotropic g and A without ZFS, or GridSymmetry='O3') it sent the single orientation to the triangle projection, whose O3 triangulation is empty, and returned zeros with zero gradient. Because pepper routes to pepper_autograd when an input requires grad, pepper with an isotropic g tensor that requires grad returned zeros as well, so a fit of any isotropic system saw no spectrum and no gradient. S = 1/2, g = 2.0, lw [1 0], 9.5 GHz, Range [330 350]: 0.0 before, 738.23 now (pepper 738.23). pepper_autograd now takes pepper’s O3 branch: every line gets an exact template at its position (Gaussian for Sys.lw(1) or a strain width, Lorentzian for Sys.lw(2) alone, the rest convolved), with the same resonance search (matrix or perturbation, Opt.Transitions, QuadraticZeeman), Temperature, mwMode, HStrain/HStrainL and ModAmp. It equals pepper to ≤ 5e-11 on 55 isotropic cases and EasySpin to cosine > 0.999995 and amplitude 1 ± 1e-5 (tests/data/ref_pepper_isotropic.mat); gradients w.r.t. g, A, lw and HStrain match central differences of pepper. A powder grid that yields no usable facets now raises RuntimeError instead of returning zeros. pepper itself is unchanged.

[0.9.17] — 2026-11-11#

Fixed#

  • Euler frame angles stay on the autograd graph (B3). A gFrame, AFrame, DFrame, QFrame, eeFrame, nnFrame, sigmaFrame or BFrame tensor with requires_grad=True used to get no gradient, without a warning: every call site read the angles with .tolist() or float() before erot. erot now builds the matrix from torch operations when an angle requires grad (same formula; otherwise the float path as before), and the angles are passed as tensors in ham_ez, ham_hf, ham_zf (D and the Stevens BFrame rotation, now a torch Wigner D), ham_nq, ham_ee, ham_nn, ham_nz, strainwidth (gStrain, AStrain and DStrain frames), resfields_perturb, resfreqs_perturb, endorfrq_perturb, resfields_hybrid and salt. The zero-angle check that skips the rotation is made on detached values and does not skip a frame that requires grad. With a nonzero BFrame the Stevens B coefficients were detached too; they are not any more. pepper routes a system whose only grad tensor is a frame to pepper_autograd, saffron switches to its differentiable time-domain accumulation for frames as it does for tensors, and salt’s field-swept mode raises NotImplementedError for grad frames as it does for g, A, D, Q and ee. Gradients equal central differences (ham, levels, batched strain widths: 1e-8; pepper_autograd powder, perturbation and Exp.Orientations, salt fixed-field, saffron: 1e-5), also at beta = 0 and beta = pi.

  • hamsymm with a frame that requires grad. The eigenvalue path (full tensors, Stevens terms) called .numpy() on the frame and raised RuntimeError. hamsymm now runs without a graph: the point group and grid frame are a discrete decision on the detached values.

  • Values without grad are unchanged: 466 arrays (ham, H0, muz for 150 random systems with every frame type, 16 pepper spectra with strains) and 30 outputs of ham, pepper (matrix and perturb), strain widths, salt and saffron with tilted frames were bit-identical to 0.9.0. The test suite checks the property within the build: with a frame that requires grad the same 30 configurations give the float path’s values (bit-identical; ham with BFrame within 4 ulp, pepper_autograd with a grad gFrame within 1e-11), and a tensor frame without grad is bit-identical to a list.

[0.9.16] — 2026-11-11#

Fixed#

  • pepper_autograd with Exp.Orientations now honors Options.QuadraticZeeman and Options.Transitions, as pepper does (B64). Its orientation branch called resfields_batch without the higher-order Zeeman operators and without the user’s level pairs, so the spectrum silently equaled the one without the option: for S = 1, D = [300 30] MHz with Sys.Ham220/Ham222 and QuadraticZeeman=True it differed from pepper by 1.04 (one orientation) and 1.03 (five) of the maximum, and with Transitions=[[1,2]] by 1.00 and 0.39. Both now equal pepper to ≤ 5e-14. Method='perturb' with either option now raises on this path too, as in pepper and on the powder path. The powder path, and every spectrum without these options, is unchanged. EasySpin references: tests/data/ref_pepper_orientations_qz.mat (crystal sums as the exact χ average; 2.5e-3 with Ham2xx, which is EasySpin’s linear-moment dB/dE, and 1.9e-4 for the level-pair selection).

[0.9.15] — 2026-11-11#

Fixed#

  • SpinSystem input shapes follow EasySpin’s validatespinsys.m (B62, B63). Many shapes were kept unnormalized by the constructor and failed later in pepper with an IndexError or RuntimeError (some ran silently with the wrong tensor), and a 1-D gStrain, HStrain or AStrain of one or two values raised although EasySpin expands them. A 1-D list is read as a MATLAB row vector. Now:

    • Expanded as in EasySpin (were late errors or ValueError): g = [g_perp, g_par] for one electron spin and (nElectrons, 2) axial rows; one g per electron in any shape; A as (nNuclei, nElectrons) isotropic (e.g. [[10.]] for one nucleus, [A1, A2] for one nucleus and two electrons), (nNuclei, 2*nElectrons) axial (e.g. [A_perp, A_par]) and a 1-D 3*nElectrons row for one nucleus; a scalar A_; a 1x6 AFrame row; empty gFrame, DFrame, AFrame (zeros); ee as an (nPairs, 1) column of isotropic values; lw/lwpp as [[G, L]]; gStrain rows of 1 or 2 values ([x] -> [x x x], [x y] -> [x x y], validatespinsys.m:822-823); HStrain/AStrain with 1, 2 or 3 values in any shape; empty gStrain, HStrain, AStrain, DStrain (no strain). Each gives the same tensor and a bit-identical spectrum as the explicit form, and against EasySpin (ref_spinsystem_shapes.mat, 5 cases in the short form) cosine >= 0.9999990, amplitude within 0.0009.

    • ValueError at construction, as EasySpin errors: g that is not one of those forms (e.g. [2.0] or [[2.0]] for two electrons, a 6-vector, (3, 3) for two electrons); gFrame, DFrame, QFrame, eeFrame, AFrame that are not one row per tensor (e.g. [0.1]); D_ without one [D, E/D] pair per electron (e.g. [300.], was a RuntimeError); A inconsistent with the numbers of nuclei and electrons (e.g. [10.] for two nuclei, [10.] or [Ax, Ay, Az] for two electrons); Q that does not give (nNuclei, 3); ee that does not give (nPairs, 3) or (3*nPairs, 3); lw/lwpp with 0 or 3+ values (a third value was ignored); gStrain without one row per electron; HStrain/AStrain with 4+ values; and A, AFrame, Q or a nonzero QFrame without Nucs (were silently ignored).

    • Unchanged: every input that worked before, including torchspin’s own shorthands (scalar g, A, gStrain, DStrain; [x, y, z] for every electron, nucleus or pair), except the flat D below. Gradients flow through the expanded forms.

Changed#

  • A flat D of 2 or 3 values for two or more electron spins raises ValueError (B61; behavior change, deliberate deviation from EasySpin). SpinSystem(S=[1, 1], D=[a, b]) was read as one [D, E] shared by both electrons and S=[1, 1, 1], D=[a, b, c] as shared principal values, while EasySpin reads both as one D value per electron (numel(Sys.D) == nElectrons, validatespinsys.m:208-210). The same lists with a different number of electrons (e.g. [D, E] for three or four) were also read as shared. Neither reading is adopted: the error asks for the explicit form, one row per electron spin (D=[[D1, E1], [D2, E2]], D=[[Dxx, Dyy, Dzz], ...], D=[[D1], [D2]] or D_). The old meaning is D=[[D, E]] * nElectrons. Unchanged: a scalar D (same D, E = 0 for every electron, as EasySpin), a flat list of one D per electron for four or more electron spins, [D], [D, E] and [Dxx, Dyy, Dzz] for one electron spin, and every 2-D form. D_ has no shared shorthand and is unchanged. No test, example or document in the repository used the ambiguous form.

[0.9.14] — 2026-11-11#

Fixed#

  • resfields_perturb raises a clear ValueError for a zero hyperfine principal value at second order (B65). The second-order terms invert A; Sys.A = [0 5 10] raised torch’s raw LinAlgError from inv. As EasySpin (resfields_perturb.m:120-127) the message is now “All hyperfine coupling constants must be non-zero” (a singular full A too). First order still runs (EasySpin rejects it at every order). Test in test_resfields_perturb.py. Superseded in 0.9.29: the adjugate gives the A -> 0 limit.

  • ENDOR transition selection as EasySpin endorfrq, in one place for endorfrq and every salt matrix path (B57/B41, B40, B59). EasySpin selects the level pairs once (endorfrq.m:258-341): on the coarse grid sphgrid(Opt.TPSGridSymm, Opt.TPSGridSize) ('D2h', 4) it sums the nuclear-moment rates with the grid weights, drops pairs whose frequency never enters the range, always removes electronic pairs, and keeps a pair if its rate is > Threshold * max. Enhancement changes intensities only. torchspin now does the same (endorfrq._endor_tps_select, run without autograd; positions and intensities keep their gradients), so the selection no longer depends on GridSize or on the orientation.

    • salt, fixed field (B57): a pair was kept if it was strong at any orientation of the simulation grid. For 14N+1H with Enhancement (endor_enhancement_refs.mat) the zero-quantum pairs (8,9), (10,11) at an anticrossing near 0 MHz passed (4.3e-4 > 1e-4; EasySpin’s summed rates 1.3e-9, 2.1e-9): 23 pairs instead of EasySpin’s 16, and a spike at 0 MHz. Residual vs EasySpin 4.6e-3 → 1.8e-12 (without Enhancement 3.4e-6 → 1.9e-12). The 14N, 1H-enhanced and 14N+1H references now all agree to ≤ 5e-12 (the test tolerance is tightened from 1e-2 to 1e-9).

    • endorfrq (B41): thresholded each orientation against its own maximum and filtered the range per orientation: 14 pairs vs EasySpin’s 16 (14N+1H), 34-97 vs 81 (63Cu+14N) at Threshold 1e-4. Now EasySpin’s Transitions exactly, at every orientation, and freq_range acts on the selection only: the selected pairs are returned even where their frequency at this orientation is outside it, as in EasySpin. The threshold is now strict (>), so at threshold=0 pairs of exactly zero rate are dropped, as in EasySpin.

    • Electronic pairs (B40): were kept without Enhancement: 6 pairs vs EasySpin’s 2 for S = 1/2 + 1H at threshold 0 in endorfrq; in salt, 63Cu (A = [60 60 600], Q) on the default 0-2·mwFreq axis had EPR lines near 8.9 GHz (0.05 % of the integral, 3e-4 of the maximum). Now always removed.

    • salt, field sweep (B59): the threshold was applied per (orientation, field) entry against the maximum of each memory batch (≤ 512 entries), so the spectrum depended on the batch size (14N+1H, Threshold 1e-2: 2.4e-3 of the maximum between batch caps 1 and 512, 0.19 with Enhancement). The pairs are now selected once per sweep at 5 fields spanning the resonance fields (kept if selected at any) and every entry of a kept pair is binned. The spectrum is identical for any batch size; at Threshold 0.01 (0-40 MHz) 2.57 % of the integral is dropped, as the fixed-field rule drops 2.56 % (0.60 % before).

    • Zero field (Options.ZeroField): the same rule on cluster pairs, without the electronic-pair removal.

    • New options: Options.TPSGridSymm / TPSGridSize (EasySpin’s undocumented options, defaults 'D2h', 4). Options.Transitions is read by endorfrq and salt (as EasySpin’s Opt.Transitions): the pairs replace the selection, with no threshold; salt then uses the matrix path; with ZeroField it raises.

    • Results that change: every endorfrq result with a freq_range or a pair that was below/above the per-orientation threshold; salt matrix-path spectra by the pairs that EasySpin drops (e.g. 14N+1H fixed field above); field-swept matrix-path spectra (the threshold is now EasySpin’s). The first-order perturbation path (one electron, no Q, no Enhancement) is unchanged. In test_zero_field.py the B → 0+ continuity check now passes Options(Transitions='all'): at 1e-5 mT the electronic-pair rule cuts through the Kramers doublets (the default spectrum is 0.48 of the zero-field one).

    • Tests: test_endor_tps_selection.py with tests/data/endor_tps_selection_refs.mat (generate_endor_tps_selection_refs.m: 18 endorfrq cases, 3 salt cases with info.Transitions), batch-cap independence, gradients vs central differences (14N+1H with Enhancement); test_endor_enhancement.py gains a default-threshold companion of test_endorfrq_vs_easyspin. 15 of the new or tightened tests fail on the 0.9.2 base.

[0.9.13] — 2026-11-11#

Added#

  • Gradients with respect to Sys.Ham coefficients (B53). ham_ezho detached the Ham coefficients, so ham, levels, pepper_autograd and pepper gave no gradient for them (Ham110, Ham112, and with Options.QuadraticZeeman Ham2xx/Ham3xx). The coefficients now stay on the autograd graph; a coefficient that is zero also gets its gradient. pepper sends a system whose Ham coefficient requires grad to its differentiable path (autograd.inputs_require_grad now looks into Sys.Ham). Values are bit-identical (1188 matrices compared against 0.9.12 for S = 1/2 to 5/2 and two electrons); ham(Sys) and pepper take the same time. Gradients match central differences to 1e-8 (crystal orientations, all six Ham110/Ham112 coefficients) and the chain rule through the g-equivalent matrix to 1e-9 (powder).

  • ham_ezho.ham_linear_g(Sys, e): the g matrix equivalent to the Ham110/Ham112 terms of electron e.

Fixed#

  • chili, cardamom and fastmotion now raise for Sys.Ham (B54). They build the Zeeman term from Sys.g only and ignored Sys.Ham without an error; for g given as Ham110/Ham112 they ran with g = 0. They now raise ValueError for any Sys.Ham entry, as EasySpin’s chili does (chili.m:160) and torchspin’s garlic already did. EasySpin’s cardamom and fastmotion do not check.

  • pepper’s automatic field range raises a clear error for g = 0 (B55). With no Exp.Range/Exp.CenterSweep and the linear Zeeman term given as Ham110/Ham112, the range computation divided by g = 0 and raised ZeroDivisionError. EasySpin takes the range from Sys.g too and fails with an index error (pepper.m:324). torchspin now raises ValueError and asks for Exp.Range or Exp.CenterSweep.

  • gStrain with a Ham110/Ham112 Zeeman term no longer gives an all-zero spectrum (B56). The strain widths divided gStrain by g = 0, and pepper (matrix) returned zero without an error (S = 1/2, g ≡ [2.01 2.005 1.998], gStrain [0.01 0.005 0.002]: max 0 against 327.7 for the same g as Sys.g). EasySpin’s pepper does the same. gStrain is now taken relative to the g-equivalent of the Ham terms in Sys.gFrame (in pepper, pepper_autograd and resfields); the spectrum equals the Sys.g one to 1e-13 and EasySpin’s spectrum of that g system at cosine > 0.9999999 (ref_ham_gstrain.mat, three cases incl. a gFrame and a 1H). A g-equivalent matrix that is not diagonal in Sys.gFrame raises ValueError, as gStrain with a full g matrix does.

[0.9.12] — 2026-11-11#

Fixed#

  • A one-element D is one D value with E = 0, as in EasySpin (B52). SpinSystem(S=[2.5], D=[300.]) was accepted with D left as a length-1 vector, and pepper then failed in ham_zf with IndexError: too many indices for tensor of dimension 1. EasySpin reads numel(Sys.D) == nElectrons as one D per electron (validatespinsys.m:208-210), so for one electron spin [D] is now the same as the scalar D: identical tensor and spectrum, and for S = 3/2, D = 300 MHz and S = 1, D = 400 MHz (ref_pepper_ext2.mat) D = [D] matches EasySpin to cosine 1.0000000, amplitude 1.00000 / 1.00001 (was an IndexError). For several electrons a single value is EasySpin’s ‘Sys.D has wrong size.’ and now raises ValueError (torchspin’s scalar D, which is applied to every electron, is unchanged). Any other D that does not normalize to (nElectrons, 3) or (3*nElectrons, 3), such as [[D]] for two electrons or a length-6 vector, now raises ValueError in the constructor instead of an IndexError later. Valid inputs are unchanged.

[0.9.11] — 2026-11-11#

Fixed#

  • Bins that no SOPHE triangle or zone reaches are exactly 0 in pepper and pepper_autograd, as in EasySpin (projecttriangles.c:98-100, 123-125; projectzones.c). The vectorised projections fill the interior bins of wide ramps and zones through running sums c1·k + c0; past the last ramp the +s/−s pairs did not cancel exactly and the residual was multiplied by the bin index. Empty bins therefore held a roundoff floor: for the rhombic stick spectrum g = [2 2.05 2.1], 9.5 GHz, Range [325 337] mT, 601 points, the minimum was −5.3e-14 of the maximum at GridSize [31 1] (pepper; −4.7e-14 in pepper_autograd) and −1.6e-14 at [31 4], −3.9e-14 for the corresponding frequency sweep, and positive residuals up to 2.9e-13 appeared in a Cu hyperfine stick spectrum. An integer coverage count built with the same scatter now leaves those bins at exactly 0; it carries no graph, so pepper_autograd stays differentiable. Bins inside an interior are bit-identical; a whole spectrum changes by less than 1e-12 of its maximum (the residual removed, also from bins another pass fills, then convolved), and spectra without a residual (the Dinfh zone cases checked) are bit-identical. Applies to field, frequency and zero-field sweeps and to salt, which uses the same torch projections. EasySpin references: tests/data/ref_pepper_exactzero.mat.

[0.9.10] — 2026-11-11#

Fixed#

  • Powder spectra whose field range leaves some orientations without a resonance lost or distorted the facets next to the missing knots (B48, B50). With missing knots pepper interpolates linearly, as EasySpin does (gridinterp L1, private/gridinterp.m:129, interp2(...,'linear')). torchspin’s bilinear interpolation (pepper._interp_grid) multiplied every corner by its weight, so a missing coarse knot (NaN) with zero weight still gave 0 * NaN = NaN and removed the fine knots on the neighboring coarse row or column; MATLAB’s interp2 ignores zero-weight corners (interp2([1 NaN; 2 3], 1, 1.5) = 1.5). Each corner term is now 0 when its weight is 0. Which fine knots lie exactly on a coarse row or column also depended on ulp-level differences: sphgrid built φ as k * dPhi, EasySpin as linspace(0, maxPhi, nPhi) (sphgrid.m:298,307), and the fractional knot indices were 0-based where gridinterp.m:121-125 adds 1 first (which rounds away an excess of a few ulp). sphgrid’s φ is now EasySpin’s bit for bit (all 12 φ-sweeping groups, GridSize 7 and 73), and the indices are formed 1-based and shifted. S = 1/2, g = [2 2.05 2.1] over [325 337] mT (GridSize [31 4], the range cuts the g = 2.1 edge): the stick spectrum deviated from EasySpin by up to 5.6 % of its maximum, with lw = 1.5 mT 2.4 % (Harmonic 0) and 7.1 % (Harmonic 1); now 5e-7, 2e-8 and 1e-7. S = 5/2, D = 300 MHz, tetragonal B4 on a D2h grid over [290 390] mT: 0.54 % (Harmonic 1) and 0.96 % (stick); now 4e-5, the deviation of the same system without interpolation. pepper_autograd takes its NaN pattern from the same numpy interpolation and changes identically; its gradients are unaffected in form and agree with central differences (B48 d/dg ≤ 2e-7, B50 d/dD, d/dE ≤ 6e-7 relative). Spectra with a resonance at every knot change only by roundoff (≤ 1.3e-13 of the maximum, from the φ values). Open-φ grids (Ci, C2h, C4h, C6h, S6, C1) with missing knots keep a separate deviation from EasySpin (B58, see KNOWN_LIMITATIONS.md). EasySpin references: tests/data/ref_interp_nan_edges.mat.

[0.9.9] — 2026-11-11#

Fixed#

  • Field-swept salt (Experiment.Range) has the same scale on both EPR solvers (B44). At infinite temperature EasySpin shares the polarization among the nuclear sublevels, 1/prod(2I+1), in both resfields and resfields_perturb (resfields.m:1265-1266, resfields_perturb.m:486-487), and torchspin’s resfields_perturb_batch does too, but salt called resfields_batch without the spin system, which skips that division. The matrix path (several electrons; also Sys.Ham systems once those are routed there) was therefore prod(2I+1) times too large: S = 1/2 with g = [2.01 2.005 1.998], 330-345 mT, GridSize 7, matrix/perturbation ratio of the spectrum sums 2.0000 for 1H (A = [3 5 12] MHz) and 6.0000 for 1H + 14N (A = [1 1.5 2] MHz); now 1.0000 (cosine 0.99978 / 0.99998, unchanged). The division is applied in salt rather than by passing the spin system, which would also compute strain widths that salt does not use. Finite temperature is unchanged (the Boltzmann populations already include it). Fixed-field salt (EasySpin’s mode) and one-electron field-swept spectra are bit-identical. EasySpin’s salt has no field-swept mode, so there is no direct reference.

[0.9.8] — 2026-11-11#

Fixed#

  • Perturbation-theory solvers now raise for Sys.Ham instead of returning NaN or zero (B46, B49). They build the electron Zeeman term from Sys.g only, and with g given as Ham110/Ham112 Sys.g is zero: endorfrq_perturb and resfreqs_perturb returned NaN frequencies, resfields_perturb/resfields_perturb_batch found no resonances, and pepper/pepper_autograd with Options.Method='perturb', 'perturb1' or 'perturb2' returned an all-zero spectrum (S = 1/2 + 1H: max 0 against 456 for the same g), all without an error. Other nonzero Ham terms of order lB ≤ 1 were dropped. These entry points now raise ValueError for any nonzero Ham term of order lB ≤ 1 and point to Sys.g or the matrix method (new spinsystem._reject_ham). EasySpin’s resfreqs_perturb rejects Sys.Ham* (resfreqs_perturb.m:75-77); its resfields_perturb, endorfrq_perturb and pepper perturbation path do not and give zero, which torchspin deliberately does not follow. pepper raises for every 'perturb*' call with such a system, also where it used to switch to the matrix solver without saying so (frequency sweeps, strain, several electrons). Terms of order lB ≥ 2 (dropped unless Options.QuadraticZeeman) still pass. Results with g, and every matrix and hybrid result, are unchanged.

[0.9.7] — 2026-11-11#

Fixed#

  • Resonance positions on axial (Dinfh) grids are interpolated with EasySpin’s spline (gridinterp.m:77-78, esspline1d(y, 1, iphi)): a cubic spline over the θ knot index with zero first derivatives at both ends (esspline1d.m EndCon = 1). torchspin fitted a not-a-knot cubic spline in cos θ, which bends differently next to both poles. Axial g (g = [2 2 2.4], lw 0.3 mT, GridSize [10 10]) was cosine 0.99863 and amplitude 1.029; a Cu(II)-like system (g = [2.05 2.05 2.25], 63Cu A = [50 500] MHz) on the default grid was cosine 0.99380 and amplitude 1.034 (0.93891 / 1.045 at GridSize [10 10]). All are now cosine ≥ 1 − 1e-10 and amplitude within 3e-6. This changes every interpolated Dinfh spectrum without missing resonances in pepper, pepper_autograd (the cached linear interpolation map is rebuilt from the same rule, so it stays differentiable) and the fixed-field salt path that interpolates. Intensities and widths (L3) and Dinfh grids with missing resonances (L3 for positions) are unchanged. EasySpin references: tests/data/ref_pepper_dinfh_interp.mat.

[0.9.6] — 2026-11-11#

Fixed#

  • pepper, pepper_autograd and salt now pad the sweep range with the edge values before the final line-width convolution when the spectrum reaches an end of the range, as EasySpin does (pepper.m:1171-1193, salt.m:858-882; B34). The convolution used to zero-extend, so the points within about two widths of such an end were wrong. Fixed-field salt, 1H, g = [2 2.05 2.1], A = [5 8 12] MHz, 10–19 MHz, lw 0.2 MHz: end points 0.562 and 0.552 of EasySpin’s (max |diff| 0.44 of the peak); 1H + 14N with Q (matrix path), 1.5–19 MHz, lw 0.3 MHz: 0.454 and 0.562; pepper frequency sweep, Lorentzian lw 40 MHz, Harmonic 1, 9.3–9.55 GHz: 0.538 and 0.548; pepper field sweep with HStrain and a Gaussian lw 1 mT, Harmonic 1: 2.94 and 3.21. All now 1.0000 (max |diff| 3e-13 of the peak; 1.8e-4 for the matrix-path salt and the HStrain case, the same as without padding). Spectra that are zero at both ends are bit-identical. An end counts as nonzero above 1e-9 of the row maximum, not at exact ~= 0 as in EasySpin, because torchspin’s projections leave a ~1e-14 round-off floor in empty bins (KNOWN_LIMITATIONS.md); a rhombic Voigt field sweep that EasySpin does not pad stays unpadded. Gradients flow through the edge copies (checked against central differences). EasySpin references: tests/data/range_padding_refs.mat.

Added#

  • Options.PaddingMultiplier (EasySpin Opt.PaddingMultiplier, default 3): the number of line widths by which the range is padded before the convolution; 0 switches padding off. Used by pepper, pepper_autograd and salt; a negative, non-finite or non-numeric value raises ValueError.

[0.9.5] — 2026-11-11#

Fixed#

  • salt simulates Sys.Ham systems on the matrix paths (B35). A linear Zeeman term given as Ham110/Ham112 sets g = 0, but salt’s first-order ENDOR path (fixed field, one electron without Q) and the field-swept mode’s perturbation resonance search build the Zeeman term from Sys.g alone. For S = 1/2 + 1H, A = [3 5 12] MHz at 338 mT with Ham110/112 equal to g = [2.01 2.005 1.998], the fixed-field spectrum was 12.77x the amplitude of the g spectrum with lines at the bare 1H Larmor frequency (cosine 0.00); 8.90x with orientation selection (ExciteWidth 30 MHz); the field-swept spectrum was all zero. Any system with a Sys.Ham entry (EasySpin’s MO_present) now always takes the matrix paths (resonance fields by resfields_batch, ENDOR by diagonalizing ham()), and the Ham spectrum equals the g spectrum on that path to 2e-12 (fixed field, with and without orientation selection) and 2e-14 (field swept); against the default first-order g spectrum: cosine 0.99999, amplitude 0.994. Deliberate deviation: EasySpin’s salt rejects every Sys.Ham* (salt.m:132). Field-quadratic and cubic terms (lB >= 2) are dropped, as in pepper with the default Options.QuadraticZeeman=False (True raises). An explicit Options.Method='perturb', 'perturb1' or 'perturb2' with Sys.Ham now raises ValueError (salt still ignores Method otherwise). The field-swept mode, which is not differentiable, now also raises NotImplementedError when a Sys.Ham coefficient requires grad (as for g, A, D, Q, ee), instead of returning a partial gradient once Ham coefficients are differentiable (B53). Results change only for systems with Sys.Ham; nothing else is routed differently.

  • salt raises for Sys.L, as EasySpin does (B45; salt.m:133, ‘salt does not support Sys.L.’). The first-order path ignored orbital angular momenta (S = 1/2, L = 1, soc = 100 MHz gave the spectrum without L exactly); the matrix path included them through ham() but was never validated (EasySpin has no reference).

[0.9.4] — 2026-11-11#

Fixed#

  • pepper interpolates the positions of every transition linearly once any transition lacks a resonance somewhere, as EasySpin does (pepper.m:701, 763-772: one global NaN_in_Pdat flag switches InterpMode to L1 on 2-D grids). torchspin switched only the slots that carried NaNs and kept the global cubic spline for the others, so the two kinds of slot were interpolated differently. S = 5/2 with D = 300 MHz and a B4 term on an explicit D2h grid, Range [200 480] mT, was cosine 0.9587 (Harmonic 1) and 0.9988 (Harmonic 0); a rhombic S = 5/2 (D = 400, E = 100 MHz) with a truncated range 0.99971. All are now ≥ 1 − 3e-8 with amplitude within 4e-5. pepper_autograd and salt already did this; pepper now gives the same spectra. Only non-axial field and frequency sweeps with interpolation in which some transition leaves the range (or has no resonance) at some knots change. EasySpin references: tests/data/ref_pepper_nanlinear.mat. On open-φ grids (C2h, Ci) a residual remains in both implementations; see KNOWN_LIMITATIONS.md.

[0.9.3] — 2026-11-11#

Fixed#

  • Wrong φ range of the D3d, D4h, D6h, Oh, C6h and S6 powder grids (B36), and Options rejected these grid symmetries (B51). sphgrid covered φ = 0..π/2 for D6h, D4h, Oh, D3d and C6h and 0..π for S6. EasySpin (private/gridparam.m) and torchspin’s own gridparam, used by pepper’s grid interpolation and by grid_triangulation, use π/6, π/4, π/4, π/3, π/3 and 2π/3. With orientations without resonances, pepper interpolated the coarse knots in gridparam’s layout although they came from the other grid: S = 5/2 with D and a tetragonal B4 (hamsymm D4h) over [200 480] mT had cosine 0.673 with EasySpin, a cubic B4 (Oh) over [250 430] mT 0.491. Even with resonances at all knots, the D3d, C6h and S6 grids held a non-integer number of symmetry wedges, which affected every sphgrid caller: a trigonal B4 (D3d) over [0 800] mT had cosine 0.964; the same system on an explicit S6 grid 0.901, a hexagonal B6 (D6h) on a C6h grid 0.735 (amplitude 1.83). The sphere average of a D3d-, S6- or C6h-invariant function was 2-4 % off. sphgrid now takes all grid parameters from one table (sphgrid._GRIDPARAM, EasySpin’s values; _SYM_PARAMS is gone), and all nine EasySpin cases agree to cosine ≥ 0.99993 and amplitude within 5e-4, for pepper and pepper_autograd. The knot counts do not change. With missing knots, pepper now also interpolates the positions of transitions that resonate at every knot linearly, as EasySpin does once any transition misses a knot (its L1 mode); before, those were bicubic (Oh case with only the grid fixed: cosine 0.463). This part applies to every grid: the D4h system above on an explicit D2h grid goes from cosine 0.959 to 1.0000000 with EasySpin. Options accepted only Dinfh, D2h, C2h, Ci, C1, O3 and 'auto'; it now accepts EasySpin’s 14 grid symmetries, 'auto' and '' (same as 'auto', as in pepper and EasySpin). The D2h, Th, C4h, C2h, Ci, C1, Dinfh and O3 grids are unchanged, and so are their spectra unless some orientations have no resonance.

[0.9.2] — 2026-11-11#

Changed#

  • API: endorfrq returns 1-based level pairs, as EasySpin and Options.Transitions. The third output transitions was 0-based ([i, j] indexing the eigenvalues), unlike every other level pair in torchspin (Options.Transitions, experiment.py; pepper’s _user_transitions) and EasySpin’s endorfrq ([u,v] = find(keepidx), endorfrq.m:331-332). It is now [u, v], 1-based levels in ascending energy, u < v; for S = 1/2 + 1H at high field the pairs are [1, 2] and [3, 4] as in EasySpin. Rows still follow the returned frequencies (ascending); EasySpin orders them by descending selection rate (endorfrq.m:339-341). Frequencies and intensities are unchanged, and salt does not use the indices. Migration: subtract 1 (transitions - 1) where the pairs index eigenvalues or eigenvectors. Tests: the EasySpin comparison in test_endor_enhancement.py now uses endor_enhancement_refs.mat’s Tr without the - 1 offset; one new test checks the pairs against EasySpin’s (fails on main).

[0.9.1] — 2026-11-11#

Tests#

  • EasySpin reference for zero-field lines exactly on bin edges with an interpolated grid. S = 1, D = [-700 -1300 2000] MHz puts its lines (0.6, 2.7, 3.3 GHz) on points of a 10 MHz axis, i.e. on bin edges. With GridSize [19 4] or [10 8] the positions are interpolated, and pepper._zf_const_pos gives every fine-grid vertex the coarse position, so each line goes into one bin as in EasySpin. Without it, interpolation round-off moves 5-39 % of each line into the lower bin (sticks: 1 - cosine 0.069-0.079; Gaussian 30 MHz: 1.0e-2-1.2e-2; Gaussian 300 MHz: max difference 1.9e-2). With it, torchspin matches EasySpin to max |difference| / max 6.9e-15 for sticks and both widths (ref_pepper_zerofield_edge.mat, 8 new tests; all 8 fail with _zf_const_pos replaced by the identity). Which of the two bins a line on an edge lands in depends on the last bit of the eigenvalues (B19), so the tests accept bin k or k - 1 and rebuild the reference from EasySpin’s single-pair spectra (Opt.Transitions) at torchspin’s bins; the tolerance (1e-12) holds either way. No code change.

Changed#

  • pepper._zf_const_pos docstring and call-site comments give its current purpose (single-bin deposit of a zero-field line on a bin edge). The near-zero-width triangle cancellation it was written for was fixed in the projection in 0.8.4 (B18).

[0.9.0] — 2026-11-11#

Changed#

  • orisel now has EasySpin’s interface (API break; minor version bump). The call is orisel(sys, exp, opt=None, *, per_transition=False). Experiment.Field (mT), mwFreq (GHz) and ExciteWidth (FWHM, MHz) are required, as in EasySpin (orisel.m:52-54), and a missing one raises a ValueError that names it; Exp.Range is no longer read (an experiment with Range but no Field gets a migration hint). Exp.Orientations ((N, 2) [phi, theta]) replaces the grid when given. OriselOptions is now GridSize=46 (was 19; EasySpin orisel.m:66), GridSymmetry='auto' (hamsymm, with the grid rotated into the symmetry frame, orisel.m:79-93) and AveragedIntensity=True; ExcitBandwidth and Threshold were removed and raise with a hint. The return values are torch tensors (were NumPy arrays): (weights, phi, theta) with the weights summed over level pairs (EasySpin’s one-output form), not normalized and not multiplied by grid weights; per_transition=True gives EasySpin’s two-output form as (Weights, Transitions, phi, theta), Weights of shape (nOri, nTrans) and Transitions the 1-based level pairs (u, v), u < v, in the order of nchoosek(1:N, 2) (the numbering of Options.Transitions). phi, theta are the orientations the weights belong to. Systems with several electron spins and SpinSystem.H0Extra are now supported (full diagonalization). Migration: orisel(sys, Experiment(mwFreq=9.5, Range=[300, 380]), OriselOptions(ExcitBandwidth=100)) becomes orisel(sys, Experiment(mwFreq=9.5, Field=B, ExciteWidth=100)) at the observer field B; divide by w.max() for the old normalization.

Fixed#

  • orisel selected the wrong orientations (all releases up to 0.8.7). It ignored Exp.Field and the excitation width, computed resonance fields over Exp.Range by one-electron perturbation theory and weighted them with a field-domain Lorentzian always centered at the g = 2.0023 field, with the width converted at the free-electron slope, HStrain ignored, SOPHE grid weights multiplied in and the result normalized to 1 (old orisel.py:137-169). EasySpin diagonalizes the full Hamiltonian at Exp.Field and weights every level pair by its transition rate times exp(-2 xi^2), xi = (nu_uv - mwFreq)/Gamma, Gamma = sqrt(sum_i n_i^2 HStrain_i^2 + ExciteWidth^2)/sqrt(2 ln 2) (orisel.m:110-153). Per orientation, the old weights correlated with EasySpin’s at -0.57 to +0.98 depending on the observer field (rhombic S = 1/2, Cu(II) with 63Cu, g = [1.9 2.0 6.0]; 9 fields), with cosine 0.000 at the g = 6 and g = 4 fields. torchspin now runs EasySpin’s model, and the weights and transitions agree with EasySpin to 7e-13 (relative to the largest weight) in 18 cases: the three systems above, S = 1 and S = 3/2 with D and HStrain, two coupled electron spins, AveragedIntensity false, ExciteWidth = Inf, and six default grids incl. rotated D2h and C2h GridFrames, Dinfh, O3 and an explicit Ci, where the orientations also agree to 1e-15. EasySpin’s own regression data (orisel_rhombic.mat, orisel_onenucleus.mat) agree to 4e-6 after normalization. The weights are now differentiable (g, A, D, HStrain, …). The computation is shared with salt’s orientation selection (orisel._orisel_weights), which was already EasySpin’s model.

    • Results that change: every orisel result. No other torchspin function called orisel; salt spectra are bit-identical (checked with and without HStrain, S = 1, two electron spins, 14N with Q, and zero field), and saffron keeps its own selection.

[0.8.13] — 2026-11-11#

Fixed#

  • saffron’s S = 1/2 fast path now raises for nonzero Sys.Ham terms instead of dropping them. That path builds the electron Zeeman term from Sys.g only, so a g given as Ham110/Ham112 (where g is zero) gave a signal of exactly zero (3pESEEM, S = 1/2 + 1H: norm 0 against 0.226 for the same g), and other Ham terms were ignored. EasySpin’s saffron rejects every Sys.Ham* (saffron.m:130-131). The S > 1/2 fast path and the real-pulse engine (Opt.SimulationMode='thyme') build the full Hamiltonian with ham() and keep supporting Ham (torchspin extension; Ham-given g reproduces g to 1e-11 on both); the error message points to them. No other result changes. Supporting Ham on the S = 1/2 fast path is left open (see KNOWN_LIMITATIONS.md).

[0.8.12] — 2026-11-11#

Fixed#

  • Spin systems built with D_ (or A_) failed in torchspin’s internal rebuilds: the isotopologue expansion, the Lorentzian strain path (HStrainL) and spin2sys’s U term. All three used dataclasses.replace, which passes every stored field, so the D (A) that __post_init__ derives from D_ (A_) was passed together with it and the constructor raised “Zero-field splitting given in both D and D_” (spinsystem.py, __post_init__). For example pepper(SpinSystem(S=1, D_=[300, 0.1], Nucs='Cu', A=...), ...) and pepper with D_ and HStrainL raised; isotopologues.py cleared A_ but not D_, and HStrainL also failed with A_. The new internal helper spinsystem._replace(sys, **changes) rebuilds from _init_kwargs (pairs passed through their source only) and clears the alternative of a changed field, as attribute assignment does; it is used at all three sites. Tensors are not copied, so a D_ that requires grad keeps its gradient (autograd vs central differences 1e-6 through HStrainL). Spectra with D_ now equal those with the same D (1e-10); no other result changes. The constructor is unchanged: calling dataclasses.replace directly on such a system still raises (see KNOWN_LIMITATIONS.md for the workaround).

[0.8.11] — 2026-11-11#

Fixed#

  • salt no longer convolves an ENDOR line width of at most two rf increments, as in EasySpin (salt.m:899-911; EasySpin skips a Gaussian or Lorentzian Sys.lwEndor component of FWHM ≤ 2 increments when its harmonic is 0). torchspin always convolved lw_mhz, which lowered the peaks of under-resolved spectra: 1H (g = [2 2.05 2.1], A = [5 8 12] MHz, 2–28 MHz at 0.02 MHz increments, perturb1) was 0.933 of EasySpin’s peak at 1.5 increments and 0.900 at 2.0. Both are now 1.0000 (max deviation 3e-13 of the peak); 2.5 and 10 increments were already exact and are bit-identical. Applied in the fixed-field mode (via pepper._lw_convolve, the B13 rule of 0.8.5) and the field-swept mode (no EasySpin counterpart). Results change only for lw_mhz ≤ 2 increments, which now give the unbroadened spectrum; this includes the default lw_mhz = 0.1 on the default 512-point axis. A skipped width that requires grad has zero gradient. EasySpin references: tests/data/salt_narrowlw_refs.mat. A Lorentzian ENDOR width and Exp.Harmonic are still not supported in salt (KNOWN_LIMITATIONS.md § ENDOR).

[0.8.10] — 2026-11-11#

Fixed#

  • salt now raises for sets of equivalent nuclei (Sys.n > 1), as EasySpin does (salt.m:135-136, ‘salt does not support sets of equivalent nuclei (Sys.n>1).’). torchspin had no check on n, and every ENDOR path treats each entry of Nucs as one nucleus, so n = [2] returned the spectrum of n = [1] exactly (maximum difference 0 for 1H at 326.5 mT). The check runs before anything else in salt, on every path (first-order, matrix, several electrons, field-swept, zero field), and also catches n assigned after construction. Results with n = 1 are bit-identical. Give equivalent nuclei as separate entries of Nucs instead.

[0.8.9] — 2026-11-11#

Fixed#

  • The closed-φ powder grid interpolation now resamples each θ row with zero end slopes, as EasySpin does (gridinterp.m:184, esspline1d(y,1,nc)). To turn the triangular grid (D2h and the other closed-φ symmetries) into the rectangle for the bicubic spline, torchspin fitted each row with scipy’s default not-a-knot spline. The rows next to the pole have only 2–5 knots, so the two rules give different resonance fields near g_z, which shows at Harmonic 1: for S = 1/2, g = [2 2.05 2.1] at 9.5 GHz and the default GridSize [19 4], the peak amplitude was 1.0058 of EasySpin’s with lw = [1 0] and 1.0048 with lw = [0 0.8] (relative residual 3.9e-3 and 6.5e-3), independent of nPoints. Both are now 1.0000000 at residual 5e-7, the field-sweep floor without interpolation. Also before → after: GridSize [31 4] amplitude 0.99991 → 1.0000001; a 14N hyperfine spectrum residual 1.5e-2 → 2.4e-8; a frequency sweep 4.4e-3 → 7e-13; HStrain 1.5e-4 → 8.0e-5; fixed-field salt (rhombic g and A, Method 'perturb1') 7.6e-4 → 1e-12; the 0.8.5 Voigt cases at Harmonic 1 1.0020 / 1.0048 → 1.0000000; d spc/d g_z as a central difference (h = 1e-4) 1.9e-2 → 4.2e-5. Every powder spectrum interpolated on a closed-φ grid (interpolation factor > 1) changes, in pepper, pepper_autograd and salt (all through pepper._d2h_interp_matrix), the large-grid fallback in _interp_sph, and the closed-φ rows of _interp_grid. The 2-D step stays not-a-knot, as in EasySpin’s esspline2d. Gradients stay exact (pepper_autograd vs central differences to 1e-6 for d/d g_z). Spectra without interpolation, on axial (Dinfh) grids and on open-φ grids are bit-identical. EasySpin references: tests/data/ref_closedphi_interp.mat.

[0.8.8] — 2026-11-11#

Fixed#

  • endorfrq_perturb intensities, element order and full 3×3 Q now match EasySpin’s endorfrq_perturb.m element by element (bugs B20, B27). Intensities: torchspin used the matrix element (I+mI)(I−mI+1)/4 with mI the lower level, one level off from EasySpin’s k(2I+1−k)/4, k = 1..2I (.m:367), so the lowest transition of every nucleus had intensity 0, and it dropped the factor ∏(2I+1) over all nuclei (.m:385). For 1H+14N at φ = 0.3, θ = 0.7 (340 mT) torchspin gave 0 for all 1H lines and 0 / 1.58e-6 for the 14N lines; EasySpin gives 1.36e-3 and 9.47e-6, as torchspin does now. Order: torchspin listed transitions mS-major with mS descending; EasySpin lists them per nucleus by the mI of the lower level, mS ascending within it (.m:303-304, 377-381). torchspin now uses EasySpin’s order, so frequencies agree element by element and not only after sorting. Full Q: with sys.fullQ torchspin read row i of the 3×3 matrix as principal values (14N with a full Q: sorted 12.27/12.33/14.37/14.40 MHz vs EasySpin 11.15/13.31/13.42/15.48); it now uses the matrix as EasySpin does (.m:84-85). Agreement over 8 systems × 4 orientations × PerturbOrder 1 and 2: frequencies 7.4e-16, intensities 4.9e-16 relative. Callers that index the output by position or use its intensities see different values; sorted frequencies are unchanged except with a full Q. salt does not call endorfrq_perturb and is unaffected. EasySpin references: tests/data/endorfrq_perturb_refs.mat.

[0.8.7] — 2026-11-11#

Fixed#

  • Assigning a SpinSystem field after construction skipped its normalization (all releases up to 0.8.6). sys.HStrain = [1, 2, 3] left a raw list, and pepper then failed with TypeError: '>' not supported between instances of 'list' and 'int'; other fields kept shorthand forms (D = [D, E], scalar g, Q = [e2qQ/h, eta], …) that the solvers do not read. SpinSystem.__setattr__ now rebuilds the system with the new value, so an assigned field holds exactly what the constructor would have stored, and a value the constructor rejects raises at the assignment (the system is left unchanged). Assigning one of an alternative pair (D/D_, A/A_, lw/lwpp, tcorr/logtcorr, Diff/logDiff) clears the other. Tensors are not copied, so an assigned tensor that requires grad stays on the autograd graph. Attributes that are not constructor fields (e.g. ZeemanFreq for spidyan) are assigned as before; object.__setattr__(sys, name, value) bypasses the normalization.

    • Results that change: none for systems built in the constructor. After an assignment, results are now those of the system constructed with that value. Two cases behave differently from before: assigning tcorr over a set logtcorr now takes effect (logtcorr, which the solvers read first, is cleared), and sys.A = None now gives the constructor default (zero hyperfine) instead of leaving None. Assigning a value that only fits after a second assignment (e.g. Nucs with a different number of nuclei before n) now raises; build a new SpinSystem instead.

[0.8.6] — 2026-11-11#

Fixed#

  • orisel turned every solver error into zero selectivity. It wrapped the per-orientation call to resfields_perturb in try/except Exception and set the weight to 0, so an unsupported system or a real bug returned plausible-looking weights (a two-electron system gave all zeros without a warning). Errors now propagate, and a system with more than one electron spin raises NotImplementedError up front (orisel uses the one-electron perturbation solver; EasySpin’s orisel diagonalizes the full Hamiltonian). A field range without resonances still gives weight 0. Unchanged: the weights of every system that ran without an error (bit-identical for S = 1/2 with and without nuclei, S = 1 and S = 5/2 with D).

[0.8.5] — 2026-11-11#

Fixed#

  • pepper no longer convolves line widths of at most two increments when no harmonic is taken, and with a Voigt width the Lorentzian carries the harmonic and Exp.mwPhase, as in EasySpin (pepper.m:1152-1223). torchspin convolved such delta-like lines anyway, which lowered peak amplitudes: the S=1 frequency sweep (D = 3000 MHz, lwpp = 10 MHz at 9.8 MHz increments) was 0.989 of EasySpin’s amplitude, 0.984 and 0.971 for pairs (1,2) and (2,3); narrow field sweeps at Harmonic 0 were 0.974 (Gaussian) and 0.926 (Lorentzian). All are now 1.0000. Results change only for (a) a width ≤ 2 increments whose harmonic is 0 and (b) spectra with both lw components and a harmonic or mwPhase (Voigt frequency sweep at Harmonic 1: 1.039 → 1.000). Every other spectrum is bit-identical. Applied to field and frequency sweeps in pepper and pepper_autograd. A narrow width with a harmonic is still convolved (EasySpin raises); see KNOWN_LIMITATIONS.md. EasySpin references: tests/data/ref_pepper_narrowlw.mat.

[0.8.4] — 2026-11-11#

Fixed#

  • The SOPHE triangle projection lost mass for near-zero-width triangles straddling a bin edge (pepper._projecttriangles and the differentiable projecttriangles_t). The edge-bin integrals subtracted terms of the size of the bin index, and the ramp slope (∝ 1/width²) amplified their rounding: vertices [10 − 1e-14, 10 − 1e-14, 10] on a 5 + 0.01·k axis gave area 1.0526 instead of 1, and a seeded fuzz found per-bin errors up to 33 %. The integrals are now written in the overlaps with the edge bins, and mass is conserved to rounding for every geometry. Only spectra with such triangles change (narrow powder features sitting on a bin edge, e.g. zero-field or axial lines). Results for ordinary triangles agree with 0.8.0 to ~1e-15 relative, and gradients are unchanged apart from rounding. EasySpin’s projecttriangles.c has the same cancellation (see KNOWN_LIMITATIONS.md).

  • salt at zero field no longer pins the interpolated line positions to the coarse-grid values; that workaround for the projection error above is removed.

  • salt no longer warns “Converting a tensor with requires_grad=True to a scalar”: the transition-selection threshold is now computed from detached intensities (it is a discrete selection; gradients are unchanged).

[0.8.3] — 2026-11-11#

Fixed#

  • pepper_autograd used second-order perturbation theory for Options.Method='perturb1'. Its powder route called the perturbation solver without the order, so 'perturb1' gave the second-order spectrum (and its gradient) while pepper gave the first-order one: up to 1.47 relative max deviation for axial Cu(II). Because pepper hands inputs that require grad to pepper_autograd, pepper(..., Method='perturb1') with a differentiable parameter was affected too. The order now follows PEPPER_PERTURB_ORDER, as in pepper and the orientation route. Changes: differentiable 'perturb1' powder spectra and gradients. Unchanged: 'perturb', 'perturb2', 'matrix', 'hybrid', all non-differentiable pepper results, and the Exp.CrystalOrientation route (which already passed the order).

[0.8.2] — 2026-11-11#

Fixed#

  • nucspinrmv, nucspinkeep and nucspinadd dropped most fields of the spin system (all releases up to 0.8.1). They rebuilt it from a short list of fields, so ee became zero, Ham None, and ee2, eeFrame, D_, sigma, n, Abund, L/gL/soc/CF*, initState, tdm, tcorr/Diff, T1/T2 and the other non-hyperfine fields were lost. They now copy every field and filter only the per-nucleus ones (Nucs, n, A/A_, AFrame, gnscale, sigma, sigmaFrame, Q, QFrame, Abund, full 3×3 forms included), as EasySpin’s nucspinrmv.m does; tensors are passed without copying, so the result stays on the autograd graph.

    • Results that change: pepper Method='hybrid' for systems whose core carries ee, ee2, Sys.Ham, OAM/crystal-field terms or initState (cosine to EasySpin’s hybrid: exchange-coupled dimers 0.00 and −0.02, now 1.00000 and 0.99998; S = 3/2 with Ham132 0.945, now 1.00000; with initState the hybrid spectrum was the thermal one), and saffron’s fast algorithm for S > 1/2 with Sys.Ham (the term was missing from the electronic Hamiltonian). Hybrid for a single electron without these fields, and every other method, are unchanged.

    • AStrain applies to the first nucleus: it is dropped with a UserWarning when that nucleus is removed. initState given for the full spin space raises when the nuclear dimension changes. Nonzero nn raises (as in EasySpin) unless fewer than two nuclei remain.

    • nucspinadd accepts [Aperp, Apar], full 3×3 A and Q, Q as e2qQ/h or [e2qQ/h, eta], and tensors that require grad (they were converted through NumPy, which detached them); mixing a full and a principal-value tensor writes both as full matrices.

[0.8.1] — 2026-11-11#

Fixed#

  • salt’s first-order perturbation path gave every ENDOR line unit intensity (all releases with this path). For one electron without quadrupole couplings salt picks first-order perturbation theory by itself; its lines had intensity 1, while the matrix path (and EasySpin, with both Opt.Method='matrix' and 'perturb1') uses |⟨i|μ⊥|j⟩|² in (MHz/mT)². The absolute scale therefore jumped about 2200× for 1H with the path (e.g. when Options.Enhancement was switched on), and nuclei with different gn or spin I had wrong relative weights (1H+14N: cosine 0.649 against EasySpin). Each first-order line now carries EasySpin endorfrq_perturb.m’s intensity, summed over its 2I coinciding mI transitions: (gn·μN/h)²/4 · 2I(I+1)/3 · ∏(2I+1). This matches EasySpin perturb1 to round-off (shape and scale) and EasySpin’s default matrix to 0.3 % (1H) in area. Both the fixed-field (Experiment.Field) and the field-swept (Experiment.Range) modes are fixed. What changes: the absolute scale of every one-electron, no-Q salt spectrum (by 1/2206 for a lone 1H), and the shape of spectra with several kinds of nuclei. Fitted amplitude scales change accordingly. What does not change: systems with Q, more than one electron, Options.Enhancement=True or Options.ZeroField=True (all on the matrix path), line positions, and the automatic choice of the first-order path.

[0.8.0] — 2026-11-11#

The first PyPI release since 0.7.0: it also contains 0.7.1–0.7.7 below, which were merged but not published separately.

Added#

  • torchspin.lft: ligand-field tools. Josh Telser’s programs, ported from telser-tools and differentiable. lft.ddn, ddnloop, ddnpow, ddnfit, ddnsus, ddnmag, dpn, dpnfit, dsoxf, tanabe_sugano, dlsd5, dipole, dtd.

    • lft.fit.JointFit fits one model to band energies, g values, χ, M and EPR spectra together, with exact Jacobians.

    • lft.dn2sys builds a SpinSystem with the full g matrix, for a differentiable route from a ligand field to pepper.

    • lft.plot draws its plots in cm⁻¹ by default.

    • lft.telser2torchspin converts DDZHQ, DDPOWH, DJDZE and DDPOWJ inputs.

    • lft.ddpowh, lft.ddpowj: Telser’s field-point powder EPR, FDMR, ENDOR and S = 0 NMR/NQR on a SpinSystem. They add what pepper lacks: the level strain width that depends on the composition of each level (DDPOWH sum and DDPOWJ product weights), m_S-manifold pair selection, Lorentzian frequency-domain lines, the Flygare factor, the line cutoff, zero-field FDMR, chemical shielding, and Telser’s w and U terms. The converters’ target='lft' runs a Telser input through them; all 103 DDPOWH/DDPOWJ golden inputs match telser-tools to 1e-10.

    • The package is additive: only torchspin/__init__.py gains lft. See docs/lft.md.

Fixed#

  • Flaky test test_orientations_at_zero_field_match_the_powder. Its zero-field lines (0.6, 2.7, 3.3 GHz) sat exactly on bin edges of the 10 MHz axis, so the powder projection put each line in one of two bins depending on the last bit of the eigenvalues, and the test failed by 4 % on some CI runners. The lines are now a third of a bin from any edge, and the powder is compared on the half-bin-shifted axis. pepper is unchanged: the single-bin deposit matches EasySpin and the B → 0⁺ limit. KNOWN_LIMITATIONS documents the bin-edge case.

[0.7.7] — 2026-11-10#

Added#

  • SpinSystem.HStrainL: Lorentzian strain in pepper. A [3] vector (or scalar) of frequency-domain Lorentzian FWHM in MHz along the molecular x, y, z axes. A transition’s width is sqrt(sum_k (HStrainL_k n_k)^2), the orientation dependence and dB/dE conversion of HStrain, but every line is drawn as a Lorentzian instead of a Gaussian (Telser’s DDPOWH/DDPOWJ Lorentzian width). Works on every pepper path (powder facet summation, per-orientation and interpolated fallbacks, isotropic, crystals, Exp.Orientations, frequency sweeps, Method='hybrid'), with Exp.mwPhase (the dispersion admixture is in each line; the remaining Sys.lw is then convolved as absorption) and in pepper_autograd (gradients w.r.t. HStrainL, g and the other spin-system tensors). esfit treats it as non-negative and ml templates keep it. Not an EasySpin field: EasySpin’s strains are all Gaussian, so this is a deliberate addition. Validated by: isotropic HStrainL equals the EasySpin-validated Sys.lw(2) Lorentzian exactly (field and frequency sweeps, harmonics 0–2); single orientations equal the analytic Lorentzian to 1e-12; rhombic S = 1/2 powders meet a brute-force reference as closely as the Gaussian HStrain does (0.6 % vs 0.7 %); gradients match central differences to 1e-6. Combining it with HStrain, gStrain, AStrain or DStrain raises ValueError (no per-line Voigt profile). The default (None) is unchanged.

[0.7.6] — 2026-11-10#

Added#

  • Experiment.Orientations / Experiment.OrientationWeights: pepper on a user-supplied list of field directions. Orientations is an (N, 2) array (or tensor) of [phi, theta] in radians in the molecular frame, B0 along (sinθ cosφ, sinθ sinφ, cosθ) as in levels/resfields; OrientationWeights (default 1/N) are fractions of the sphere, used as given, so weights summing to 1 give the powder amplitude. pepper sums the stick spectra of these orientations with χ-averaged (powder) transition rates, without grid interpolation or SOPHE projection: every line is accumulated with an exact template (strain width or Sys.lw(1) Gaussian, else Sys.lw(2) Lorentzian) and the rest of Sys.lw is convolved, as on the crystal and isotropic paths. Supported: field and frequency sweeps, Method='matrix'/'perturb*'/'hybrid', strains, temperature, Sys.initState, photoselection, ModAmp, Opt.separate='orientations'. pepper_autograd supports it for field sweeps (gradients w.r.t. the spin system, lw, strains and the weights). Raises with Ordering, SampleFrame, SampleRotation, MolFrame, CrystalSymmetry, Opt.Sites and Opt.separate='transitions'/'sites'; GridSize/GridSymmetry are ignored. EasySpin has no counterpart; validated against EasySpin crystal spectra summed over two rotations about B0 (an exact χ average). The default (None) is unchanged.

[0.7.5] — 2026-11-10#

Added#

  • Options.Transitions selects the transitions pepper simulates, like EasySpin’s Opt.Transitions. None (the default) keeps the automatic transition pre-selection with Opt.Threshold, so default spectra are unchanged (bit-identical). 'all' takes every level pair u < v with neither the pre-selection nor the Threshold intensity post-selection (EasySpin sets its post-selection threshold to zero for 'all'), which recovers weak lines that the default drops, such as the half-field ΔmS = 2 line of a triplet with small D. A list of 1-based level pairs (u, v), levels numbered by ascending energy at the resonance field, takes exactly those transitions: pairs are normalized to u < v, duplicates are removed, and out-of-range indices, u = v, non-integers and empty lists raise ValueError (EasySpin silently drops out-of-range rows and keeps duplicates). Within a list the Threshold post-selection still applies, as in EasySpin. Supported on every matrix path of pepper (powder projection, strain summation, interpolation, crystals, the isotropic O3 path, frequency sweeps including the automatic range, and Method='hybrid', where levels are those of the exact core) and in pepper_autograd (gradients flow as before; the pair list is a constant). Method='perturb*' raises when Transitions is set (EasySpin ignores the option there). Validated against EasySpin on 9 cases (tests/data/ref_pepper_transitions.mat).

[0.7.4] — 2026-11-10#

Added#

  • Zero-field frequency sweeps and fixed-field ENDOR: Options.ZeroField (default False, which leaves results unchanged). With ZeroField=True, pepper frequency sweeps and salt fixed-field ENDOR accept Experiment.Field = 0. Levels are grouped into degenerate clusters (Kramers doublets, accidental degeneracies), and each transition carries the rate summed over all level pairs between two clusters. Intensities are therefore independent of the arbitrary eigenbasis inside a degenerate subspace. The summing is done before slot tracking, threshold pruning and pair preselection. The isotropic O3 shortcut is replaced by a D2h grid. Validated against EasySpin’s pepper at Exp.Field = 0 (5 cases, ref_pepper_zerofield.mat), closed forms (S = 1: D−E, D+E, 2E; S = 3/2: 2·sqrt(D²+3E²)) and the B → 0 limit. See KNOWN_LIMITATIONS.md, “Pepper and salt — zero field”.

  • Experiment(Field=0) now constructs in frequency-swept and fixed-field mode. Without ZeroField, the same ValueError("Experiment.Field must be positive (mT).") is raised when pepper, salt, garlic, chili or resfreqs_perturb is called. A negative field still raises in the constructor.

[0.7.3] — 2026-11-10#

Added#

  • Hyperfine enhancement in ENDOR intensities: Options.Enhancement (EasySpin Opt.Enhancement). Default False: results are unchanged (bit-identical). With True, endorfrq (new keyword opt=Options(...)) and the matrix paths of salt use the total magnetic moment (electron + nuclear, the mux/muy/muz of ham()) perpendicular to the field, chi-averaged over lab x and y, as the rf transition operator. As in EasySpin endorfrq.m, the transition selection (threshold/Opt.Threshold) still uses the nuclear-only rates and electronic level pairs are excluded. salt with Enhancement=True always uses the matrix ENDOR path; its automatic first-order perturbation shortcut (one electron, no Q) has no enhancement. endorfrq_perturb gained an opt keyword and raises NotImplementedError for Enhancement=True (EasySpin silently ignores it there). Validated against EasySpin endorfrq/salt with Opt.Enhancement='on' (tests/data/endor_enhancement_refs.mat), a NumPy brute force, the first-order factor (ν_ENDOR/ν_I)² and gradients (reverse and forward mode).

[0.7.2] — 2026-11-10#

Added#

  • SpinSystem.H0Extra: generic extra terms in the field-independent Hamiltonian. A list of (coeff, op) pairs; ham adds Σ coeff·op (MHz) to H0 on both the (H0, μ) and the ham(Sys, B0) path, so every simulator that diagonalizes the full Hamiltonian (pepper’s matrix method and pepper_autograd, levels, resfields, resfreqs, endorfrq, curry, nucfrq2d, saffron’s real-pulse engine, spidyan) includes it. coeff is a real scalar (float or 0-d tensor) and stays on the autograd graph, as does op when it is a tensor that requires grad; op is an (n, n) Hermitian matrix in the full spin-system basis (sop order). This allows terms that torchspin has no field for, such as the S=3/2 U term U Σ C_k(S) I_k. Shape, Hermiticity and real coefficients are checked when the spin system is built. hamsymm analyzes systems with H0Extra through the eigenvalue probe, and pepper routes to pepper_autograd when a coefficient or operator requires grad. Solvers that build the Hamiltonian from the tensors without ham (perturbation theory, Method='hybrid', garlic, chili, fastmotion, cardamom, saffron’s fast algorithm, salt for one electron, orisel, nucspinrmv/nucspinkeep/nucspinadd) raise when it is set; so do isotope mixtures in Nucs and SpinSystem.n > 1. Not an EasySpin feature. The default (None) is unchanged.

[0.7.1] — 2026-11-10#

Added#

  • Opt-in field-quadratic and field-cubic higher-order Zeeman terms in the resonance search: Options.QuadraticZeeman (default False, unchanged behavior). With True, the Sys.Ham terms of order lB = 2 and 3 enter pepper’s matrix solver, so that H(B) = H0 − B n·μ + B² n·G2·n + B³ G3[n,n,n] equals ham(Sys, B·n) at every field. The Hermite level model, Hellmann–Feynman slopes, companion-matrix roots, Newton polish, the dB/dE intensity factor and the strain widths all use dH/dB = −n·μ + 2B n·G2·n + 3B² G3[n,n,n]; the transition pre-selection diagonalizes the full H at the center field, and frequency sweeps add the terms at the fixed field. Covers pepper and pepper_autograd (Method='matrix': powders, crystals, O3, field and frequency sweeps; the implicit-function gradient uses the full slope) and resfreqs_matrix; levels gets the same switch as the keyword quadratic_zeeman=False. resfields_batch/resfreqs_batch take the operators as zeeman_ho= (from the new torchspin.ham_ezho.field_nonlinear_zeeman_ops). The perturbation and hybrid methods, resfields, garlic and salt raise NotImplementedError when the option is on and such terms are present; lB ≥ 4 terms raise. Validated against ham(Sys, B) (levels to 1e-12, resonance condition to 1e-9), a closed form for S = 1 with w(μB B·S)², a brute-force field-point powder simulation (cosine 0.999998), finite differences (dB/dE, gradients) and EasySpin pepper (tests/data/ref_pepper_quadzeeman.mat, cosine ≥ 0.99999, amplitude within 0.4 %). With the default False, every result is bit-identical to 0.7.0.

[0.7.0] — 2026-11-09#

CPU-parallel fitting and data generation. Default behavior (n_workers=1, simulate_batch(workers=0)) is unchanged; no physics code changed.

Changed — behavior differs from 0.6.7#

  • FitOptions.n_workers now also applies to levmar, trf, lbfgsb and the uncertainty estimate of every method, not only to the population methods. A script that already set n_workers='auto' (or an integer > 1) for one of these methods used to get no parallelism; it now starts spawned worker processes, which needs the usual if __name__ == '__main__': guard around the code that runs the fit.

Added#

  • Parallel finite differences in esfit. With FitOptions(n_workers > 1) or 'auto', the independent finite-difference probes run in the worker pool: levmar’s initial Jacobian (n + 1 calls), every trf Jacobian and L-BFGS-B gradient (n calls each, through SciPy’s workers=, SciPy ≥ 1.16; older SciPy runs them sequentially with a warning) and the uncertainty Jacobian (2n calls). Probe points, recording order and evaluation counts are unchanged, so a model with deterministic output gives the same fit. For trf and lbfgsb, SciPy evaluates the base point in the main process and the probes in workers with fewer threads; torch round-off then differs at ~1e-14, which shows up as a ~1e-6 relative Jacobian difference, far below what changes a fit. Measured on a 224-core cluster node (4-parameter pepper fit, 8–64 threads): levmar 1.6–1.7×, trf 2.6–3.2× faster. The uncertainty Jacobian no longer evaluates an unused base point.

  • FitOptions.devices, e.g. ['cuda:0', 'cuda:1']: process workers are pinned to these GPUs round-robin (CUDA_VISIBLE_DEVICES per worker), so a model with device='cuda' runs on its own GPU.

  • torchspin.ml.simulate_batch reuses its worker pool (shared with esfit) instead of starting one per call, sends rows in chunks, and accepts workers='auto'. Cu(II) on a 64-core node: 197 → 1473 spectra/s with 64 workers (one process: 42; one A100 GPU: 76). An interrupted batch terminates the pool.

  • torchspin.parallel (public): cpu_budget() (CPU affinity, then SLURM, then the machine), inner_threads(), the thread_budget(n) context manager (caps torchspin’s inner pools, and BLAS with blas=True when threadpoolctl is installed) and native_thread_env(n) for spawned workers (also passes OMP_WAIT_POLICY=PASSIVE).

  • Optional extra [hpc] (threadpoolctl, cloudpickle).

  • Docs: docs/pitfalls.md, “Training sets of large spin systems” (orientation symmetry and Options.Threshold: for Cu(II) with two ¹⁴N, Threshold=1e-2 was 3.6× faster with a 0.4 % spectrum change).

  • Benchmarks:

    • end-to-end esfit workloads (levmar and trf, sequential and with process workers; swarm with process and thread backends; a nested-parallelism case);

    • benchmarks/workloads/ml_throughput.py (spectra per second of simulate_batch);

    • benchmarks/analysis/compare_baseline.py, which saves host-free baselines and flags regressions;

    • a generic SLURM job-array template, benchmarks/cluster/slurm_array_template.sbatch;

    • run_workloads.py --save-outputs;

    • docs/v1_acceleration/: the acceleration review and roadmap with the measurement log.

Fixed#

  • benchmarks/workloads/run_workloads.py:

    • --threads N now overwrites the native thread variables. With an inherited OMP_NUM_THREADS (as batch scripts set it), “1-thread” runs used to keep every core in the native pools.

    • It also caps Apple Accelerate (VECLIB_MAXIMUM_THREADS).

    • --procs starts its process pool once, outside the timed replicates.

    • A failing workload is recorded instead of aborting the run.

    • It imports torchspin before torch and records OMP_WAIT_POLICY.

Removed#

  • benchmarks/cluster/slurm_cpu.sh and slurm_gpu.sh, replaced by the array template. The CPU script’s thread sweep was mislabeled (see Fixed).

[0.6.7] — 2026-11-09#

Fixed#

  • Linear higher-order Zeeman terms (Sys.Ham1xx) had opposite signs in ham(Sys) and ham(Sys, B0) (all public releases, 0.3.0–0.6.6). The moment operators of ham(Sys) carried +dH/dB, but torchspin’s convention is H = H0 − μ·B, so the field-free decomposition (used by pepper’s resonance search, levels, endorfrq, salt, curry, nucfrq2d) had these terms with the opposite sign to ham(Sys, B0) and to the nuclear Zeeman interaction. Without nuclei this does not change spectra (time reversal); with nuclei it changed ENDOR and nuclear frequencies and forbidden-transition intensities. EasySpin’s ham.m has the same inconsistency; torchspin now deliberately deviates from it (see KNOWN_LIMITATIONS.md, “Higher-order Zeeman terms”).

  • hamsymm added the higher-order Zeeman Hamiltonian twice when probing for symmetry (ham(Sys, B0) already includes it).

  • SpinSystem(g=[2.0]) (a one-element list, which EasySpin treats like g=2) crashed ham with an IndexError; it now means isotropic g, like a scalar.

[0.6.6] — 2026-11-09#

Fixed#

  • Every cm⁻¹ conversion in unitconvert was off by a factor of 100 (in every public release, 0.3.0–0.6.5). CLIGHT is stored in cm/s, but the conversions multiplied it by 100 again, as if it were in m/s: unitconvert(1, 'cm^-1->MHz') returned 2 997 924.58 instead of 29 979.2458, and 1 cm⁻¹ came out as 143.9 K instead of 1.4388 K. This affected all eight cm^-1 conversions (to and from MHz, mT, K and eV) and the energy axis of levelsplot(..., Units='cm^-1'), which was 100× too small. The old test built its expected value with the same factor; the new tests compare against exact SI values (1 cm⁻¹ = 29 979.2458 MHz = 1.438 776 877 K = 1.239 841 984 × 10⁻⁴ eV).

  • curry docstring: wrong SI-to-CGS factor for the susceptibility. It said 1 m³/mol = 10⁶ cm³/mol; the correct relation is 1 cm³/mol (CGS) = 4π × 10⁻⁶ m³/mol, so SI values are converted to cm³/mol by multiplying by 10⁶/(4π). The values curry returns (SI) were always correct. The two magnetometry examples used the wrong factor too, so they printed CGS values 4π too large (a Curie constant of 4.71 instead of 0.375 cm³·K/mol for S = 1/2, g = 2); a new test checks χT = 0.375 cm³·K/mol.

[0.6.5] — 2026-11-09#

Fixed#

  • FitOptions(n_workers='auto') could start far more worker processes than the machine or job could hold. It meant one worker per core of the whole machine (os.cpu_count()), and every worker is a separate Python process with its own torch, about 0.3–0.5 GB before the model allocates anything. On a 224-core node that is over 200 workers and roughly 80 GB, even inside a SLURM job granted 16 cores and 8 GB. 'auto' now takes the smallest of:

    • the cores this process may use (CPU affinity, then SLURM_CPUS_PER_TASK);

    • 32 (more workers did not make fits faster in our measurements);

    • the workers that fit in half the available memory at 0.5 GB each, where available memory honors the cgroup limit of a SLURM job or container and the job’s SLURM memory request;

    • the number of tasks.

    An explicit integer is used as given. In a 16-core SLURM job, 'auto' now gives 7 workers with --mem=8G and 2 with --mem=3G.

Documentation#

  • README: how to launch the interactive fitting panel (torchspin.fitgui), and what n_workers='auto' costs in memory.

[0.6.4] — 2026-11-09#

Fixed#

  • The 0.6.3 thread fix did not apply when torch was imported before torchspin, the usual order in scripts (import torch first). The OpenMP runtime had already read OMP_WAIT_POLICY, so fits stayed slow with more threads. Now:

    • esfit’s process workers and torchspin.ml.simulate_batch workers always start with OMP_WAIT_POLICY=PASSIVE (unless the user set a value), since each worker loads its own runtime;

    • when it is too late for the current process (torch loaded first, variable unset, Linux, more than one torch thread), import torchspin warns once with the fix: import torchspin first, or export OMP_WAIT_POLICY=PASSIVE. See docs/pitfalls.md, “Threads and performance”.

[0.6.3] — 2026-11-08#

Fixed#

  • Fits got slower when threads were added on many-core Linux machines. After each parallel region torch’s OpenMP threads spin-wait, and a fit runs many small spectra, so the Python thread and torchspin’s worker threads competed with spinning threads for the cores. On a 224-core Linux node one fit-model call (nitroxide, GridSize 31×4) took 84 ms on 1 thread and 554 ms on 8; the 4-parameter levmar fit benchmark took 3.6 s on 1 thread and 11.0 s on 8. import torchspin now sets OMP_WAIT_POLICY=PASSIVE (idle threads sleep), which brings the 8-thread call to 93 ms. The OpenMP runtime reads the variable once, when torch loads, so this takes effect only when torchspin is imported before torch; an explicit user setting is never changed. See docs/pitfalls.md, “Threads and performance”.

    Measured with paired A/B runs (default vs PASSIVE, interleaved, pinned) on all 13 benchmark workloads at 1–64 threads, on a 224-core cluster node and a 64-core workstation. At 8 threads the 20-call fit loop went from 9.5 to 2.4 s and from 3.3 to 2.2 s, and the levmar fit from 13.2 to 4.1 s and from 5.8 to 3.4 s. No workload became measurably slower at any thread count.

[0.6.2] — 2026-11-08#

Bug fixes found while running the GPU tests on a CUDA host.

Fixed#

  • pepper on CUDA failed in every public release (0.3.0–0.6.1) with “Expected all tensors to be on the same device”. The transition pre-selection (_preselect_pairs) built its rate and mask tensors on the CPU, so every Options(device='cuda') call aborted before simulating. The CPU-vs-CUDA consistency tests catch this, but they only run on a GPU host.

  • pepper on CUDA ran out of memory on dense strain grids. Batched CUDA eigendecompositions went to cuSOLVER in a single call. The solver reserves about 1–2 MB of workspace per matrix whatever its size, so strain broadening (one 6×6 diagonalization per resonance) asked for tens of GB. CUDA batches are now split into chunks that fit in half the free GPU memory.

  • pepper on CUDA was up to 25× slower than on CPU. The resonance search finds cubic roots as eigenvalues of 3×3 companion matrices. On CUDA, torch computes general (non-Hermitian) eigenvalues one matrix at a time with a host sync each, hundreds of thousands per call: 34.7 s for the Mn(II) matrix workload against 1.4 s on 32 CPU threads. These small solves now run as one batched CPU call, the same LAPACK routine the CPU path uses.

  • pepper was not thread-safe. The slot keys of the matrix method were kept in a function attribute shared by the whole process. With concurrent pepper calls, such as esfit(..., FitOptions(workers='threads')) or any user thread pool, one call could read another’s keys: _filter_slots raised IndexError: list index out of range, or separate='transitions' mislabeled transitions. The keys are now per thread. This was found when a benchmark fit with the thread backend crashed on a single-core allocation.

  • sigeq(..., polarization=True) built its identity matrix on the CPU, so it failed with a device mismatch for a CUDA Hamiltonian.

Changed — behavior differs from 0.6.1#

  • Seeded cardamom results no longer depend on the thread count. The fast path groups orientations, and the group size scales with torch.get_num_threads(). Every group used to draw its trajectories from the same CardamomPar.seed, so a seeded spectrum changed with the number of threads, and orientations in different groups shared identical trajectories. Each orientation now draws from its own stream, derived from the seed with numpy.random.SeedSequence. The global-dynamics (DiffGlobal) trajectories of a group also started from a spiral grid over the whole group rather than over nTraj, which made the result depend on the group size too; they now start from the same per-orientation grid as the serial path. Seeded cardamom spectra differ from 0.6.1. Unseeded runs are unaffected.

Added#

  • DiffusionPar.seed and JumpPar.seed accept a sequence of per-block seeds: the trajectories split into equal blocks with independent random streams.

Tests#

  • The garlic CPU-vs-CUDA test compared the CPU with itself (garlic has no device path) and is removed. salt and sigeq have real CPU-vs-CUDA tests.

[0.6.1] — 2026-11-04#

Fixes for GitHub issues #5–#9. Each one was a case where torchspin returned a plausible result without any warning that it was wrong. Two more defects found while verifying them are fixed too: dict-style esfit ignored all but the last element of each array field, and pepper_autograd returned NaN gradients for an exactly isotropic A.

Changed — behavior differs from 0.6.0#

  • esfit autoscale='lsq' with a negative unconstrained scale (#6). The scale is now the sign-constrained least-squares optimum: 0, with the baseline refitted alone. EasySpin, and torchspin up to 0.6.0, took abs(scale) but kept the baseline solved for the opposite sign. That objective is not a least-squares fit, so optimizers walked away from the true minimum (an inversion-recovery fit with exp(-t/T) ran to its bound). esfit warns when the final fit has a negative scale. The old behavior is FitOptions(lsq_negative_scale='abs').

  • esfit uncertainties (#5). A parameter that has no effect on the residuals at the finite-difference step now gets pstd = nan and a warning, not pstd = 0, which read as a perfectly determined parameter.

  • pepper with inputs that require grad (#7) now returns a spectrum on the autograd graph by dispatching to pepper_autograd. It used to return a detached spectrum without any warning. Unsupported configurations raise an error that names pepper_autograd.

  • saffron with a predefined Sequence and nonzero Exp.tp (#9) now raises, as saffron.m 351 does, in every simulation mode. 0.6.0 meant to do this, but the check sat in the fast path, and nonzero tp routed to the real-pulse engine first. Its predefined templates use fixed 16/32 ns pulses and never read Exp.tp, so the requested pulse lengths were silently ignored.

Fixed#

  • Dict-style esfit fitted only the last element of each array field. TorchSpinParameterHandler.to_dict rebuilt each element from the original p0, so varying g[0,0], A[0,0] or lw[0] never reached the simulator. Present since 0.3.0.

  • esfit was blind to line positions with garlic’s default AccumMethod='binning' (#5). The binned spectrum is piecewise-constant in g and A, so every finite-difference Jacobian was zero for them and levmar never moved A. Dict-style esfit now runs garlic with 'linear' when AccumMethod is unset. levmar, trf and the uncertainty estimate warn when a Jacobian column is dead, which also covers custom models that wrap garlic.

  • esfit baselines with autoscale='none' and 'maxabs'. 'none' fitted the baseline jointly with a free scale and then applied it at scale 1. 'maxabs' built scale * x**sum(arange) and not a polynomial. Both now fit the polynomial to the data minus the scaled model.

  • pepper_autograd and natural-abundance nuclei (#7). Nucs=['Zr'] failed in nucdata. Components are now expanded into isotopologues and summed with Sys.weight × abundance, as in pepper. Sys.weight was previously ignored, and lists of components are accepted.

  • Quadrupole shorthand [e2qQ/h, eta] dropped the graph (#7). It was converted with float(), so dL/dQ was silently zero in a fit. The principal values are now built with torch ops.

  • NaN gradients in pepper_autograd’s axial-grid interpolation. When a transition slot was missing at some orientations (e.g. exactly isotropic A), torch.where’s backward computed 0·NaN. The forward output is unchanged.

  • The preselection cutoff no longer triggers PyTorch’s “converting a tensor with requires_grad=True to a scalar” warning.

Added#

  • spidyan warnings (#8) for a user-set IntTimeStep coarser than Nyquist/2 (a π pulse is ~3 % off there and 40 % at Nyquist), and for SimFreq less than 5 nutation frequencies below the lowest pulse carrier.

  • docs/pitfalls.md (#8): perturbation errors at large A/ν (measured on ⁹¹Zr, A/ν = 0.08), binned garlic spectra in fits, the lsq sign, satellite-assignment minima, Q fits started at zero, and the pulse-simulation limits.

  • examples/fitting/large_hyperfine_fit.py: a staged fit of a synthetic natural-abundance Zr spectrum.

  • torchspin.autograd.inputs_require_grad.

Fixed — a flaky tolerance in the real-pulse frame-rotation test#

test_frame_tilts_match_an_equivalent_sample_tilt asserted that a tensor tilt and an equal sample tilt agree to 1e-12 of the peak, copying EasySpin’s own areequal(y1, y2, 1e-12, 'abs'). That bound sits below the round-off floor of torchspin’s route, which conjugates the Hamiltonian into the lab-frame basis rather than rotating the interaction tensors: the two Hamiltonians agree to 2e-16 relative, but integrating that over the 0.3 µs detection window makes a phase error growing linearly in time, 2e-11 absolute on a signal of magnitude 12. The test passed on two CI runners and failed on a third with identical code. It is now scored as a relative L2 error (measured 1.8e-12 against a 1e-9 bound) plus a per-point bound at 1e-9 of the peak, and the mechanism is written down in the docstring and in KNOWN_LIMITATIONS.md. Library code is unchanged; both sides remain validated against MATLAB at ~1e-12.

0.6.0 — 2026-10-19#

Follow-up to 0.5.0: the pulse-EPR test suites now assert the relative L2 error against MATLAB rather than a cosine similarity, the one physics issue 0.5.0 left open turned out not to be a physics issue, and the real-pulse (saffron_thyme) route — the last pulse-EPR route with no cross-validation at all — is now EasySpin-equivalent and MATLAB-validated on 28 cases. Every saffron route, ideal-pulse and real-pulse, rectangular and shaped, is now cross-validated against MATLAB EasySpin.

Minor rather than patch: the real-pulse route’s output changes (it was not reproducing EasySpin before), and one input that used to be accepted now raises. A predefined sequence with a nonzero Exp.tp was answered with a silent ideal-pulse result; it now raises, as in saffron.m 351. Scripts relying on that fallback were getting a wrong answer, and need either Exp.tp = 0 to keep the ideal-pulse result or a list-valued Exp.Sequence to get the real-pulse one.

Fixed — the real-pulse saffron route now reproduces EasySpin#

Two new oracles, 28 MATLAB cases in all (MATLAB R2024b), agreeing on both the raw and the mean-centered signal at 3e-13..8e-12:

  • tests/data/generate_saffron_thyme_refs.m → torchspin/tests/test_saffron_thyme_matlab_validation.py (18 cases, rectangular pulses): powder and single-crystal samples, transient and single-point detection, echo integration, detection phase, explicit simulation frame, relaxation, one and two indirect dimensions, and predefined 2pESEEM / 3pESEEM / HYSCORE run through the real-pulse engine.

  • tests/data/generate_saffron_thyme_shaped_refs.m → torchspin/tests/test_saffron_thyme_shaped_matlab_validation.py (10 cases, transcribed from EasySpin’s own tests/saffron_thyme_*.m): quartersin/ linear chirps with Pulse.trise and a swept Pulse.Frequency, relaxation during a chirp, Opt.SimFreq = 15 against the automatic 32 GHz, a delay sweep crossed with a pulse-parameter sweep (Exp.Dim2 = {'p1.Flip' pi/3}, which regenerates the chirp at every point), Sys.gFrame/Sys.AFrame tensor tilts against an equivalent sample tilt, and a predefined sequence detected over a transient window.

Shaped pulses needed no new code: torchspin/pulse.py already built them for spidyan, and a pulse dict in a list-valued Exp.Sequence passes through to it unchanged. What had kept EasySpin’s own thyme cases from running was the propagation and detection, below.

0.5.0 reported that this route “does not reproduce EasySpin and has a different output contract”, and that no reduction of its per-increment transients recovered EasySpin’s trace. That was correct, and the cause was not only the missing detection stage: the propagation was wrong too. Six separate problems, each of which alone makes the comparison meaningless:

  • The pulses were never given a carrier. Exp.mwFreq was not passed to the sequencer, so FrameShift was 0 and every pulse was built as a DC envelope and applied in the lab frame, against an electron Zeeman term of ~9.5 GHz. Nothing was excited. Exp.mwFreq is now required, as in EasySpin’s s_sequencer, and the simulation frame is entered by the same isotropic g shift EasySpin uses (saffron.m 1838-1846).

  • The Hamiltonian and the operators were in different frames. The Hamiltonian was built in the molecular frame with the field rotated into it, while the initial state (-Sz), excitation (Sx) and detection (S+) operators stayed lab-frame. Any orientation with a nonzero phi angle was therefore wrong, and rotating the operators instead is not an option because s_thyme builds its pulse propagators from real(xOp) and 1i*imag(xOp), which presumes xOp = Sx. The Hamiltonian is now transformed into the lab-frame basis with the spin-rotation operator exp(-i*phi*Jz) exp(-i*theta*Jy) exp(-i*chi*Jz) over all spins, which is the same operator EasySpin’s rotatesystem + ham(Sys_L, [0 0 B]) produces (agreement 5e-13) without needing per-interaction tensor rotation.

  • The orientation sum was renormalized. EasySpin sums over orientations weighted by Exp.OriWeights and does not divide by the total weight, which is 4*pi. Dividing by it scaled a powder down by ~12.6 and turned a multi-site crystal stack into a mean instead of a sum.

  • The whole detection stage was missing (saffron.m 1884-1940): Exp.DetPhase, Exp.DetIntegrate echo integration, down-conversion through signalprocessing.m and the Exp.DetWindow time axis. Exp.DetWindow is applied the way EasySpin applies it, by shifting the last sequence element by DetWindow(1) and appending the detected event — a zero-length one for single-point detection — rather than by slicing the transient afterwards, which would move the echo rather than the window. The output contract is now EasySpin’s: one detected point per increment for single-point detection, and the transient axis appended to the indirect axes otherwise.

  • Opt.IntTimeStep’s default did not match. EasySpin takes the Nyquist time of the highest simulation-frame frequency, divides by 50 and rounds to two significant digits; torchspin divided by 10 and did not round. The two codes therefore integrated with different steps whenever the step was left implicit.

  • A zero-length detected delay produced no signal, so EasySpin’s way of expressing single-point detection yielded an empty trace.

Fixed — relaxation propagated conj(rho) in Liouville space#

spidyan’s Liouville-space commutator superoperator was written as EasySpin writes it, kron(I,H) - kron(H.',I), which is correct for MATLAB’s column-major vec(). numpy flattens row-major, where vec_r(A@rho@B) = kron(A, B.T) @ vec_r(rho), so the two Kronecker factors swap. With EasySpin’s order the relaxation path propagated rho.T, which for a Hermitian density matrix is conj(rho). The same applies to the transform of the relaxation superoperator into the Hamiltonian eigenbasis.

This affects spidyan and the real-pulse saffron route whenever relaxation is active. A real detection trace (Sz) is untouched, which is why the existing spidyan relaxation reference — Exp.DetOperator = {'z1'}, compared on its real part only — could not see it; a demodulated S+ trace was wrong by a factor of several. generate_spidyan_refs.m gains case 8, spidyan_relaxationcomplexdetection.mat, which detects S+ under relaxation and is compared on its imaginary part as well as its real part. Regenerating the other seven spidyan references reproduced the committed files bit for bit.

Added — Exp.Det* fields and Opt.SimulationMode on saffron#

PulseExperiment gains DetWindow, DetSequence, DetPhase, DetFrequency, DetIntegrate and DetOperator, plus Dim1, Dim2 and PhaseCycle and support for a list-valued Exp.Sequence (EasySpin’s general pulse syntax: pulse dicts and delays). SaffronOptions gains SimulationMode ('fast' | 'thyme'), IntTimeStep and SimFreq.

Engine selection now follows EasySpin: Opt.SimulationMode chooses explicitly, and leaving it unset keeps torchspin’s inference from nonzero Exp.tp, a list-valued Exp.Sequence or an Exp.DetWindow. The fast algorithm raises EasySpin’s errors rather than ignoring the input: a predefined sequence with nonzero Exp.tp is rejected (saffron.m 351) where torchspin used to ignore Exp.tp and silently return an ideal-pulse result, and Exp.DetSequence/Exp.DetOperator are rejected (saffron.m 303). The real-pulse engine warns about the fast-only fields it ignores, as EasySpin’s s_sequencer reports them.

Fixed — misleading NotImplementedError for multi-electron saffron#

saffron.py told users to set Opt.SimulationMode='thyme' for multi-electron systems, an option SaffronOptions did not have. The option now exists, and the message says what else is needed (a finite length for every pulse).

Not changed — the ideal-pulse and real-pulse routes do not converge#

The plan this work followed expected that as Exp.tp -> 0 the real-pulse result would approach the ideal-pulse result for the same sequence, as a reference-free check on the normalization. It does not, and that is EasySpin’s behavior too: at matched settings torchspin reproduces EasySpin’s own ideal-vs-real mismatch to 1e-7 in scale (measured at four pulse lengths from 20 ns down to 2.5 ns), so there is nothing here for torchspin to fix. Three reasons, none of them a defect:

  • With single-point detection EasySpin does not down-convert, so the detected point carries the simulation-frame carrier phase, which advances ~50 cycles per 20 ns increment.

  • A single detected point contains coherence pathways that the ideal route excludes analytically; the two-step cycles EasySpin’s own templates use do not remove them for this observable.

  • As tp -> 0 at fixed flip angle the required B1 grows without bound and eventually exceeds the carrier frequency, so the rotating-wave picture breaks down and a rectangular real pulse does not approach an ideal one.

Putting the simulation frame on the carrier to remove the first effect is not a neutral change: it removes the carrier from the pulse too, so the linearly polarized field becomes a rotating-frame field of twice the strength.

What that check was reaching for is covered instead by three relations that need no reference and do hold: 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, which is the sharpest cheap guard against the pulse amplitude slipping by a factor of two.

Changed — spidyan’s default detection, and Exp.DetSequence strings#

With neither Exp.DetWindow nor Exp.DetSequence given, _sequencer used to detect only the last free evolution event. EasySpin’s documented default is Exp.DetSequence = ones(1, length(Exp.Sequence)) — detection active during the entire sequence — and that is now what happens. Calls that state their detection explicitly, which is every cross-validated case, are unaffected. Exp.DetSequence also accepts EasySpin’s 'last' and 'all' strings, and a length that is neither 1 nor length(Exp.Sequence) now raises instead of being silently truncated.

Fixed — rfmixer could drop the last sample#

The output time axis was built with np.arange(t[0], t[-1] + dt/2, dt) and then clipped to t <= t[-1], so floating-point round-off in the last step could discard the final point and return a signal one sample shorter than its input. MATLAB’s tIn(1):Opt.dt:tIn(end) does not, and the axis is now built from a step count.

Fixed — the “spidyan multi-spin phase drift” was a test transcription error#

0.5.0’s KNOWN_LIMITATIONS reported an undiagnosed residual in spidyan that grew linearly through free evolution for multi-spin systems (4.7e-3 for two coupled electrons, 6.4e-5 electron-nucleus, 8.8e-6 for S=3/2), and warned that it would be worse for longer sequences. There is no such defect.

Fitting the accumulated phase showed torchspin reproducing the analytic Larmor frequency exactly (1489.828541 MHz at 1195 mT, g = 2.00232, in the 32 GHz simulation frame) while the MATLAB reference sat 11.6 kHz below it. That offset is (2.00232 - gfree)/2.00232 = 3.47e-7 of the full Larmor frequency: generate_spidyan_refs.m sets Sys.g = gfree (2.0023193043…), and the Python tests had transcribed it as a rounded 2.00232. A 3.5e-7 error in g shifts the precession frequency enough to accumulate visibly as phase over a 0.5 us delay.

The three affected tests are exactly the three whose generator uses Sys.g = gfree; the cases that set Sys.ZeemanFreq were unaffected and had always agreed to 1e-13. With GFREE used in place of the rounded value, every spidyan case agrees to 1e-14..1e-12. No library code changed.

Changed — pulse-EPR tests assert relative error, not cosine#

test_spidyan_matlab_validation.py, test_spidyan_tp_matlab_validation.py and test_saffron_matlab_validation.py now assert the relative L2 error against the MATLAB reference (STRICT_TOL = 1e-8 and 1e-6 respectively) instead of cosine > 0.85..0.99. A cosine is scale-invariant and dominated by a pulse-EPR trace’s DC offset, so it could see neither the eight defects fixed in 0.5.0 nor the gfree rounding above.

Making them strict required fixing three kinds of harness fault that a cosine had been hiding. None was a library fault – checked against matched references, agreement is 1e-16..1e-7 in every case:

  • Accumulation path. No saffron reference generator sets Opt.TimeDomain, so every reference comes from the frequency-binned path, but twelve tests ran with TimeDomain=True. That compares direct time evolution against EasySpin’s own binned approximation – a 7-60% difference in the modulation that is real, expected, and nothing to do with correctness.

  • Normalization. Six generators write y = y/max(abs(y)); the tests compared torchspin’s unnormalized output against them, leaving fixed scale factors of ~4*pi and similar.

  • Orientation grid. saffron_hyscore14n and saffron_hyscore_ganiso are generated at Opt.GridSize = 181 but were tested at 91, and saffron_2psimple is generated at EasySpin’s default 31 but was tested at 20. GridSize is now stated explicitly in every case rather than inherited from a default that could drift apart between the two codes.

test_orientation_selective documents a measured case where the committed fixture is stale: regenerating it from the local EasySpin gives a reference torchspin matches to 4.4e-15, and that fresh reference differs from the stored one by 1.4e-6 in overall scale. Its amplitude is therefore checked at 1e-5 with the peak-normalized shape checked strictly, rather than silently loosening everything.

The dead cosine helpers are removed, and the tests no longer carry a _cosine suffix that would misdescribe what they assert.

0.5.0 — 2026-10-19#

Found while cross-validating saffron against MATLAB EasySpin on a 13C HYSCORE model, where the modulation came out wrong although the raw cosine stayed at 0.99999. The existing saffron suite scored agreement with a cosine similarity, which for a pulse-EPR time trace is dominated by the DC offset: a HYSCORE trace can have a ~100% wrong modulation and still score >0.999. Every defect below lived in that blind spot.

New oracle: tests/data/generate_saffron_phase_refs.m → torchspin/tests/test_saffron_phase_matlab_validation.py (25 cases, MATLAB R2024b), plus a strict spidyan amplitude case. It asserts the mean-centered relative L2 error — the modulation — as well as the raw error, at tolerances near double-precision roundoff. All 26 strict cases, 25 of them fail on 0.4.0 and pass here (the 26th, two-nucleus Mims ENDOR, is the one case 0.4.0’s hardcoded EndorMethod=1 got right). Agreement across the predefined 2p/3p/4pESEEM, HYSCORE and Mims-ENDOR routes, direct and frequency-binned, powder and explicit single crystal, S=1/2 and S=3/2, with and without orientation selection and nuclear quadrupole coupling, is now 1e-16 to 1e-14 rather than “cosine ≥ 0.98”.

Fixed — saffron tau phase factor in all four predefined ESEEM/HYSCORE routes#

saffron.m builds the tau-dependent phase factor as Q_ = exp(-2i*pi*Ea*tau)*exp(-2i*pi*Eb*tau)', and MATLAB’s ' is a conjugate transpose, so element (i,j) is exp(-2i*pi*(Ea_i - Eb_j)*tau) — a difference of the two manifold energies. torchspin formed the outer product without conjugating the second factor, giving their sum. The error vanishes at tau = 0, which is why it survived.

Fixed for exp_id 1, 2, 3 and 4 (2pESEEM, 3pESEEM, 4pESEEM, HYSCORE); the Mims-ENDOR branch already conjugated correctly. On the in-repo saffron_HYSCORE.mat case (tau = 0.08 µs) the mean-centered error against MATLAB drops from 112% to roundoff, while the raw cosine moves only from 0.999991 to 1.000000.

Fixed — saffron alpha/beta manifold assignment for S=1/2#

EasySpin’s Transitions = [1 2] makes Ea the upper manifold (<S> = +1/2·n) and Eb the lower. The S=1/2 fast path had them swapped, while torchspin’s own S>1/2 path assigned them correctly — an internal inconsistency. Invisible while the nuclear Hamiltonian is linear in I (the two HYSCORE coherence-transfer pathways then symmetrize the swap away), it becomes a 7–33% error as soon as a nuclear quadrupole makes the manifold eigenvectors non-trivial.

Fixed — saffron dimension order of the 2D frequency-bin accumulation#

sf_peaks.c bins a 2D spectrum at idx = nu1 + nu2*nPoints1, i.e. dimension 1 carries nu1. saffron_peaks.py computed idx2 * n_points1 + idx1 into a row-major (n_points1, n_points2) buffer, which transposes the spectrum and mis-strides it when the two dimensions differ in length. Fixed at all five 2D increment schemes (11–15, 17). The binned and direct paths of torchspin itself disagreed by 2% before this; a new test asserts they agree, which catches this class of bug without any MATLAB reference.

Fixed — saffron Opt.OriThreshold reference level under orientation selection#

EasySpin takes the pruning threshold from the unweighted |<i|SyLab|j>| maximum and only then multiplies in the excitation amplitude, so a narrow Exp.ExciteWidth discards more transitions. torchspin took the maximum after excitation weighting and so kept transitions EasySpin drops, giving a 75% modulation error for S=3/2 + 14N at ExciteWidth = 100 MHz. Affects S>1/2 with Exp.ExciteWidth only.

Fixed — saffron Opt.Expand and Opt.EndorMethod defaults are conditional in EasySpin#

Both were hardcoded to a single value, so the default-argument path silently ran a different algorithm than EasySpin:

  • Opt.Expand defaults to 4 for 1D and 2 for 2D sequences (saffron.m:751); torchspin always used 4, changing the zero-fill of every binned HYSCORE.

  • Opt.EndorMethod defaults to 0 for a single SHF nucleus or under ProductRule, else 1 (saffron.m:729); torchspin always used 1, which selects a different RF-pulse model. For one nucleus this put the ENDOR amplitude 40% out and changed the lineshape, at cosine 0.996.

Both now accept None (the default) to mean EasySpin’s rule; an explicit integer still overrides it.

Fixed — saffron/saffron_thyme treated Exp.SampleFrame alone as a single crystal#

EasySpin decides sample type from CrystalSymmetry or MolFrame only (p_sampletype.m:26): Exp.SampleFrame rotates the sample, but a disordered powder stays a powder. saffron and saffron_thyme also keyed on SampleFrame, so SampleFrame alone silently simulated a single crystal where EasySpin simulates a powder — a different physical sample, not a numerical discrepancy. pepper already had this right; saffron now matches it. Code that relied on SampleFrame alone to select a crystal must now pass CrystalSymmetry (e.g. 'P1') or MolFrame, as EasySpin requires.

Fixed — saffron custom sequences were not divided by their pathway prefactor#

For a user-defined sequence (Exp.Sequence given as pulses and delays, not a predefined name) saffron.m:1669 divides the signal by the largest surviving pathway prefactor. torchspin omitted this, leaving a custom HYSCORE-style sequence a factor of 8 too small. Shape was unaffected, so the cosine was 1.000000 and the existing cosine > 0.95 test passed. Predefined sequences are deliberately not renormalized this way, and are unchanged.

Fixed — spidyan complex detection operators were half amplitude#

signalprocessing.m multiplies a complex detection trace (S+/S-) by two when it is demodulated, because the analytic-signal normalization is otherwise off by that factor; a purely real or purely imaginary trace (Sz) is left alone. torchspin applied the demodulation phase but not the factor, so a demodulated <S+> channel came out at exactly half EasySpin’s amplitude — at cosine 1.000000, under a cosine >= 0.99 assertion. The <Sz> channel in the same simulation was already correct, which is why it went unnoticed.

Audit of the remaining pulse-EPR routes#

Prompted by the above, the routes that were scored only by cosine were re-checked against fresh MATLAB references with strict metrics. Now at roundoff and covered by tests: custom user sequences (direct and binned), ProductRule x TimeDomain for two nuclei (all four combinations), multi-component input with Sys.weight, and S=1 systems.

Several apparent discrepancies turned out to be test-harness faults rather than library faults, and are worth knowing about before trusting an old number: test_3psimple, test_4psimple, test_hyscore14n, test_hyscore_ganiso, test_mimssimple and test_twocomponents compare torchspin’s unnormalized output against a MATLAB reference its generator had normalized (y = y/max(abs(y))), so they sat at a fixed scale factor of 4*pi or similar; and test_saffron_2pESEEM, test_saffron_3pESEEM, test_saffron_HYSCORE_cosine_1d, test_S1_*, test_S32_HYSCORE, test_orientation_selective and test_customsequence run with TimeDomain=True against references generated without Opt.TimeDomain, i.e. they compare direct time evolution against EasySpin’s own frequency-binned approximation. Both faults are invisible to a cosine. Checked against matched references, the library agrees to roundoff in every one of these cases.

Still open, and recorded in KNOWN_LIMITATIONS.md:

  • ~~spidyan multi-spin systems show a small residual that grows linearly through free evolution — a phase drift of order 1e-5 relative — for two coupled electrons (4.7e-3 overall), an electron-nucleus pair (6.4e-5) and S=3/2 (8.8e-6). Single-electron cases are exact to 1e-13. Not diagnosed.~~ Retracted — there is no such defect. This was a test transcription error (the tests rounded EasySpin’s gfree to 2.00232); torchspin reproduces the analytic Larmor frequency exactly. See [Unreleased]. The claim is struck through rather than deleted because 0.5.0 shipped with it.

  • saffron with real pulses returns per-increment transients (nPoints x nDet x nTime) where EasySpin returns one detected point per increment, and no simple reduction of those transients recovers EasySpin’s trace — the closest is ~3% off after fitting an arbitrary scale. Treat the real-pulse route as unvalidated; saffron_thyme remains without MATLAB cross-validation.

  • saffron accepts a predefined Exp.Sequence together with real pulses (Exp.tp) and silently routes it to the thyme engine; EasySpin rejects that combination outright. The output is therefore unvalidated.

  • EasySpin’s shaped/chirped pulses (Type, trise, Frequency), Exp.DetWindow/DetPhase and Opt.SimulationMode are not implemented in saffron_thyme, so EasySpin’s own thyme test cases cannot be run against it.

Note#

saffron gradients are unaffected in form: a finite-difference check against the corrected simulator at nonsymmetric hyperfine values agrees to 1e-10. Gradients taken before this release were consistent with the old, incorrect forward model.

0.4.0 — 2026-10-09#

Found by fitting a Cu(II) phthalocyanine spectrum (CuPc in ZnPc: S=1/2, A∥(Cu) ≈ 647 MHz, four equivalent 14N) — a system that hit every limit of pepper’s resonance solvers at once. Every change below is validated against EasySpin on MATLAB R2024b through a new 34-case oracle, tests/data/generate_pepper_cupc_refs.m → torchspin/tests/test_pepper_cupc_matlab_validation.py, covering all three solvers on the same systems plus natural-abundance isotopologues, tilted and anisotropic ligand A tensors, nuclear quadrupole coupling, an enlarged exact core, and a two-component model.

Added — Options.Method='hybrid' (EasySpin Opt.Method='hybrid')#

Exact diagonalization of a core — all electron spins plus the nuclei named in the new Options.HybridCoreNuclei (1-based, as in EasySpin) — with the remaining nuclei shifting and splitting the core lines. This is the method for a large central hyperfine coupling surrounded by small ligand couplings, where the exact treatment is unaffordable and perturbation theory is wrong about the central coupling. Cu + 4×14N needs a 648-dimensional Hilbert space exactly, which neither code can put in a fit loop; as hybrid the core is 8-dimensional and each nitrogen is a 3×3 problem, and the spectrum takes 0.27 s against EasySpin’s 0.28 s.

The implementation follows resfields.m: the electron spin operators in the hyperfine term are replaced by their expectation values in the two core eigenstates at the resonance field, and the resulting nuclear sub-Hamiltonian is then diagonalized exactly, so the quadrupole and nuclear Zeeman terms and the nuclear state mixing are not approximated. Line amplitudes come from the Mims overlap matrix |⟨u_r|v_c⟩|², sub-lines below Options.HybridIntThreshold (0.005, as EasySpin) are dropped, and the nuclei are combined by an outer sum of shifts and an outer product of amplitudes. Matches EasySpin’s hybrid to cosine 0.9998 on every case.

Against the exact matrix result hybrid reaches cosine 0.9805 (Cu + 1×14N) and 0.9740 (Cu + 2×14N). EasySpin’s own hybrid gives 0.982 and 0.974 on the same comparison — that gap is the method’s first-order decoupling, not a port defect. Second-order perturbation theory gives 0.896 and 0.918 on the same systems. See § Pepper in KNOWN_LIMITATIONS.md for when to use which.

Added — pepper supports sets of equivalent nuclei#

SpinSystem.n > 1 now works on the hybrid and perturb paths, which treat nuclei one at a time and combine them combinatorially, so a multiplicity is a pure saving rather than an obstacle: four equivalent 14N written as n=[1,4] take 0.30 s instead of 2.0 s and agree with four explicit nitrogens to cosine 0.99999999. A set of n equivalent nuclei shares one sub-Hamiltonian, so its copies are combined once by multiset enumeration — for four 14N that is 495 combinations instead of 9⁴ = 6561.

The matrix path still rejects n > 1, since there the nuclei multiply the Hilbert space and cannot be collapsed. EasySpin’s pepper rejects n > 1 for every method, so this goes beyond it.

Fixed — Method='matrix' crashed on highly degenerate systems#

pepper(Sys, Exp) on S=1/2 Cu + 4 equivalent 14N aborted with torch._C._LinAlgError: linalg.eigh: (Batch element 5): The algorithm failed to converge … too many repeated eigenvalues (error code: 394590) after 13 s. One matrix out of a batch of 59 complex 648×648 Hermitians: the input is Hermitian to 0.0 and finite, but LAPACK’s divide-and-conquer driver stalls on the hundreds of exactly equal eigenvalue gaps that four identical nuclei produce.

_linalg.eigh and _linalg.eigvalsh had no error handling, so one bad matrix killed the whole orientation batch. They now retry a rejected batch matrix by matrix — the torch routine alone, then NumPy (a different LAPACK build, and zheevr/zheev rather than divide-and-conquer), then a 1e-14 relative diagonal perturbation that breaks the exact ties. Spectra are invariant under unitary rotations inside a degenerate subspace, so none of these changes the result beyond round-off. On the autograd path the NumPy detour is skipped, because it would silently drop gradients.

Fixed — Options.IsoCutoff had no effect#

expand_components passed the cutoff as the second positional argument of isotopologues, which is n, so it was silently discarded and pruning always used the 1e-4 default. Affected pepper and garlic. No test caught it because every test passed rel_threshold by keyword.

Fixed — the perturbation path built a Hamiltonian it never used#

pepper built the full H0/mux/muy/muz operators before dispatching on Options.Method, but resfields_perturb_batch works from the spin system and never receives them. For Cu + 4×14N that is a 648×648 Kronecker product costing about 80 % of the run time, repeated for every isotopologue — which is why the cost barely depended on GridSize. They are now built on first use. Natural-abundance Cu + 4×N at [91,4] goes from 2.70 s to 0.41 s, now faster than EasySpin’s 0.71 s, with bit-identical output (verified on 14 systems spanning both solvers, strain broadening and multi-component input).

Fixed — Options.Method accepted perturbation orders pepper cannot run#

'perturb3', 'perturb4' and 'perturb5' were accepted and silently run as second order, and the requested order was never passed to the solver at all, so 'perturb1' also ran second order. pepper now rejects the orders it does not implement and forwards the order it does, and the Options.Method docstring describes the methods per simulator instead of claiming 'perturb' means fifth order everywhere (that is garlic’s convention; pepper’s 'perturb' is second order, as in EasySpin).

Fixed — two examples did not compute what they claimed#

examples/solidstate/copper_nitrogens.py was titled “Four Equivalent 14N Ligands” and labelled its plot “4×14N” while simulating two, and had dropped the AFrame tilts that make the four nitrogens inequivalent in the first place. It is now the system from the EasySpin original (Buchanan & Dismukes 1987) and shows perturb against hybrid. examples/solidstate/matrixperturb.py ran the matrix method twice, labelled one curve “perturb”, and carried a comment claiming perturbation theory “is not yet exposed as a pepper option in torchspin” — untrue since 0.2.x. It now calls Method='perturb'.

Fixed — concurrent eigendecompositions could corrupt the thread count#

_linalg._pooled and pool_map save, set and restore torch.set_num_threads, which is process-global. esfit evaluates objective functions in a thread pool, so two concurrent batches could interleave and leave the process pinned at one intra-op thread for the rest of the session. Both now hold a lock across the critical section.

Added — grid_convergence, to answer whether Options.GridSize is enough#

The default GridSize=[19,4] is badly unconverged for a narrow line on a large hyperfine coupling — for the reported Cu(II) case the derivative peak is 3 % out at [19,4] and still moving 4 % between [91,4] and [361,4], in EasySpin equally — and a single spectrum gives no hint of it.

torchspin.grid_convergence(sys, exp, opt) simulates again on a refine× finer coarse grid and reports the cosine and amplitude change, with .converged against tolerances a tenth of the repository’s parity bar, and .report() giving a sentence that names a grid to use.

A heuristic was tried first and deliberately abandoned: comparing the field step between knots against the linewidth sounds right, but the SOPHE projection integrates analytically over each grid segment, so a large step per knot is normal and harmless. That heuristic flagged ~60 simulations in this repository’s own suite which agree with EasySpin to cosine 0.9999. A check that cries wolf on validated-correct cases is worse than none, so the honest version costs a second simulation and is opt-in rather than a warning inside pepper.

Fixed — torchspin.fitgui now says which extra to install#

FitPanel(...) failed with a bare ModuleNotFoundError: No module named 'ipywidgets' and no hint that an optional dependency group provides it. The imports now raise an ImportError naming the module, what it is needed for, and pip install "torchspin[gui]".

The gui extra was also incomplete: it omitted ipython, which FitPanel.show() needs, and cloudpickle, which the panel’s own n_workers control needs. Both are now in it, and ipywidgets is in test and dev so the four test_fitgui.py tests run instead of skipping.

Fixed — vary could put a linewidth or a weight below zero#

vary becomes p0 ± vary, so Vary.lw = 1 around lw = 0.54, or Vary.weight = 0.2 around weight = 0.001 — both taken from a real fit script — handed the optimizer a negative lower bound for a quantity that cannot be negative. In the dict style the field name is known, so the lower bound is now clipped at zero for lw, lwpp, lwEndor, HStrain, gStrain, AStrain, DStrain, weight, tcorr, Diff, T1 and T2, which is what EasySpin’s esfit does (nonnegFieldNames). Explicit lb/ub are still used exactly as given — clipping a bound the user stated would be worse than the problem.

A plain parameter vector carries no field names, so neither esfit nor FitSession can clip there, as in EasySpin; both docstrings now say so and point at lb/ub.

Fixed — eprload units are now documented where they bite#

eprload returns the abscissa in the file’s own units, so a Bruker field axis is in gauss while the rest of torchspin works in mT. That is deliberate and matches EasySpin, and it was recorded in KNOWN_LIMITATIONS.md — but the eprload docstring said only “Abscissa (magnetic field, time, frequency, etc.)”, which is where a user actually looks before feeding the axis straight into Experiment.Range. The docstring now states the units per format, shows the / 10 conversion in a worked example, and notes that the file’s own unit string survives in params.

eprload_info now prints the unit and, for a gauss axis, that it needs dividing by 10 (it also no longer crashes on multi-dimensional data, where x is a list of axes and y can be a list of datasets).

Documented — derivative amplitude at a turning point is grid-limited#

Investigated because it first looked like a parity defect of the exact solver, and turned out not to be one. Comparing Cu + 1×14N by matrix against EasySpin at GridSize=[91,4] gives cosine 0.99948 but amplitude 0.990, and 0.978 at two nitrogens — outside the 2 % amplitude convention. Refining the grid removes it: 0.9903 → 0.9978 → 1.0010 and cosine 0.99948 → 0.99998 → 1.00000 over [91,4] → [181,4] → [361,4].

Neither code is converged at [91,4]: EasySpin’s own derivative peak moves 53.70 → 51.62 → 51.44 across the same refinement, a 4 % change in its own answer. The two are simply unconverged by slightly different amounts. The derivative extremum at a turning point is the most grid-sensitive quantity in a powder spectrum, much more so than the integrated intensity.

Absolute intensity agrees throughout, including with nuclei: integrated absorption against EasySpin is 578.38/578.38, 559.77/559.90 and 535.49/534.99 for 0, 1 and 2 nitrogens (0.02–0.09 %), and absorption peak heights agree to 0.2–0.8 %. That the integral falls as nuclei are added is real but EasySpin does the same to 0.1 % — it is the matrix method’s transition pre-selection dropping weak transitions, and both codes select exactly the same number of level pairs (60 and 215). hybrid and perturb hold at 578 because they put all the nuclear intensity on the core lines.

The two cupc_*_2N_matrix cases are kept at [91,4] with the amplitude tolerance set to the measured grid error, as the regression anchor for this.

Added — benchmarks/python/cupc_claims.py#

Reproduces the five reported defects and records the measured before/after state, so the performance claims have a ledger rather than an anecdote.

0.3.0 — 2026-10-04#

First public release.

Fixed — NumPy 2.0 and case-sensitive filesystems (2026-10-04)#

Found by installing the release into an empty environment on a machine that had never run torchspin (NumPy 2.5, SciPy 1.18, PyTorch 2.14, Linux). All three were silent on the development hosts and broke 26 tests on the clean one; none changes any numerical result.

  • pepper partial ordering (Exp.Ordering) raised AttributeError: module 'numpy' has no attribute 'trapz' on every call under NumPy >= 2.0, which removed np.trapz. torchspin/ordering.py now uses np.trapezoid through the same fallback shim already used in torchspin/pulse.py and torchspin/exponfit.py. The 10 MATLAB-validation cases for ordering (test_pepper_features2_matlab_validation.py, test_pepper_round3_matlab_validation.py) were failing on this alone and now pass — the ordering physics was never in question.

  • eprload could not open Bruker ESP/WinEPR data on a case-sensitive filesystem: a FOO.SPC file was paired with a hard-coded FOO.par, so the real FOO.PAR was reported missing. The companion-file probe that the BES3T loader already had is now a module-level _find_companion used by both loaders.

  • Three saffron tests called float() on the shape-(nNuclei,) array returned by larmorfrq, which NumPy 2.0 rejects; they now take the element explicitly.

Added — esfit method='trf' (2026-09-09)#

  • esfit: FitOptions(method='trf'), SciPy’s bounded trust-region reflective least squares on esfit’s target-transformed residual vector. Parameter mapping (dict/array p0, fixed parameters, lb/ub/vary), amplitude and baseline fitting (autoscale/baseline), target, progress reporting and max_time/stop_when/interrupt handling are shared with the other methods. New options: trf_diff_step (relative finite-difference step, SciPy diff_step), trf_x_scale ('jac', a float, or one entry per active parameter) and trf_gradient_tol (gtol); tol_fun/tol_x are passed as ftol/xtol. For this method max_iter is SciPy’s max_nfev, the number of step evaluations; the finite-difference Jacobian probes are not charged against it but are counted in FitResult.n_evaluations and drive the progress/stop checks. An exhausted budget returns success=False, interrupted=False with SciPy’s message; a stop or interrupt returns the best point so far with interrupted=True; n_iterations is the Jacobian-evaluation count (one per trust-region iteration). TRF is an optimization method, not a CPU-acceleration feature: it runs sequentially; simulation threading and the population-worker n_workers parallelism are separate. The default method is unchanged (simplex). Parity with a direct scipy.optimize.least_squares call is tested (tests/test_esfit_trf.py).

Fixed — fitting panel (2026-09-09)#

  • fitgui: 'trf' is offered in the method selector. Sessions built with explicit lb/ub keep those absolute bounds across restarts and slider moves (they were rebuilt as p0 ± vary around each new start). A parameter fixed for one run (the “fix” box, or start(vary=...) with a zero) can be released again on the next run (the zeroed vary used to overwrite the session’s). A start outside the bounds raises before any session state changes, and the panel re-enables its controls. The residual trace is now data − fit (it was fit − data).

  • FitResult.residuals docstring states the actual sign (fit − data).

Added — ML layer, cardamom seed (2026-09-06)#

  • torchspin.ml: ParamSpec (free spin-system parameters with ranges and linear/log/softplus transforms; pack/unpack between a flat tensor and a SpinSystem built from a template, on the autograd graph when the vector requires grad), simulate/simulate_batch (any differentiable simulator, (N, nPoints) output, optional spawned pool for no-grad generation), SpectrumDataset (seeded on-the-fly samples with resampling, normalization, noise and baseline), and torch losses (cosine_loss, rmsd, normalize, resample) so network predictions can be refined through the simulators.

  • convspec accepts tensor widths: differentiable ones are routed to the torch implementation, others are used as floats.

  • CardamomPar.seed: reproducible trajectory ensembles (DiffusionPar/ JumpPar seeds were not reachable from cardamom).

Changed — differentiable field modulation (2026-09-06)#

  • dataproc.fieldmod_t: the pseudo-modulation (Jacobi–Anger Bessel kernel, Kaelin & Schweiger) in torch (orders 0–2 closed form, higher by recurrence), equal to fieldmod to 1e-12; pepper_autograd and garlic use it, so Exp.ModAmp spectra are differentiable (pepper: forward = pepper() to 5e-10, gradient vs FD 2e-6).

Changed — pepper_autograd: perturbation methods (2026-09-06)#

  • Opt.Method='perturb*' now uses pepper’s perturbation resonance route in pepper_autograd (forward equals pepper() to 1e-10 for the dense-grid perturb2 workload, nitroxide perturb1 and Cu perturb2). Second-order trace and determinant scalars in resfields_perturb_batch stay tensors (they were .item()-detached, which left 1e-2 errors in the A gradient); gradients vs finite differences of pepper() are 1e-8 for A and g.

Changed — pepper_autograd: strain broadening (2026-09-06)#

  • pepper_autograd / differentiable_spectrum handle strains (HStrain, gStrain, AStrain, DStrain): the per-transition widths from compute_strain_widths_batch are already torch, and the EasySpin summation branch (facet centers, spread-smoothed widths, bin-integrated Gaussians — gaussian_bins_t) is now torch too. Forward equals pepper() to 2e-12 on nitroxide HStrain+gStrain (D2h), axial gStrain (Dinfh), AStrain and S=1 DStrain cases; gradients vs finite differences of pepper() 1e-6–1e-8 for g, A, gStrain, HStrain. DStrain magnitudes are constants (not differentiable).

Changed — differentiable saffron (2026-09-06)#

  • saffron (ESEEM/HYSCORE, predefined and custom ideal-pulse sequences): the relaxation decay, apodisation and FFT tail and the S=1/2 orientation-selection weights are torch, so with grad tensors in the spin system the time-domain signal and info['td']/info['fd'] are tensors on the autograd graph; without grad tensors the NumPy outputs are unchanged (forward identical to rounding). The default frequency-domain accumulation bins peaks (EasySpin sf_peaks) and is not differentiable in the peak frequencies, so grad tensors switch the call to SaffronOptions(TimeDomain=True) (exact evolution; forward differs from the binned default by the bin quantisation). Gradients vs finite differences of the time-domain path: 1e-5–1e-7 for A, Q, g (2pESEEM, HYSCORE; test_saffron_autograd.py). Mims-ENDOR raises for grad tensors.

Changed — differentiable garlic (2026-09-06)#

  • garlic runs in torch end to end (same algorithm: isotropic g/A, Breit–Rabi fixed point and perturbation Newton for the line positions, Kivelson–Freed fast-motion widths in fastmotion_t, explicit Lorentzian accumulation with torch line shapes and convolution, torch resampling), so spectra are on the autograd graph for g, A, Q, tcorr/logtcorr and lw/lwpp. Forward unchanged to 1e-9 (Fremy’s salt, nitroxide fast motion, methyl perturb2, frequency sweep, Temperature, Harmonic 2, ModAmp); gradients vs finite differences 1e-8 (test_garlic_autograd.py; the fine accumulation grid is re-discretized with the smallest width, so tcorr finite differences need a step within one discretization).

  • Options.AccumMethod='linear' (EasySpin makespec: a line is split between its two neighboring bins) is the differentiable form of the default nearest-bin stick spectrum and is selected automatically when the spin system carries grad tensors; it differs from nearest-bin binning by the sub-bin quantisation only (≈(Δx/2)/σ relative, 1 % for a 0.3 mT Gaussian at Δx = 6 µT; cosine 0.99998). ModAmp with grad tensors raises.

  • fastmotion() keeps its NumPy signature and wraps fastmotion_t.

Changed — differentiable salt; projection and eigh gradient fixes (2026-09-06)#

  • salt (fixed-field ENDOR) is differentiable: the transition arrays stay on the graph and the powder average uses the torch interpolation / projection / convolution shared with pepper_autograd (forward unchanged to 1e-12 on the 8-case MATLAB suite; Jacobians vs finite differences 1e-6–1e-8 for g, A, Q, lw in both the perturbative and the matrix path). The field-swept ENDOR mode still bins sticks and raises NotImplementedError for grad tensors.

  • pepper_autograd projection: a tent ramp of zero width (tied vertices — generic for axial systems, where the resonance field does not depend on φ) contributes no value but a first-order term; it was masked away, giving 9 % errors in d spec/dA_x at A_x = A_y. Now kept on the graph (1e-7).

  • torchspin._linalg.eigh uses a degeneracy-safe backward on the graph: within-subspace terms 1/(λ_j − λ_i) of coincident eigenvalues are dropped, the correct gradient for gauge-invariant outputs such as spectra.

  • torchspin.pepper_autograd.projecttriangles_t/projectzones_t/convspec_t are reused by salt; salt(..., lw_mhz=tensor) is allowed.

Changed — differentiable pepper shares pepper’s forward path (2026-09-05)#

  • New torchspin.pepper_autograd.pepper_autograd(sys, exp, opt): pepper’s rigid-limit powder spectrum (matrix method, no strain) on the autograd graph. It reuses pepper’s resonance-field search and transition tracking (resfields_batch, whose converged Newton step yields the implicit gradient of the resonance fields), and adds torch ports of the transition-slot bookkeeping, EasySpin grid interpolation (as linear maps, L3 in torch), SOPHE triangle/zone projection (projecttriangles_t, projectzones_t) and EasySpin’s sampled-kernel convolution/harmonic (convspec_t). Forward output equals pepper() to 1e-11 relative; autograd Jacobians match central finite differences of pepper() for g, A, D, Gaussian/Lorentzian lw and Temperature (1e-8 relative for A/D/lw; g to the finite-difference kink limit of the piecewise-linear projection).

  • differentiable_spectrum now builds a SpinSystem from the parameter tensors and calls pepper_autograd (method='pepper', default); GridSize accepts pepper’s [N, Ninterp] form, GridSymmetry defaults to 'auto', a tensor Temperature is differentiable. The earlier stand-alone models are kept as deprecated method='broadband' / 'analytical': they sum discrete orientations without interpolation or projection and carry orientation-grid ripple at GridSizes where pepper is converged (Cu(II) hyperfine, GridSize 31: cosine to EasySpin 0.985–0.999 in absorption, 0.73–0.88 in first derivative; pepper 0.9998–1.0000 / 0.999). Training a CNN on their output was training on a model that differs from pepper/EasySpin by more than the features to learn.

  • SpinSystem keeps tensors that requires_grad (no copy) and accepts lists of tensors (g=[g_tensor], A=[[ax, ay, az]]), so parameters can be optimized through the regular simulators; resfields_batch Boltzmann normalization is out of place (autograd through exp); hamsymm detaches before comparing.

  • Not yet differentiable: strains, ModAmp, mwPhase, ordering, photoselection, crystals, frequency sweeps (pepper_autograd raises NotImplementedError; pepper() is unchanged).

[0.2.2] — 2026-09-03#

Fixed — salt powder average#

  • salt (fixed-field ENDOR): the powder spectrum was accumulated as a stick spectrum (one nearest-bin hit per orientation), which left orientation-grid ripple on top of every powder pattern (EasySpin parity cosine 0.9947 for the rhombic-g 1H reference at GridSize 31). It now follows EasySpin salt.m: transition positions/intensities are tracked per transition across the grid, interpolated when GridSize=[N, Ninterp] is given (G3 positions, linear intensities; off when any orientation is missing), and projected with projecttriangles / projectzones, reusing the pepper ports. Parity on the 8-case MATLAB suite rises to 0.9917–0.99999 (rhombic-g 0.99996 at GridSize 31, 0.999998 at the reference’s [20 5]; S=3/2 0.942 → 0.992).

  • salt accepted only an integer GridSize and crashed with the default Options() (GridSize=[19, 4]); the [N, Ninterp] form is now honoured.

[0.2.1] — 2026-09-03#

Added — interactive fitting panel#

  • torchspin.fitgui: FitSession (esfit in a background thread with live progress; Stop returns the best fit so far) and FitPanel (ipywidgets sliders with bounds and fix boxes, method/budget controls, Start/Stop/Reset, live figure with data, best fit, residual and RMSD trace; ipympl canvas or PNG refresh). Optional extra torchspin[gui]; tutorial notebook examples/notebooks/09_fit_gui.ipynb.

[0.2.0] — 2026-09-03#

EasySpin parity rounds 1–3, performance rounds 1–2, esfit progress/early stop, notebooks 01–08, benchmark report against MATLAB/EasySpin. Details below.

Added — esfit progress, resource summary, early stop (2026-09-02)#

  • FitOptions.progress ('text', 'bar' with tqdm, or a callable), progress_every, progress_interval: rate-limited reports of iteration, evaluations, current and best RMSD, elapsed time, evaluations/s and ETA for every method (population methods report per evaluation chunk when worker processes are used); a resource summary (torch threads, worker processes, CPUs, CUDA/MPS, RSS) at the start and a totals line at the end.

  • Early stop: max_time, stop_when(info), a progress callable returning False, or a keyboard/kernel interrupt now return the best-so-far FitResult (success=False, interrupted=True, message with the reason) instead of losing the fit; an interrupted worker pool is terminated cleanly.

  • FitResult.n_evaluations, elapsed_s, interrupted.

Fixed — chili default basis (2026-09-02)#

  • chili: for one S = 1/2 electron with ≤ 2 nuclei, no potential and a rhombic basis (Mmax > 0, Kmax > 0) — where EasySpin auto-selects its fast builder and that builder equals general+MpSymm at half amplitude — the M–pS–pI symmetry basis is now the default (MpSymm=None = automatic) with the fast-method amplitude convention (verified in MATLAB on the stored cases). The plain general basis was 6 % off EasySpin’s default in the slow-motion limit (τc = 100 ns nitroxide: cosine 0.937 → 1.000).

  • Examples: fitting/fit_bruker_cw.py (load a Bruker file with eprload, read the acquisition parameters, baseline, fit with esfit); slowmotion/nitroxide_tcorr.py plot fix; liquids/fremysalt.py uses the reference’s A conversion; fitting/multicomponents.py built its target from separately weighted spectra (minor component weighted twice) — now uses the multi-component call, seeded noise and method='global'; examples/tests/compare_with_matlab_refs.py path fixed.

Changed — performance round 2 (2026-09-02, after the reference-workstation baseline)#

  • pepper strain summation: Gaussian accumulation in cache-sized chunks run in a thread pool, one spline evaluation per fine grid, cached spherical grids.

  • pepper interpolation: the D2h G3 coarse→fine interpolation (row splines + bicubic) is applied as one cached matrix per grid size (75× faster per slot; agreement 1e-12), which halves a small interpolated pepper call.

  • cardamom: orientations propagated in groups (trajectories were unseeded per orientation, so results are statistically unchanged), torch propagator and step loop, torch quaternion→rotation conversion.

  • esfit: population methods can evaluate the population in a spawned process pool (FitOptions.workers='auto'|'processes'|'threads', one torch thread per worker); the objective is a picklable partial.

  • Test: test_esfit_vs_matlab[field_g3lw_simplex] accepts the gx↔gy mirror solution — the case starts from gx0 == gy0 without hyperfine coupling, so the two minima are the same powder spectrum and which one a simplex reaches is decided by rounding noise.

Changed — performance round 1 (2026-09-02)#

Results are unchanged (MATLAB parity suites and the full test suite green after every step; resonance positions within 1e-11 mT of the previous search).

  • resfields_batch: one exact diagonalization per resonance candidate at the cubic-model root (EasySpin’s scheme) with a free Hellmann–Feynman Newton correction, instead of three polish evaluations plus a final pass; the transition eigenvectors are gathered there and reused for intensities; knot and candidate diagonalizations chunked to ~400 MB; per-orientation reassembly and strain widths as tensor ops (one host sync per call).

  • torchspin/_linalg.py: batched eigh/eigvalsh split over a thread pool of single-threaded LAPACK calls (torch loops serially over CPU batches; 21–23× on 32 cores); CUDA batches of matrices larger than cuSOLVER’s batched limit (32) are routed to the CPU pool. Used by resfields, resfreqs, salt, curry and the strain widths.

  • Options.BatchSize default is now automatic (all orientations per call, memory-capped) instead of 10.

  • pepper: vectorised SOPHE projection (_projecttriangles/_projectzones, loop ports kept as *_loop), windowed Gaussian bin accumulation, no per-resonance Python in the strain path.

  • cardamom: batched density-matrix propagation and tensor rotation.

  • chili: vectorised Liouvillian assembly (liouvhamiltonian; loop port kept as _liouvhamiltonian_loop).

  • Benchmarks: benchmarks/cluster/run_workstation.sh (serial campaign incl. MATLAB), benchmarks/analysis/workstation_report.py; results in benchmarks/results/workstation_20260902*/ and benchmarks/results/BENCHMARK_REPORT.md.

Added — EasySpin parity round 2 (2026-09-01)#

  • chili: full port of EasySpin’s general stochastic-Liouville method (torchspin/chili_sle.py): arbitrary spin systems, several nuclei, S>1/2, orienting potentials with powder integration, LjKKM basis switches, Lanczos/direct/eigen solvers, field-sweep methods, post-convolution nuclei, multi-component input; 60-case MATLAB suite (59 at cosine ≥0.999).

  • pepper: first-principles absolute intensity (dBdE, nuclear-sublevel sharing, density normalization) — the empirical scale factors are gone; symmetry-frame fix for tilted axial tensors; level-pair transition bookkeeping and EasySpin’s strain summation on the interpolated grid; Delaunay triangulation, rectified interpolation and projection for the open-φ grids (Ci, C2h, C1, …); exact templates for isotropic systems; Options.Method honoured (matrix default, perturbation opt-in); Experiment.SampleFrame; 102+12+11-case MATLAB suites.

  • sphgrid.grid_triangulation for all grid symmetries.

  • pepper features (all MATLAB-validated): single crystals and site transforms, parallel mode, isotopologues (torchspin/isotopologues.py, shared with garlic and chili), non-equilibrium populations (SpinSystem.initState, torchspin/initstate.py), partial ordering (Experiment.Ordering, torchspin/ordering.py), photoselection (lightBeam/lightScatter/tdm), field modulation, dispersion, Options.separate, and frequency sweeps through the unified interpolation/projection/summation path (resfreqs_batch).

  • garlic: component × isotopologue loop with weights, Options.separate='components', automatic sweep ranges (Options.Stretch), frequency sweeps with Experiment.Field alone.

  • SpinSystem.ee2 (biquadratic exchange), SpinSystem.D_, SpinSystem.Abund, SpinSystem.Q shorthand forms ([e2qQ/h eta]), Options.IsoCutoff.

  • spidyan: Dim sweeps of the pulse length tp.

  • eprload validated on all 75 EasySpin-readable example files; multi-D data, companion-file axes, multi-value BES3T, JEOL and specman fixes.

  • Ports of EasySpin’s isotopologues_* tests; cardamom MATLAB references.

Added — EasySpin parity round 3 (2026-09-02)#

  • pepper: Experiment.mwMode excitation modes (torchspin/excitation.py), photoselection on the perturbation paths, Options.separate='transitions', automatic sweep ranges, EasySpin transition pre-/post-selection, paired resonances of looping transitions, EasySpin interpolation modes for intensities and widths; 32-case MATLAB suite.

  • esfit: levmar is a port of esfit_levmar.m; 6-case EasySpin oracle.

  • orca2torchspin: 33-file orca2easyspin oracle; binary .prop frames and coordinates read column-major.

  • cardamom: three EasySpin 6 references (diffusion/fast, jump/fast, ISTOs) at cosine ≥0.97–0.9998.

Changed — EasySpin parity round 3#

  • cardamom: field-swept spectra no longer apply Experiment.Harmonic (EasySpin returns the imaginary FFT of the time-weighted FID); the output scale follows EasySpin’s double orientation normalization; the jump model no longer requires a correlation time.

  • hamsymm: principal-value equality at 1e-12 relative (was torch.allclose).

  • FitOptions.lm_delta default 1e-3 and lm_gradient_tol 1e-5 (EasySpin).

Changed — EasySpin parity round 2#

  • eprload returns abscissae in the file’s native units (Bruker: Gauss) and one abscissa per dimension for multi-dimensional data, as EasySpin does.

  • Experiment.Harmonic defaults to 1 for field sweeps and 0 for frequency sweeps; Experiment.Range may be omitted for automatic ranging (garlic).

  • resfields/resfreqs intensity thresholds use absolute values so emissive lines of non-equilibrium states survive.

Fixed — EasySpin parity round 2#

  • SpinSystem silently defaulted lw to 0.5 mT; the default is now no broadening (EasySpin). pepper/garlic fall back to Harmonic 0 when nothing broadens.

  • convspec samples the line-shape kernel on the grid like EasySpin (sub-increment widths differed by up to 3.7× from the analytic kernel).

  • pepper: resonances were matched across orientations by list index; strain widths were evaluated at one field per orientation; slots with missing resonances were filled from neighbors; isotropic systems and frequency sweeps had wrong normalization/units; single components ignored Sys.weight.

Added — EasySpin port completion (2026-09-01)#

  • saffron: S>1/2 systems, MimsENDOR blind-spot fix, ProductRule with TimeDomain, multi-component input with Sys.weight and opt.separate='components', single-crystal simulations via PulseExperiment.SampleFrame/CrystalSymmetry/MolFrame backed by a full sitetransforms port (230 space groups, vendored data/spacegroups.txt); saffron_thyme crystal orientations. MATLAB validation suite: 25 cases, zero skips.

  • salt: EasySpin fixed-field ENDOR mode (Experiment.Field + RF Range, ExciteWidth orientation selection) and an 8-case MATLAB validation suite.

  • spidyan: simulation-frame machinery (ZeemanFreq→g, SimFreq, pulse carriers through pulse()/rfmixer, phase cycling, DetFreq down-conversion, Dim pulse-parameter sweeps); 7-case MATLAB validation.

  • garlic: EasySpin’s line-position engine — exact Breit–Rabi fixed-point solver (default) and perturb1–perturb5, equivalent nuclei (SpinSystem.n, equivcouple), frequency sweeps, CenterSweep, field modulation (ModAmp), Boltzmann polarization, full g/A matrices; 18-case MATLAB suite (positions <1e-6 mT).

  • hamsymm: eigenvalue-based point-group analysis (hamsymm_eigs port) for Stevens/Ham*/crystal-field/full-tensor systems; sigma and nn tensors in the geometric pass; 22-case MATLAB suite plus the 20 EasySpin hamsymm_* tests.

  • Strain: multi-electron g strain and per-electron D strain with tilted DFrame and DStrainCorr; SpinSystem.DStrain is (nElectrons, 2). Transition-level MATLAB validation of strain widths.

  • ham_zf: BFrame rotation of high-order Stevens terms (Wigner D).

  • curry/blochsteady MATLAB validation suite (5 cases).

  • Hamiltonian MATLAB validation extended from 10 to 92 cases mirroring EasySpin’s ham_* tests.

  • esfit: dict-style lb/ub bounds.

  • Options.Method accepts exact/perturb/perturbN; new Options.AccumMethod, Accuracy, MaxIterations; Experiment.CenterSweep, mwCenterSweep, ModAmp.

Fixed — EasySpin port completion#

  • ham() omitted higher-order Zeeman terms (Sys.Ham*); now includes ham_ezho like EasySpin ham.m.

  • SpinSystem: scalar D meant [D D D] (isotropic); now [D, E=0] as in EasySpin. EasySpin input shorthands that crashed (per-electron scalar g/D, 1-D Q/sigma/frames for one nucleus, scalar/per-pair nn, scalar gnscale) are accepted; ee=[J] per-pair isotropic input no longer raises in ham_ee; g must be zero with Ham110/Ham112.

  • saffron: double orientation weighting under ProductRule; t2 UnboundLocalError for 2D custom sequences.

  • spidyan: pulses were propagated in the lab frame with DC envelopes (off-resonance) and Sys.ZeemanFreq was ignored.

  • salt: Experiment.Range was treated as an EPR field window instead of the RF window at fixed field.

  • pepper/chili reject sets of equivalent nuclei (SpinSystem.n > 1) explicitly, as EasySpin does.

Fixed#

  • esfit Nelder-Mead simplex: initial simplex edge length increased from 0.05 to 0.2 in the transformed [-1, 1] parameter space, matching MATLAB EasySpin’s esfit_simplex.m (delta = 0.1 * (ub - lb) in original space). The undersized initial simplex caused premature convergence to local minima on rugged loss surfaces (alpha-test report: 2-parameter EPR fits converging to wrong values even with reasonable bounds). Added TestSimplexExploration regression tests in tests/test_esfit.py.

  • esfit autoscale: scale factor is now forced positive (matches EasySpin esfit.m:1049 coeffs(1) = abs(coeffs(1))). A negative scale lets the optimizer “fit” by sign-flipping the model, which created spurious local minima on derivative spectra.

  • salt CUDA device wiring: frequency-swept path kept g_mat, A_i, frame rotations, flattened arrays, and spectrum bins on the active compute device. Options(device='cuda') now flows end-to-end through the freq-swept salt path; freq_axis and spec are returned on CPU to preserve the public API contract.

  • pepper, resfields_batch, resfields_perturb, and all ham_{ee,ez,hf,nn,nq,nz,zf}.py: tightened device propagation so Options(device='cuda') no longer leaks intermediate CPU tensors.

  • eprload Bruker BES3T: case-insensitive companion-file lookup (probes both .DSC/.DTA and .dsc/.dta) so Linux checkouts with lowercase fixtures load correctly.

  • MATLAB validation tests (test_chili_matlab_validation.py, test_endorfrq_matlab_validation.py): float(np.asarray(x).squeeze()) replaces float(x) on .mat fields to work with numpy ≥ 1.25 where 0-dim-array→scalar conversion is a hard error rather than a warning.

Added#

  • esfit new option target='auto' (now the default): inspects the data and picks 'int' for derivative-like spectra (mean ≪ std) and 'fcn' otherwise. Matches EasySpin’s behavior of auto-selecting the integral target for pepper/garlic with Harmonic > 0. Smooths the loss landscape for derivative EPR.

  • esfit new method method='global': particle-swarm (global) followed by Nelder-Mead (local polish). Recommended for realistic EPR fits with rugged loss landscapes where plain simplex gets trapped. Recovers gx=2.001 (true 2.000) on the canonical Harmonic=1 powder fit where plain simplex returned gx=2.080. Brings the optimizer count to 9.

  • esfit new option n_workers: int = 1: enables ThreadPoolExecutor evaluation of the population for swarm, genetic, montecarlo, grid, and global methods. Effective for forward models that release the GIL during torch tensor ops (pepper/garlic/chili/saffron).

  • TestAutoTargetAndGlobal and TestSimplexExploration regression tests in tests/test_esfit.py (6 new tests total).

  • benchmarks/PERFORMANCE_SUMMARY.md and benchmarks/RUNLOG_2026-04-20.md (development records, not distributed; their results are summarized in benchmarks/results/BENCHMARK_REPORT.md and embedded in benchmarks/analysis/make_manuscript_figures.py) — performance and accuracy summary (MATLAB parity table, pepper CPU vs GPU scaling, differentiable_spectrum 2.5× GPU speedup, esfit method comparison, 5-parameter stress test, MSE vs integral-MSE finding for gradient-based fitting).

[0.1.0] — 2026-04-18#

Initial PyPI release#

Full EasySpin parity achieved — all scientifically relevant MATLAB functions ported to Python/PyTorch with 1820+ passing tests.

CW EPR simulators

  • pepper — powder CW EPR (MATLAB cosine > 0.999)

  • garlic — solution / fast-motion EPR (MATLAB cosine 1.0000)

  • chili — slow-motion SLE (MATLAB cosine 0.92–0.997)

  • salt — ENDOR powder (MATLAB cosine > 0.92)

  • curry — magnetometry (susceptibility, magnetization)

  • blochsteady — Bloch steady-state

  • levels — energy level diagrams

  • fastmotion — Kivelson/Freed linewidths

Pulse EPR

  • saffron — predefined (2p/3p/4p ESEEM, HYSCORE, MimsENDOR) + custom sequences

  • saffron_thyme — real-pulse orientation-averaged propagation

  • spidyan — arbitrary pulse sequences with relaxation and phase cycling

  • pulse, exciteprofile, resonator, rfmixer, transmitter — pulse primitives

Trajectory-based

  • cardamom — diffusion, jump, MD-direct, ISTOs methods

  • stochtraj_diffusion, stochtraj_jump

  • mdload, mdhmm, mdtraj2oripot — MD trajectory analysis

Differentiable

  • differentiable_spectrum — S=1/2 analytical + N-spin broadband via batch eigh

  • Gradients validated vs finite differences for g, A, D tensors

Fitting

  • esfit — 8 optimizers: Nelder-Mead, L-BFGS-B, Powell, grid, Monte Carlo, genetic, particle swarm, Levenberg-Marquardt

  • autoguess — starting-parameter estimation

Data I/O

  • eprload — 12 vendor formats (BES3T, ESP, Bruker, Varian, JEOL, Magnettech, …)

  • eprsave — BES3T writer

  • orca2torchspin — ORCA QC output import (.out, .prop, _property.txt)

GPU + compilation

  • Options.device='cuda' support throughout simulator chain

  • Opt-in torch.compile via TORCHSPIN_COMPILE=1

  • Batched simulation via batch_pepper, batch_simulate

Conventions#

  • Energy units: MHz throughout

  • Field units: mT

  • Euler angles: radians, z-y’-z’’ passive rotation

  • Default dtype: torch.complex128