torchspin 0.6.7__tar.gz → 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. {torchspin-0.6.7 → torchspin-0.8.0}/CHANGELOG.md +272 -0
  2. {torchspin-0.6.7 → torchspin-0.8.0}/CITATION.cff +2 -2
  3. {torchspin-0.6.7 → torchspin-0.8.0}/PKG-INFO +8 -4
  4. {torchspin-0.6.7 → torchspin-0.8.0}/README.md +4 -3
  5. {torchspin-0.6.7 → torchspin-0.8.0}/pyproject.toml +2 -1
  6. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/__init__.py +1 -1
  7. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_linalg.py +6 -2
  8. torchspin-0.8.0/torchspin/_zerofield.py +61 -0
  9. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/autograd.py +10 -0
  10. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/cardamom.py +2 -0
  11. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/chili_sle.py +4 -0
  12. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/endorfrq.py +42 -1
  13. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/endorfrq_perturb.py +15 -0
  14. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/esfit.py +435 -226
  15. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/experiment.py +143 -4
  16. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/fastmotion.py +2 -0
  17. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/garlic.py +8 -0
  18. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham.py +14 -0
  19. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_ezho.py +84 -0
  20. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/hamsymm.py +4 -1
  21. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/levels.py +19 -0
  22. torchspin-0.8.0/torchspin/lft/__init__.py +48 -0
  23. torchspin-0.8.0/torchspin/lft/_engines/__init__.py +1 -0
  24. torchspin-0.8.0/torchspin/lft/_engines/dipole.py +53 -0
  25. torchspin-0.8.0/torchspin/lft/_engines/dlsd5.py +675 -0
  26. torchspin-0.8.0/torchspin/lft/_engines/dn.py +387 -0
  27. torchspin-0.8.0/torchspin/lft/_engines/dsoxf.py +616 -0
  28. torchspin-0.8.0/torchspin/lft/_engines/igloo.py +150 -0
  29. torchspin-0.8.0/torchspin/lft/_engines/ligand_field.py +85 -0
  30. torchspin-0.8.0/torchspin/lft/_engines/pn.py +289 -0
  31. torchspin-0.8.0/torchspin/lft/_engines/tanabe_sugano.py +725 -0
  32. torchspin-0.8.0/torchspin/lft/_linalg.py +391 -0
  33. torchspin-0.8.0/torchspin/lft/_operators.py +74 -0
  34. torchspin-0.8.0/torchspin/lft/_powder.py +163 -0
  35. torchspin-0.8.0/torchspin/lft/bridge.py +41 -0
  36. torchspin-0.8.0/torchspin/lft/ddn.py +193 -0
  37. torchspin-0.8.0/torchspin/lft/ddnfit.py +27 -0
  38. torchspin-0.8.0/torchspin/lft/ddnloop.py +306 -0
  39. torchspin-0.8.0/torchspin/lft/ddnmag.py +184 -0
  40. torchspin-0.8.0/torchspin/lft/ddnpow.py +440 -0
  41. torchspin-0.8.0/torchspin/lft/ddnsus.py +78 -0
  42. torchspin-0.8.0/torchspin/lft/ddpowh.py +702 -0
  43. torchspin-0.8.0/torchspin/lft/ddpowj.py +96 -0
  44. torchspin-0.8.0/torchspin/lft/dipole.py +405 -0
  45. torchspin-0.8.0/torchspin/lft/dlsd5.py +500 -0
  46. torchspin-0.8.0/torchspin/lft/dpn.py +407 -0
  47. torchspin-0.8.0/torchspin/lft/dpnfit.py +653 -0
  48. torchspin-0.8.0/torchspin/lft/dsoxf.py +430 -0
  49. torchspin-0.8.0/torchspin/lft/dtd.py +187 -0
  50. torchspin-0.8.0/torchspin/lft/fit.py +560 -0
  51. torchspin-0.8.0/torchspin/lft/grids.py +129 -0
  52. torchspin-0.8.0/torchspin/lft/ligand_field.py +203 -0
  53. torchspin-0.8.0/torchspin/lft/plot.py +1261 -0
  54. torchspin-0.8.0/torchspin/lft/tanabe_sugano.py +309 -0
  55. torchspin-0.8.0/torchspin/lft/telser2torchspin.py +1277 -0
  56. torchspin-0.8.0/torchspin/lft/units.py +99 -0
  57. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ml.py +33 -13
  58. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/orisel.py +2 -0
  59. torchspin-0.8.0/torchspin/parallel.py +135 -0
  60. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/pepper.py +330 -15
  61. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/pepper_autograd.py +152 -8
  62. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfields.py +3 -0
  63. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfields_batch.py +69 -4
  64. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfields_perturb.py +11 -0
  65. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfreqs_matrix.py +83 -9
  66. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfreqs_perturb.py +4 -0
  67. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/saffron.py +2 -0
  68. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/salt.py +151 -14
  69. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/spinsystem.py +124 -0
  70. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/strainwidth.py +78 -3
  71. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin.egg-info/PKG-INFO +8 -4
  72. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin.egg-info/SOURCES.txt +38 -1
  73. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin.egg-info/requires.txt +4 -0
  74. {torchspin-0.6.7 → torchspin-0.8.0}/LICENSE.md +0 -0
  75. {torchspin-0.6.7 → torchspin-0.8.0}/MANIFEST.in +0 -0
  76. {torchspin-0.6.7 → torchspin-0.8.0}/setup.cfg +0 -0
  77. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_cardamom_istos.py +0 -0
  78. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_cardamom_propagatedm.py +0 -0
  79. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_cardamom_utils.py +0 -0
  80. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_compile.py +0 -0
  81. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_omp.py +0 -0
  82. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_resources.py +0 -0
  83. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/_rng.py +0 -0
  84. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/angmom.py +0 -0
  85. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/autoguess.py +0 -0
  86. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/batch.py +0 -0
  87. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/blochsteady.py +0 -0
  88. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/chili.py +0 -0
  89. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/constants.py +0 -0
  90. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/convspec.py +0 -0
  91. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ctafft.py +0 -0
  92. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/curry.py +0 -0
  93. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/data/FourierSeriesCoefficients.txt +0 -0
  94. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/data/GaussianCascadeCoefficients.txt +0 -0
  95. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/data/isotopedata.txt +0 -0
  96. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/data/spacegroups.txt +0 -0
  97. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/dataproc.py +0 -0
  98. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/dipbackground.py +0 -0
  99. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/dipkernel.py +0 -0
  100. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/diptensor.py +0 -0
  101. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/eprload.py +0 -0
  102. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/eprsave.py +0 -0
  103. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/evolve.py +0 -0
  104. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ewrls.py +0 -0
  105. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/excitation.py +0 -0
  106. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/exciteprofile.py +0 -0
  107. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/exponfit.py +0 -0
  108. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/fdaxis.py +0 -0
  109. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/fitgui.py +0 -0
  110. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/gridcheck.py +0 -0
  111. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_cf.py +0 -0
  112. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_ee.py +0 -0
  113. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_ez.py +0 -0
  114. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_hf.py +0 -0
  115. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_nn.py +0 -0
  116. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_nq.py +0 -0
  117. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_nz.py +0 -0
  118. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_oz.py +0 -0
  119. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_so.py +0 -0
  120. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ham_zf.py +0 -0
  121. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/initstate.py +0 -0
  122. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/isotopologues.py +0 -0
  123. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/levelsplot.py +0 -0
  124. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/lineshape.py +0 -0
  125. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/lpsvd.py +0 -0
  126. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/makespec.py +0 -0
  127. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/mdhmm.py +0 -0
  128. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/mdload.py +0 -0
  129. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/mdtraj2oripot.py +0 -0
  130. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/mlpsvd.py +0 -0
  131. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/nucdata.py +0 -0
  132. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/nucfrq2d.py +0 -0
  133. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/orca2torchspin.py +0 -0
  134. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/ordering.py +0 -0
  135. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/oripotentialplot.py +0 -0
  136. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/photoselect.py +0 -0
  137. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/plegendre.py +0 -0
  138. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/propint.py +0 -0
  139. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/pulse.py +0 -0
  140. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/py.typed +0 -0
  141. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/rapidscan2spc.py +0 -0
  142. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfields_eig.py +0 -0
  143. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resfields_hybrid.py +0 -0
  144. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resonator.py +0 -0
  145. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/resonatorprofile.py +0 -0
  146. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/rfmixer.py +0 -0
  147. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/rotations.py +0 -0
  148. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/rotutils.py +0 -0
  149. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/saffron_pathways.py +0 -0
  150. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/saffron_peaks.py +0 -0
  151. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/saffron_thyme.py +0 -0
  152. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/sigeq.py +0 -0
  153. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/signalprocessing.py +0 -0
  154. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/sitetransforms.py +0 -0
  155. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/sphgrid.py +0 -0
  156. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/spidyan.py +0 -0
  157. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/spinladder.py +0 -0
  158. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/spinops.py +0 -0
  159. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/stackplot.py +0 -0
  160. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/stev.py +0 -0
  161. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/stochtraj_diffusion.py +0 -0
  162. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/stochtraj_jump.py +0 -0
  163. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/transmitter.py +0 -0
  164. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin/utils.py +0 -0
  165. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin.egg-info/dependency_links.txt +0 -0
  166. {torchspin-0.6.7 → torchspin-0.8.0}/torchspin.egg-info/top_level.txt +0 -0
@@ -6,6 +6,278 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0] — 2026-11-11
10
+
11
+ The first PyPI release since 0.7.0: it also contains 0.7.1–0.7.7 below, which were merged but not
12
+ published separately.
13
+
14
+ ### Added
15
+
16
+ - **`torchspin.lft`: ligand-field tools.** Joshua Telser's programs, ported from
17
+ telser-tools and differentiable. `lft.ddn`, `ddnloop`, `ddnpow`, `ddnfit`, `ddnsus`, `ddnmag`,
18
+ `dpn`, `dpnfit`, `dsoxf`, `tanabe_sugano`, `dlsd5`, `dipole`, `dtd`.
19
+ - `lft.fit.JointFit` fits one model to band energies, g values, χ, M and EPR spectra together,
20
+ with exact Jacobians.
21
+ - `lft.dn2sys` builds a `SpinSystem` with the full g matrix, for a differentiable route from a
22
+ ligand field to `pepper`.
23
+ - `lft.plot` draws its plots in cm⁻¹ by default.
24
+ - `lft.telser2torchspin` converts DDZHQ, DDPOWH, DJDZE and DDPOWJ inputs.
25
+ - `lft.ddpowh`, `lft.ddpowj`: Telser's field-point powder EPR, FDMR, ENDOR and S = 0 NMR/NQR on a
26
+ `SpinSystem`. They add what `pepper` lacks: the level strain width that depends on the composition of
27
+ each level (DDPOWH sum and DDPOWJ product weights), m_S-manifold pair selection, Lorentzian
28
+ frequency-domain lines, the Flygare factor, the line cutoff, zero-field FDMR, chemical shielding, and
29
+ Telser's w and U terms. The converters' `target='lft'` runs a Telser input through them; all 103
30
+ DDPOWH/DDPOWJ golden inputs match telser-tools to 1e-10.
31
+ - The package is additive: only `torchspin/__init__.py` gains `lft`. See `docs/lft.md`.
32
+
33
+ ### Fixed
34
+
35
+ - **Flaky test `test_orientations_at_zero_field_match_the_powder`.** Its zero-field lines
36
+ (0.6, 2.7, 3.3 GHz) sat exactly on bin edges of the 10 MHz axis, so the powder projection
37
+ put each line in one of two bins depending on the last bit of the eigenvalues, and the test
38
+ failed by 4 % on some CI runners. The lines are now a third of a bin from any edge, and the
39
+ powder is compared on the half-bin-shifted axis. pepper is unchanged: the single-bin deposit
40
+ matches EasySpin and the B → 0⁺ limit. KNOWN_LIMITATIONS documents the bin-edge case.
41
+
42
+ ## [0.7.7] — 2026-11-10
43
+
44
+ ### Added
45
+
46
+ - **`SpinSystem.HStrainL`: Lorentzian strain in `pepper`.** A `[3]` vector
47
+ (or scalar) of frequency-domain Lorentzian FWHM in MHz along the molecular
48
+ x, y, z axes. A transition's width is `sqrt(sum_k (HStrainL_k n_k)^2)`,
49
+ the orientation dependence and dB/dE conversion of `HStrain`, but every line
50
+ is drawn as a Lorentzian instead of a Gaussian (Telser's DDPOWH/DDPOWJ
51
+ Lorentzian width). Works on every pepper path (powder facet summation,
52
+ per-orientation and interpolated fallbacks, isotropic, crystals,
53
+ `Exp.Orientations`, frequency sweeps, `Method='hybrid'`), with `Exp.mwPhase`
54
+ (the dispersion admixture is in each line; the remaining `Sys.lw` is then
55
+ convolved as absorption) and in `pepper_autograd` (gradients w.r.t.
56
+ `HStrainL`, g and the other spin-system tensors). `esfit` treats it as
57
+ non-negative and `ml` templates keep it. **Not an EasySpin field**:
58
+ EasySpin's strains are all Gaussian, so this is a deliberate addition.
59
+ Validated by: isotropic `HStrainL` equals the EasySpin-validated
60
+ `Sys.lw(2)` Lorentzian exactly (field and frequency sweeps, harmonics 0–2);
61
+ single orientations equal the analytic Lorentzian to 1e-12; rhombic S = 1/2
62
+ powders meet a brute-force reference as closely as the Gaussian `HStrain`
63
+ does (0.6 % vs 0.7 %); gradients match central differences to 1e-6.
64
+ Combining it with `HStrain`, `gStrain`, `AStrain` or `DStrain` raises
65
+ `ValueError` (no per-line Voigt profile). The default (`None`) is unchanged.
66
+
67
+ ## [0.7.6] — 2026-11-10
68
+
69
+ ### Added
70
+
71
+ - **`Experiment.Orientations` / `Experiment.OrientationWeights`: pepper on a
72
+ user-supplied list of field directions.** `Orientations` is an `(N, 2)`
73
+ array (or tensor) of `[phi, theta]` in radians in the molecular frame, B0
74
+ along `(sinθ cosφ, sinθ sinφ, cosθ)` as in `levels`/`resfields`;
75
+ `OrientationWeights` (default `1/N`) are fractions of the sphere, used as
76
+ given, so weights summing to 1 give the powder amplitude. pepper sums the
77
+ stick spectra of these orientations with χ-averaged (powder) transition
78
+ rates, without grid interpolation or SOPHE projection: every line is
79
+ accumulated with an exact template (strain width or `Sys.lw(1)` Gaussian,
80
+ else `Sys.lw(2)` Lorentzian) and the rest of `Sys.lw` is convolved, as on the
81
+ crystal and isotropic paths. Supported: field and frequency sweeps,
82
+ `Method='matrix'`/`'perturb*'`/`'hybrid'`, strains, temperature,
83
+ `Sys.initState`, photoselection, `ModAmp`, `Opt.separate='orientations'`.
84
+ `pepper_autograd` supports it for field sweeps (gradients w.r.t. the spin
85
+ system, `lw`, strains and the weights). Raises with `Ordering`,
86
+ `SampleFrame`, `SampleRotation`, `MolFrame`, `CrystalSymmetry`, `Opt.Sites`
87
+ and `Opt.separate='transitions'/'sites'`; `GridSize`/`GridSymmetry` are
88
+ ignored. EasySpin has no counterpart; validated against EasySpin crystal
89
+ spectra summed over two rotations about B0 (an exact χ average). The
90
+ default (`None`) is unchanged.
91
+ ## [0.7.5] — 2026-11-10
92
+
93
+ ### Added
94
+
95
+ - **`Options.Transitions` selects the transitions `pepper` simulates, like
96
+ EasySpin's `Opt.Transitions`.** `None` (the default) keeps the automatic
97
+ transition pre-selection with `Opt.Threshold`, so default spectra are
98
+ unchanged (bit-identical). `'all'` takes every level pair u < v with neither
99
+ the pre-selection nor the `Threshold` intensity post-selection (EasySpin sets
100
+ its post-selection threshold to zero for `'all'`), which recovers weak lines
101
+ that the default drops, such as the half-field ΔmS = 2 line of a triplet with
102
+ small D. A list of 1-based level pairs `(u, v)`, levels numbered by ascending
103
+ energy at the resonance field, takes exactly those transitions: pairs are
104
+ normalized to u < v, duplicates are removed, and out-of-range indices, u = v,
105
+ non-integers and empty lists raise `ValueError` (EasySpin silently drops
106
+ out-of-range rows and keeps duplicates). Within a list the `Threshold`
107
+ post-selection still applies, as in EasySpin. Supported on every matrix path
108
+ of `pepper` (powder projection, strain summation, interpolation, crystals,
109
+ the isotropic O3 path, frequency sweeps including the automatic range, and
110
+ `Method='hybrid'`, where levels are those of the exact core) and in
111
+ `pepper_autograd` (gradients flow as before; the pair list is a constant).
112
+ `Method='perturb*'` raises when `Transitions` is set (EasySpin ignores the
113
+ option there). Validated against EasySpin on 9 cases
114
+ (`tests/data/ref_pepper_transitions.mat`).
115
+ ## [0.7.4] — 2026-11-10
116
+
117
+ ### Added
118
+
119
+ - **Zero-field frequency sweeps and fixed-field ENDOR: `Options.ZeroField`**
120
+ (default `False`, which leaves results unchanged). With `ZeroField=True`,
121
+ `pepper` frequency sweeps and `salt` fixed-field ENDOR accept
122
+ `Experiment.Field = 0`. Levels are grouped into degenerate clusters (Kramers
123
+ doublets, accidental degeneracies), and each transition carries the rate
124
+ summed over all level pairs between two clusters. Intensities are therefore
125
+ independent of the arbitrary eigenbasis inside a degenerate subspace. The
126
+ summing is done before slot tracking, threshold pruning and pair
127
+ preselection. The isotropic O3 shortcut is replaced by a D2h grid. Validated
128
+ against EasySpin's pepper at `Exp.Field = 0` (5 cases,
129
+ `ref_pepper_zerofield.mat`), closed forms (S = 1: D−E, D+E, 2E; S = 3/2:
130
+ 2·sqrt(D²+3E²)) and the B → 0 limit. See KNOWN_LIMITATIONS.md,
131
+ "Pepper and salt — zero field".
132
+ - `Experiment(Field=0)` now constructs in frequency-swept and fixed-field mode.
133
+ Without `ZeroField`, the same `ValueError("Experiment.Field must be positive
134
+ (mT).")` is raised when `pepper`, `salt`, `garlic`, `chili` or
135
+ `resfreqs_perturb` is called. A negative field still raises in the
136
+ constructor.
137
+ ## [0.7.3] — 2026-11-10
138
+
139
+ ### Added
140
+
141
+ - **Hyperfine enhancement in ENDOR intensities: `Options.Enhancement`**
142
+ (EasySpin `Opt.Enhancement`). Default `False`: results are unchanged
143
+ (bit-identical). With `True`, `endorfrq` (new keyword `opt=Options(...)`)
144
+ and the matrix paths of `salt` use the total magnetic moment (electron +
145
+ nuclear, the `mux/muy/muz` of `ham()`) perpendicular to the field,
146
+ chi-averaged over lab x and y, as the rf transition operator. As in EasySpin
147
+ `endorfrq.m`, the transition selection (`threshold`/`Opt.Threshold`) still uses
148
+ the nuclear-only rates and electronic level pairs are excluded. `salt` with
149
+ `Enhancement=True` always uses the matrix ENDOR path; its automatic
150
+ first-order perturbation shortcut (one electron, no Q) has no enhancement.
151
+ `endorfrq_perturb` gained an `opt` keyword and raises `NotImplementedError`
152
+ for `Enhancement=True` (EasySpin silently ignores it there). Validated
153
+ against EasySpin `endorfrq`/`salt` with `Opt.Enhancement='on'`
154
+ (`tests/data/endor_enhancement_refs.mat`), a NumPy brute force, the
155
+ first-order factor (ν_ENDOR/ν_I)² and gradients (reverse and forward mode).
156
+ ## [0.7.2] — 2026-11-10
157
+
158
+ ### Added
159
+
160
+ - **`SpinSystem.H0Extra`: generic extra terms in the field-independent
161
+ Hamiltonian.** A list of `(coeff, op)` pairs; `ham` adds Σ coeff·op (MHz) to
162
+ H0 on both the `(H0, μ)` and the `ham(Sys, B0)` path, so every simulator that
163
+ diagonalizes the full Hamiltonian (pepper's matrix method and
164
+ `pepper_autograd`, `levels`, `resfields`, `resfreqs`, `endorfrq`, `curry`,
165
+ `nucfrq2d`, saffron's real-pulse engine, spidyan) includes it. `coeff` is a
166
+ real scalar (float or 0-d tensor) and stays on the autograd graph, as does
167
+ `op` when it is a tensor that requires grad; `op` is an (n, n) Hermitian
168
+ matrix in the full spin-system basis (sop order). This allows terms that
169
+ torchspin has no field for, such as the S=3/2 U term U Σ C_k(S) I_k. Shape,
170
+ Hermiticity and real coefficients are checked when the spin system is built.
171
+ `hamsymm` analyzes systems with `H0Extra` through the eigenvalue probe, and
172
+ `pepper` routes to `pepper_autograd` when a coefficient or operator requires
173
+ grad. Solvers that build the Hamiltonian from the tensors without `ham`
174
+ (perturbation theory, `Method='hybrid'`, garlic, chili, fastmotion, cardamom,
175
+ saffron's fast algorithm, salt for one electron, orisel,
176
+ `nucspinrmv`/`nucspinkeep`/`nucspinadd`) raise when it is set; so do isotope
177
+ mixtures in `Nucs` and `SpinSystem.n > 1`. Not an EasySpin feature. The
178
+ default (`None`) is unchanged.
179
+
180
+ ## [0.7.1] — 2026-11-10
181
+
182
+ ### Added
183
+
184
+ - **Opt-in field-quadratic and field-cubic higher-order Zeeman terms in the
185
+ resonance search: `Options.QuadraticZeeman` (default `False`, unchanged
186
+ behavior).** With `True`, the `Sys.Ham` terms of order lB = 2 and 3 enter
187
+ pepper's matrix solver, so that H(B) = H0 − B n·μ + B² n·G2·n + B³ G3[n,n,n]
188
+ equals `ham(Sys, B·n)` at every field. The Hermite level model, Hellmann–Feynman
189
+ slopes, companion-matrix roots, Newton polish, the dB/dE intensity factor and
190
+ the strain widths all use dH/dB = −n·μ + 2B n·G2·n + 3B² G3[n,n,n]; the
191
+ transition pre-selection diagonalizes the full H at the center field, and
192
+ frequency sweeps add the terms at the fixed field. Covers `pepper` and
193
+ `pepper_autograd` (`Method='matrix'`: powders, crystals, O3, field and
194
+ frequency sweeps; the implicit-function gradient uses the full slope) and
195
+ `resfreqs_matrix`; `levels` gets the same switch as the keyword
196
+ `quadratic_zeeman=False`. `resfields_batch`/`resfreqs_batch` take the
197
+ operators as `zeeman_ho=` (from the new
198
+ `torchspin.ham_ezho.field_nonlinear_zeeman_ops`). The perturbation and hybrid
199
+ methods, `resfields`, `garlic` and `salt` raise `NotImplementedError` when the
200
+ option is on and such terms are present; lB ≥ 4 terms raise. Validated
201
+ against `ham(Sys, B)` (levels to 1e-12, resonance condition to 1e-9), a closed
202
+ form for S = 1 with w(μB B·S)², a brute-force field-point powder simulation
203
+ (cosine 0.999998), finite differences (dB/dE, gradients) and EasySpin pepper
204
+ (`tests/data/ref_pepper_quadzeeman.mat`, cosine ≥ 0.99999, amplitude within
205
+ 0.4 %). With the default `False`, every result is bit-identical to 0.7.0.
206
+
207
+ ## [0.7.0] — 2026-11-09
208
+
209
+ CPU-parallel fitting and data generation. Default behavior (`n_workers=1`,
210
+ `simulate_batch(workers=0)`) is unchanged; no physics code changed.
211
+
212
+ ### Changed — behavior differs from 0.6.7
213
+
214
+ - **`FitOptions.n_workers` now also applies to levmar, trf, lbfgsb and the
215
+ uncertainty estimate of every method**, not only to the population methods.
216
+ A script that already set `n_workers='auto'` (or an integer > 1) for one of
217
+ these methods used to get no parallelism; it now starts spawned worker
218
+ processes, which needs the usual `if __name__ == '__main__':` guard around
219
+ the code that runs the fit.
220
+
221
+ ### Added
222
+
223
+ - **Parallel finite differences in esfit.** With `FitOptions(n_workers > 1)`
224
+ or `'auto'`, the independent finite-difference probes run in the worker pool:
225
+ levmar's initial Jacobian (n + 1 calls), every trf Jacobian and L-BFGS-B
226
+ gradient (n calls each, through SciPy's `workers=`, SciPy ≥ 1.16; older SciPy
227
+ runs them sequentially with a warning) and the uncertainty Jacobian (2n
228
+ calls). Probe points, recording order and evaluation counts are unchanged, so
229
+ a model with deterministic output gives the same fit. For trf and lbfgsb,
230
+ SciPy evaluates the base point in the main process and the probes in workers
231
+ with fewer threads; torch round-off then differs at ~1e-14, which shows up as
232
+ a ~1e-6 relative Jacobian difference, far below what changes a fit. Measured
233
+ on a 224-core cluster node (4-parameter pepper fit, 8–64 threads): levmar
234
+ 1.6–1.7×, trf 2.6–3.2× faster. The uncertainty Jacobian no longer evaluates
235
+ an unused base point.
236
+ - **`FitOptions.devices`**, e.g. `['cuda:0', 'cuda:1']`: process workers are
237
+ pinned to these GPUs round-robin (`CUDA_VISIBLE_DEVICES` per worker), so a
238
+ model with `device='cuda'` runs on its own GPU.
239
+ - **`torchspin.ml.simulate_batch` reuses its worker pool** (shared with esfit)
240
+ instead of starting one per call, sends rows in chunks, and accepts
241
+ `workers='auto'`. Cu(II) on a 64-core node: 197 → 1473 spectra/s with 64
242
+ workers (one process: 42; one A100 GPU: 76). An interrupted batch terminates
243
+ the pool.
244
+ - **`torchspin.parallel`** (public): `cpu_budget()` (CPU affinity, then SLURM,
245
+ then the machine), `inner_threads()`, the `thread_budget(n)` context manager
246
+ (caps torchspin's inner pools, and BLAS with `blas=True` when `threadpoolctl`
247
+ is installed) and `native_thread_env(n)` for spawned workers (also passes
248
+ `OMP_WAIT_POLICY=PASSIVE`).
249
+ - Optional extra `[hpc]` (`threadpoolctl`, `cloudpickle`).
250
+ - Docs: `docs/pitfalls.md`, "Training sets of large spin systems" (orientation
251
+ symmetry and `Options.Threshold`: for Cu(II) with two ¹⁴N, `Threshold=1e-2`
252
+ was 3.6× faster with a 0.4 % spectrum change).
253
+ - Benchmarks:
254
+ - end-to-end esfit workloads (levmar and trf, sequential and with process
255
+ workers; swarm with process and thread backends; a nested-parallelism case);
256
+ - `benchmarks/workloads/ml_throughput.py` (spectra per second of
257
+ `simulate_batch`);
258
+ - `benchmarks/analysis/compare_baseline.py`, which saves host-free baselines
259
+ and flags regressions;
260
+ - a generic SLURM job-array template, `benchmarks/cluster/slurm_array_template.sbatch`;
261
+ - `run_workloads.py --save-outputs`;
262
+ - `docs/v1_acceleration/`: the acceleration review and roadmap with the
263
+ measurement log.
264
+
265
+ ### Fixed
266
+
267
+ - `benchmarks/workloads/run_workloads.py`:
268
+ - `--threads N` now overwrites the native thread variables. With an
269
+ inherited `OMP_NUM_THREADS` (as batch scripts set it), "1-thread" runs used
270
+ to keep every core in the native pools.
271
+ - It also caps Apple Accelerate (`VECLIB_MAXIMUM_THREADS`).
272
+ - `--procs` starts its process pool once, outside the timed replicates.
273
+ - A failing workload is recorded instead of aborting the run.
274
+ - It imports torchspin before torch and records `OMP_WAIT_POLICY`.
275
+
276
+ ### Removed
277
+
278
+ - `benchmarks/cluster/slurm_cpu.sh` and `slurm_gpu.sh`, replaced by the
279
+ array template. The CPU script's thread sweep was mislabeled (see Fixed).
280
+
9
281
  ## [0.6.7] — 2026-11-09
10
282
 
11
283
  ### Fixed
@@ -2,8 +2,8 @@ cff-version: 1.2.0
2
2
  message: "If you use torchspin in your research, please cite both torchspin and the upstream EasySpin paper."
3
3
  title: "torchspin: Differentiable PyTorch port of EasySpin for EPR spectroscopy"
4
4
  type: software
5
- version: "0.6.7"
6
- date-released: "2026-11-09"
5
+ version: "0.8.0"
6
+ date-released: "2026-11-11"
7
7
  license: MIT
8
8
  authors:
9
9
  - family-names: "Follmer"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torchspin
3
- Version: 0.6.7
3
+ Version: 0.8.0
4
4
  Summary: Differentiable PyTorch port of EasySpin - EPR/ESR spin Hamiltonian and spectrum simulation
5
5
  Author-email: Alec Follmer <ahfollmer@ucdavis.edu>
6
6
  Maintainer-email: Alec Follmer <ahfollmer@ucdavis.edu>
@@ -31,6 +31,9 @@ Provides-Extra: plot
31
31
  Requires-Dist: matplotlib>=3.6; extra == "plot"
32
32
  Provides-Extra: fit
33
33
  Requires-Dist: cloudpickle>=2.0; extra == "fit"
34
+ Provides-Extra: hpc
35
+ Requires-Dist: threadpoolctl>=3.1; extra == "hpc"
36
+ Requires-Dist: cloudpickle>=2.0; extra == "hpc"
34
37
  Provides-Extra: gui
35
38
  Requires-Dist: ipywidgets>=7.6; extra == "gui"
36
39
  Requires-Dist: matplotlib>=3.6; extra == "gui"
@@ -153,9 +156,10 @@ print('Best-fit g:', result.pfit)
153
156
  `progress='text'` prints RMSD, evaluation count and ETA as it runs, and
154
157
  interrupting the kernel returns the best fit so far.
155
158
 
156
- Population methods (swarm, genetic, grid, montecarlo, global) can evaluate each
157
- generation in parallel worker processes with `FitOptions(n_workers='auto')`. This
158
- is off by default. Each worker is a separate Python process with its own torch
159
+ With `FitOptions(n_workers='auto')`, model evaluations run in parallel worker
160
+ processes: each generation of the population methods (swarm, genetic, grid,
161
+ montecarlo, global), and the finite-difference probes of each levmar, trf and
162
+ lbfgsb Jacobian (1.5–3× faster for a 4-parameter pepper fit). This is off by default. Each worker is a separate Python process with its own torch
159
163
  (about 0.3–0.5 GB), so `'auto'` uses the cores you were allocated, at most 32, and
160
164
  no more workers than fit in half the free memory. A script that uses it needs the
161
165
  usual `if __name__ == '__main__':` guard around the code that runs the fit.
@@ -98,9 +98,10 @@ print('Best-fit g:', result.pfit)
98
98
  `progress='text'` prints RMSD, evaluation count and ETA as it runs, and
99
99
  interrupting the kernel returns the best fit so far.
100
100
 
101
- Population methods (swarm, genetic, grid, montecarlo, global) can evaluate each
102
- generation in parallel worker processes with `FitOptions(n_workers='auto')`. This
103
- is off by default. Each worker is a separate Python process with its own torch
101
+ With `FitOptions(n_workers='auto')`, model evaluations run in parallel worker
102
+ processes: each generation of the population methods (swarm, genetic, grid,
103
+ montecarlo, global), and the finite-difference probes of each levmar, trf and
104
+ lbfgsb Jacobian (1.5–3× faster for a 4-parameter pepper fit). This is off by default. Each worker is a separate Python process with its own torch
104
105
  (about 0.3–0.5 GB), so `'auto'` uses the cores you were allocated, at most 32, and
105
106
  no more workers than fit in half the free memory. A script that uses it needs the
106
107
  usual `if __name__ == '__main__':` guard around the code that runs the fit.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "torchspin"
7
- version = "0.6.7"
7
+ version = "0.8.0"
8
8
  description = "Differentiable PyTorch port of EasySpin - EPR/ESR spin Hamiltonian and spectrum simulation"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -49,6 +49,7 @@ Issues = "https://github.com/follmerlab/torchspin/issues"
49
49
  [project.optional-dependencies]
50
50
  plot = ["matplotlib>=3.6"]
51
51
  fit = ["cloudpickle>=2.0"] # process-pool esfit with notebook-defined models
52
+ hpc = ["threadpoolctl>=3.1", "cloudpickle>=2.0"] # BLAS thread caps (torchspin.parallel.thread_budget(blas=True)), process pools
52
53
  gui = ["ipywidgets>=7.6", "matplotlib>=3.6", "ipympl>=0.9", "ipython>=7", "cloudpickle>=2.0"] # interactive fitting panel (torchspin.fitgui)
53
54
  test = ["pytest>=7", "pytest-cov", "matplotlib>=3.6", "cloudpickle>=2.0", "ipywidgets>=7.6"]
54
55
  dev = ["pytest>=7", "pytest-cov", "build", "twine", "matplotlib>=3.6", "cloudpickle>=2.0", "ipywidgets>=7.6"]
@@ -25,7 +25,7 @@ try:
25
25
  __version__ = _pkg_version("torchspin")
26
26
  except _PkgNotFound:
27
27
  # Editable install during development, or version metadata unavailable.
28
- __version__ = "0.6.7+dev"
28
+ __version__ = "0.8.0+dev"
29
29
 
30
30
  # Idle OpenMP threads must sleep, not spin-wait (see torchspin/_omp.py and
31
31
  # docs/pitfalls.md, "Threads and performance"). This has to run before anything
@@ -24,6 +24,8 @@ from concurrent.futures import ThreadPoolExecutor
24
24
  import numpy as np
25
25
  import torch
26
26
 
27
+ from torchspin.parallel import inner_threads
28
+
27
29
  _MIN_BATCH = 32 # below this the pool overhead is not worth it
28
30
  _CUSOLVER_BATCHED_MAX = 32 # syevjBatched limit
29
31
  # Workspace the batched CUDA solver reserves per matrix. Measured on torch 2.14 / CUDA 13:
@@ -55,7 +57,9 @@ def _executor(w: int) -> ThreadPoolExecutor:
55
57
 
56
58
 
57
59
  def _pool_size(nb: int) -> int:
58
- return max(1, min(torch.get_num_threads(), nb // 8))
60
+ # inner_threads() is torch.get_num_threads(), or less inside a
61
+ # torchspin.parallel.thread_budget (e.g. in an esfit worker)
62
+ return max(1, min(inner_threads(), nb // 8))
59
63
 
60
64
 
61
65
  def _one(fn, np_fn, A: torch.Tensor, allow_numpy: bool = True):
@@ -236,7 +240,7 @@ def pool_map(fn, items: list):
236
240
  concurrently instead of contending. Falls back to a plain map for one item
237
241
  or one thread.
238
242
  """
239
- w = min(torch.get_num_threads(), len(items))
243
+ w = min(inner_threads(), len(items))
240
244
  if w <= 1:
241
245
  return [fn(it) for it in items]
242
246
  with _threads_lock:
@@ -0,0 +1,61 @@
1
+ """Degenerate-level bookkeeping for zero-field simulations (``Options.ZeroField``).
2
+
3
+ At ``B = 0`` the Hamiltonian is the same for every orientation and its levels
4
+ can be exactly degenerate (Kramers doublets, accidental degeneracies of
5
+ isotropic couplings). Inside a degenerate subspace the eigenbasis returned by
6
+ the eigensolver is arbitrary, so the rate of a single level pair is not
7
+ defined; only the rate summed over all pairs that connect two degenerate
8
+ clusters is (``tr(P_a O P_b O†)``). These helpers group the levels into
9
+ clusters and sum level-pair quantities over cluster pairs. Everything stays on
10
+ the autograd graph: the cluster assignment uses detached eigenvalues, the sums
11
+ are linear maps.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import torch
16
+
17
+ #: Relative tolerance (of the level spread) below which two levels count as degenerate.
18
+ CLUSTER_RTOL = 1e-9
19
+ #: Absolute floor of the tolerance, in the energy unit of the eigenvalues (MHz).
20
+ CLUSTER_ATOL = 1e-9
21
+
22
+
23
+ def level_clusters(E: torch.Tensor):
24
+ """Group ascending eigenvalues ``E`` (n,) into degenerate clusters.
25
+
26
+ Two neighboring levels belong to the same cluster when they differ by less
27
+ than ``max(CLUSTER_RTOL * (E_max - E_min), CLUSTER_ATOL)``. Returns
28
+ ``(labels, first, onehot)``: the cluster index of every level (n,), the
29
+ first (lowest) level of every cluster (K,), and the (n, K) float64 one-hot
30
+ membership matrix.
31
+ """
32
+ Ed = E.detach().real.to(torch.float64)
33
+ n = Ed.shape[0]
34
+ spread = float(Ed.max() - Ed.min()) if n else 0.0
35
+ tol = max(CLUSTER_RTOL * spread, CLUSTER_ATOL)
36
+ gaps = Ed[1:] - Ed[:-1]
37
+ new = torch.cat([torch.zeros(1, dtype=torch.long, device=Ed.device), (gaps > tol).long()])
38
+ labels = torch.cumsum(new, dim=0)
39
+ K = int(labels[-1]) + 1 if n else 0
40
+ starts = torch.cat([torch.ones(1, dtype=torch.bool, device=Ed.device), gaps > tol])
41
+ first = torch.nonzero(starts, as_tuple=True)[0] # labels are sorted
42
+ onehot = torch.zeros(n, K, dtype=torch.float64, device=Ed.device)
43
+ onehot[torch.arange(n, device=Ed.device), labels] = 1.0
44
+ return labels, first, onehot
45
+
46
+
47
+ def cluster_means(E: torch.Tensor, onehot: torch.Tensor) -> torch.Tensor:
48
+ """Mean eigenvalue of every cluster, (..., K) from (..., n)."""
49
+ return (E.real.to(torch.float64) @ onehot) / onehot.sum(dim=0)
50
+
51
+
52
+ def inter_cluster_pairs(labels: torch.Tensor):
53
+ """All level pairs ``u < v`` in different clusters and their cluster pairs.
54
+
55
+ Returns ``(iu, ju, ca, cb)``: level indices and cluster indices (``ca < cb``).
56
+ """
57
+ n = labels.shape[0]
58
+ iu, ju = torch.triu_indices(n, n, offset=1, device=labels.device)
59
+ keep = labels[iu] != labels[ju]
60
+ iu, ju = iu[keep], ju[keep]
61
+ return iu, ju, labels[iu], labels[ju]
@@ -56,6 +56,14 @@ def inputs_require_grad(*objs) -> bool:
56
56
  return any(torch.is_tensor(u) and u.requires_grad for u in v)
57
57
  return False
58
58
 
59
+ def _rg_deep(v) -> bool:
60
+ # SpinSystem.H0Extra is a list of (coeff, op) pairs: two levels deep
61
+ if torch.is_tensor(v):
62
+ return bool(v.requires_grad)
63
+ if isinstance(v, (list, tuple)):
64
+ return any(_rg_deep(u) for u in v)
65
+ return False
66
+
59
67
  for obj in objs:
60
68
  items = obj if isinstance(obj, (list, tuple)) else [obj]
61
69
  for it in items:
@@ -63,6 +71,8 @@ def inputs_require_grad(*objs) -> bool:
63
71
  continue
64
72
  if any(_rg(getattr(it, f.name, None)) for f in dataclasses.fields(it)):
65
73
  return True
74
+ if _rg_deep(getattr(it, 'H0Extra', None)):
75
+ return True
66
76
  return False
67
77
 
68
78
 
@@ -125,6 +125,8 @@ def cardamom(
125
125
  t:
126
126
  Time axis for FID, shape ``(nSteps,)``.
127
127
  """
128
+ from torchspin.spinsystem import _reject_h0extra
129
+ _reject_h0extra(sys, 'cardamom')
128
130
  if opt is None:
129
131
  opt = CardamomOptions()
130
132
 
@@ -914,6 +914,8 @@ def chili_sle(sys, exp, opt: Optional[ChiliSLEOptions] = None):
914
914
  verbose = opt.Verbosity >= 1
915
915
 
916
916
  # ---- system checks ------------------------------------------------------
917
+ from torchspin.spinsystem import _reject_h0extra
918
+ _reject_h0extra(sys, 'chili')
917
919
  if getattr(sys, 'n', None) is not None and any(v > 1 for v in sys.n) and not opt.PostConvNucs:
918
920
  raise ValueError("chili cannot handle sets of equivalent nuclei (Sys.n > 1) unless treated by post-convolution (Opt.PostConvNucs).")
919
921
  if getattr(sys, 'nn', None) is not None and bool(torch.any(torch.as_tensor(sys.nn) != 0)):
@@ -956,6 +958,8 @@ def chili_sle(sys, exp, opt: Optional[ChiliSLEOptions] = None):
956
958
  use_potential = potential is not None
957
959
 
958
960
  # ---- experiment ---------------------------------------------------------
961
+ from torchspin.experiment import require_positive_field
962
+ require_positive_field(exp) # Field = 0 is a pepper/salt-only option
959
963
  field_sweep = not exp.is_freq_swept
960
964
  nPoints = int(exp.nPoints)
961
965
  if field_sweep:
@@ -19,7 +19,7 @@ Algorithm
19
19
  from __future__ import annotations
20
20
 
21
21
  import math
22
- from typing import Optional
22
+ from typing import TYPE_CHECKING, Optional
23
23
 
24
24
  import torch
25
25
 
@@ -27,6 +27,9 @@ from torchspin.ham import ham
27
27
  from torchspin.ham_nz import ham_nz
28
28
  from torchspin.spinsystem import SpinSystem
29
29
 
30
+ if TYPE_CHECKING:
31
+ from torchspin.experiment import Options
32
+
30
33
 
31
34
  def endorfrq(
32
35
  sys: SpinSystem,
@@ -45,6 +48,7 @@ def endorfrq(
45
48
  _snmux: Optional[torch.Tensor] = None,
46
49
  _snmuy: Optional[torch.Tensor] = None,
47
50
  _snmuz: Optional[torch.Tensor] = None,
51
+ opt: Optional["Options"] = None,
48
52
  ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
49
53
  """Compute ENDOR transition frequencies at a fixed EPR field.
50
54
 
@@ -66,6 +70,18 @@ def endorfrq(
66
70
  mwFreq:
67
71
  Microwave frequency in GHz. Currently unused (reserved for
68
72
  orientation-selection weighting).
73
+ opt:
74
+ Optional :class:`~torchspin.experiment.Options`. Only
75
+ ``opt.Enhancement`` is read (``threshold`` stays the explicit
76
+ argument). With ``Enhancement=True`` the intensities use the total
77
+ magnetic moment (electron + nuclear, ``ham()``'s ``mux/muy/muz``)
78
+ perpendicular to the field instead of the nuclear moment, i.e. they
79
+ include hyperfine enhancement (EasySpin ``Opt.Enhancement='on'``).
80
+ As in EasySpin, electronic level pairs are then excluded (levels are
81
+ grouped by energy into blocks of ``prod(2I+1)``, valid when the
82
+ electron Zeeman/zero-field splitting exceeds the nuclear splittings)
83
+ and the ``threshold`` selection uses the nuclear-only rates.
84
+ ``None`` (default) = ``Enhancement=False``.
69
85
 
70
86
  Returns
71
87
  -------
@@ -83,6 +99,7 @@ def endorfrq(
83
99
  """
84
100
  if sys.nNuclei == 0:
85
101
  raise ValueError("endorfrq: spin system must contain at least one nucleus.")
102
+ enhancement = bool(getattr(opt, 'Enhancement', False)) if opt is not None else False
86
103
 
87
104
  # ── Step 1: Build Hamiltonians and moment operators ────────────────────
88
105
  # Use pre-built operators when provided (avoids redundant ham() calls in loops).
@@ -122,6 +139,10 @@ def endorfrq(
122
139
  # Nuclear moment perpendicular to field
123
140
  snmux_perp = nx_x * snmux + nx_y * snmuy + nx_z * snmuz # lab-x component
124
141
  snmuy_perp = ny_x * snmux + ny_y * snmuy + ny_z * snmuz # lab-y component
142
+ if enhancement:
143
+ # Total moment perpendicular to the field (hyperfine enhancement)
144
+ mux_perp = nx_x * mux + nx_y * muy + nx_z * muz
145
+ muy_perp = ny_x * mux + ny_y * muy + ny_z * muz
125
146
 
126
147
  # ── Step 3: Diagonalize H at B_field ──────────────────────────────────
127
148
  H_B = H0 - float(B_field) * muzL
@@ -138,6 +159,13 @@ def endorfrq(
138
159
  [j for i in range(nStates) for j in range(i + 1, nStates)],
139
160
  dtype=torch.long,
140
161
  )
162
+ if enhancement:
163
+ # EasySpin endorfrq: drop electronic transitions (level pairs in
164
+ # different blocks of prod(2I+1) energy-sorted levels).
165
+ n_nuc_states = int(round(math.prod(2.0 * float(i) + 1.0 for i in sys.I)))
166
+ same_block = (pairs_i_all // n_nuc_states) == (pairs_j_all // n_nuc_states)
167
+ pairs_i_all = pairs_i_all[same_block]
168
+ pairs_j_all = pairs_j_all[same_block]
141
169
 
142
170
  # All transition frequencies (E is ascending from eigh, so E[j]≥E[i])
143
171
  freqs_all = (E[pairs_j_all] - E[pairs_i_all]).abs() # (nPairs,)
@@ -163,6 +191,12 @@ def endorfrq(
163
191
  me_y = (V[:, pairs_i_all].conj() * op_y).sum(dim=0) # (nPairs,)
164
192
 
165
193
  intens_t = ((me_x.abs() ** 2 + me_y.abs() ** 2) / 2.0).real
194
+ if enhancement:
195
+ op_ex = mux_perp @ V[:, pairs_j_all]
196
+ me_ex = (V[:, pairs_i_all].conj() * op_ex).sum(dim=0)
197
+ op_ey = muy_perp @ V[:, pairs_j_all]
198
+ me_ey = (V[:, pairs_i_all].conj() * op_ey).sum(dim=0)
199
+ intens_enh = ((me_ex.abs() ** 2 + me_ey.abs() ** 2) / 2.0).real
166
200
  freqs_t = freqs_all
167
201
  pairs_i_t = pairs_i_all
168
202
  pairs_j_t = pairs_j_all
@@ -180,6 +214,8 @@ def endorfrq(
180
214
  keep = intens_t >= threshold * max_i
181
215
  freqs_t = freqs_t[keep]
182
216
  intens_t = intens_t[keep]
217
+ if enhancement:
218
+ intens_enh = intens_enh[keep]
183
219
  pairs_i_t = pairs_i_t[keep]
184
220
  pairs_j_t = pairs_j_t[keep]
185
221
 
@@ -189,6 +225,11 @@ def endorfrq(
189
225
  empty_t = torch.zeros((0, 2), dtype=torch.long)
190
226
  return empty_f, empty_i, empty_t
191
227
 
228
+ if enhancement:
229
+ # Selection above used the nuclear-only rates (EasySpin); report the
230
+ # enhanced intensities.
231
+ intens_t = intens_enh
232
+
192
233
  # Sort by frequency (ascending)
193
234
  order = torch.argsort(freqs_t)
194
235
  freqs_t = freqs_t[order]
@@ -35,6 +35,7 @@ def endorfrq_perturb(
35
35
  theta: float = 0.0,
36
36
  order: int = 2,
37
37
  nuclei: Optional[list[int]] = None,
38
+ opt=None,
38
39
  ) -> tuple[torch.Tensor, torch.Tensor]:
39
40
  """ENDOR transition frequencies via perturbation theory (Iwasaki 1974).
40
41
 
@@ -51,6 +52,11 @@ def endorfrq_perturb(
51
52
  Perturbation order: 1 or 2 (default 2).
52
53
  nuclei:
53
54
  List of 0-based nucleus indices to include. Default: all nuclei.
55
+ opt:
56
+ Optional :class:`~torchspin.experiment.Options`. Only
57
+ ``opt.Enhancement`` is read: hyperfine enhancement is not available
58
+ in perturbation theory, so ``Enhancement=True`` raises (EasySpin's
59
+ ``endorfrq_perturb`` silently ignores it). Use :func:`endorfrq`.
54
60
 
55
61
  Returns
56
62
  -------
@@ -63,6 +69,8 @@ def endorfrq_perturb(
63
69
  ------
64
70
  ValueError
65
71
  If system has more than one electron or other unsupported features.
72
+ NotImplementedError
73
+ If ``opt.Enhancement`` is True.
66
74
 
67
75
  Notes
68
76
  -----
@@ -76,6 +84,13 @@ def endorfrq_perturb(
76
84
 
77
85
  ENDOR transitions connect states mI and mI+1 within the same mS manifold.
78
86
  """
87
+ if opt is not None and bool(getattr(opt, 'Enhancement', False)):
88
+ raise NotImplementedError(
89
+ "endorfrq_perturb: Options.Enhancement=True (hyperfine enhancement) is not "
90
+ "implemented in perturbation theory; use endorfrq (matrix diagonalization)."
91
+ )
92
+ from torchspin.spinsystem import _reject_h0extra
93
+ _reject_h0extra(sys, 'endorfrq_perturb (perturbation theory)')
79
94
  if sys.nElectrons != 1:
80
95
  raise ValueError(
81
96
  f"endorfrq_perturb: nElectrons must be 1, got {sys.nElectrons}."