torchspin 0.6.0__tar.gz → 0.6.2__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 (127) hide show
  1. {torchspin-0.6.0 → torchspin-0.6.2}/CHANGELOG.md +146 -0
  2. {torchspin-0.6.0 → torchspin-0.6.2}/CITATION.cff +2 -2
  3. {torchspin-0.6.0 → torchspin-0.6.2}/PKG-INFO +1 -1
  4. {torchspin-0.6.0 → torchspin-0.6.2}/pyproject.toml +1 -1
  5. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/__init__.py +1 -1
  6. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/_linalg.py +31 -2
  7. torchspin-0.6.2/torchspin/_rng.py +53 -0
  8. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/autograd.py +24 -1
  9. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/cardamom.py +39 -12
  10. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/esfit.py +218 -58
  11. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/fitgui.py +3 -1
  12. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/garlic.py +14 -1
  13. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/pepper.py +41 -11
  14. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/pepper_autograd.py +31 -3
  15. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfields_batch.py +4 -1
  16. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/saffron.py +17 -11
  17. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/sigeq.py +1 -1
  18. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/spidyan.py +47 -0
  19. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/spinsystem.py +4 -3
  20. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/stochtraj_diffusion.py +21 -14
  21. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/stochtraj_jump.py +11 -6
  22. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin.egg-info/PKG-INFO +1 -1
  23. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin.egg-info/SOURCES.txt +1 -0
  24. {torchspin-0.6.0 → torchspin-0.6.2}/LICENSE.md +0 -0
  25. {torchspin-0.6.0 → torchspin-0.6.2}/MANIFEST.in +0 -0
  26. {torchspin-0.6.0 → torchspin-0.6.2}/README.md +0 -0
  27. {torchspin-0.6.0 → torchspin-0.6.2}/setup.cfg +0 -0
  28. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/_cardamom_istos.py +0 -0
  29. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/_cardamom_propagatedm.py +0 -0
  30. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/_cardamom_utils.py +0 -0
  31. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/_compile.py +0 -0
  32. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/angmom.py +0 -0
  33. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/autoguess.py +0 -0
  34. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/batch.py +0 -0
  35. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/blochsteady.py +0 -0
  36. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/chili.py +0 -0
  37. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/chili_sle.py +0 -0
  38. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/constants.py +0 -0
  39. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/convspec.py +0 -0
  40. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ctafft.py +0 -0
  41. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/curry.py +0 -0
  42. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/data/FourierSeriesCoefficients.txt +0 -0
  43. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/data/GaussianCascadeCoefficients.txt +0 -0
  44. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/data/isotopedata.txt +0 -0
  45. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/data/spacegroups.txt +0 -0
  46. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/dataproc.py +0 -0
  47. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/dipbackground.py +0 -0
  48. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/dipkernel.py +0 -0
  49. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/diptensor.py +0 -0
  50. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/endorfrq.py +0 -0
  51. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/endorfrq_perturb.py +0 -0
  52. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/eprload.py +0 -0
  53. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/eprsave.py +0 -0
  54. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/evolve.py +0 -0
  55. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ewrls.py +0 -0
  56. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/excitation.py +0 -0
  57. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/exciteprofile.py +0 -0
  58. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/experiment.py +0 -0
  59. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/exponfit.py +0 -0
  60. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/fastmotion.py +0 -0
  61. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/fdaxis.py +0 -0
  62. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/gridcheck.py +0 -0
  63. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham.py +0 -0
  64. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_cf.py +0 -0
  65. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_ee.py +0 -0
  66. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_ez.py +0 -0
  67. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_ezho.py +0 -0
  68. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_hf.py +0 -0
  69. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_nn.py +0 -0
  70. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_nq.py +0 -0
  71. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_nz.py +0 -0
  72. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_oz.py +0 -0
  73. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_so.py +0 -0
  74. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ham_zf.py +0 -0
  75. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/hamsymm.py +0 -0
  76. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/initstate.py +0 -0
  77. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/isotopologues.py +0 -0
  78. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/levels.py +0 -0
  79. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/levelsplot.py +0 -0
  80. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/lineshape.py +0 -0
  81. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/lpsvd.py +0 -0
  82. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/makespec.py +0 -0
  83. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/mdhmm.py +0 -0
  84. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/mdload.py +0 -0
  85. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/mdtraj2oripot.py +0 -0
  86. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ml.py +0 -0
  87. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/mlpsvd.py +0 -0
  88. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/nucdata.py +0 -0
  89. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/nucfrq2d.py +0 -0
  90. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/orca2torchspin.py +0 -0
  91. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/ordering.py +0 -0
  92. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/oripotentialplot.py +0 -0
  93. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/orisel.py +0 -0
  94. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/photoselect.py +0 -0
  95. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/plegendre.py +0 -0
  96. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/propint.py +0 -0
  97. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/pulse.py +0 -0
  98. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/py.typed +0 -0
  99. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/rapidscan2spc.py +0 -0
  100. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfields.py +0 -0
  101. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfields_eig.py +0 -0
  102. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfields_hybrid.py +0 -0
  103. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfields_perturb.py +0 -0
  104. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfreqs_matrix.py +0 -0
  105. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resfreqs_perturb.py +0 -0
  106. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resonator.py +0 -0
  107. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/resonatorprofile.py +0 -0
  108. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/rfmixer.py +0 -0
  109. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/rotations.py +0 -0
  110. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/rotutils.py +0 -0
  111. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/saffron_pathways.py +0 -0
  112. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/saffron_peaks.py +0 -0
  113. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/saffron_thyme.py +0 -0
  114. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/salt.py +0 -0
  115. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/signalprocessing.py +0 -0
  116. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/sitetransforms.py +0 -0
  117. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/sphgrid.py +0 -0
  118. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/spinladder.py +0 -0
  119. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/spinops.py +0 -0
  120. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/stackplot.py +0 -0
  121. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/stev.py +0 -0
  122. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/strainwidth.py +0 -0
  123. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/transmitter.py +0 -0
  124. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin/utils.py +0 -0
  125. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin.egg-info/dependency_links.txt +0 -0
  126. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin.egg-info/requires.txt +0 -0
  127. {torchspin-0.6.0 → torchspin-0.6.2}/torchspin.egg-info/top_level.txt +0 -0
@@ -4,6 +4,152 @@ All notable changes to torchspin will be documented in this file.
4
4
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [0.6.2] — 2026-11-08
10
+
11
+ Bug fixes found while running the GPU tests on a CUDA host.
12
+
13
+ ### Fixed
14
+
15
+ - **pepper on CUDA failed in every public release (0.3.0–0.6.1)** with
16
+ "Expected all tensors to be on the same device". The transition pre-selection
17
+ (`_preselect_pairs`) built its rate and mask tensors on the CPU, so every
18
+ `Options(device='cuda')` call aborted before simulating. The CPU-vs-CUDA
19
+ consistency tests catch this, but they only run on a GPU host.
20
+ - **pepper on CUDA ran out of memory on dense strain grids.** Batched CUDA
21
+ eigendecompositions went to cuSOLVER in a single call. The solver reserves
22
+ about 1–2 MB of workspace per matrix whatever its size, so strain broadening
23
+ (one 6×6 diagonalization per resonance) asked for tens of GB. CUDA batches
24
+ are now split into chunks that fit in half the free GPU memory.
25
+ - **pepper on CUDA was up to 25× slower than on CPU.** The resonance search
26
+ finds cubic roots as eigenvalues of 3×3 companion matrices. On CUDA, torch
27
+ computes general (non-Hermitian) eigenvalues one matrix at a time with a
28
+ host sync each, hundreds of thousands per call: 34.7 s for the Mn(II)
29
+ matrix workload against 1.4 s on 32 CPU threads. These small solves now run
30
+ as one batched CPU call, the same LAPACK routine the CPU path uses.
31
+ - **pepper was not thread-safe.** The slot keys of the matrix method were kept
32
+ in a function attribute shared by the whole process. With concurrent pepper
33
+ calls, such as `esfit(..., FitOptions(workers='threads'))` or any user thread
34
+ pool, one call could read another's keys: `_filter_slots` raised
35
+ `IndexError: list index out of range`, or `separate='transitions'` mislabeled
36
+ transitions. The keys are now per thread. This was found when a benchmark
37
+ fit with the thread backend crashed on a single-core allocation.
38
+ - `sigeq(..., polarization=True)` built its identity matrix on the CPU, so it
39
+ failed with a device mismatch for a CUDA Hamiltonian.
40
+
41
+ ### Changed — behavior differs from 0.6.1
42
+
43
+ - **Seeded cardamom results no longer depend on the thread count.** The fast
44
+ path groups orientations, and the group size scales with
45
+ `torch.get_num_threads()`. Every group used to draw its trajectories from the
46
+ same `CardamomPar.seed`, so a seeded spectrum changed with the number of
47
+ threads, and orientations in different groups shared identical trajectories.
48
+ Each orientation now draws from its own stream, derived from the seed with
49
+ `numpy.random.SeedSequence`. The global-dynamics (`DiffGlobal`) trajectories
50
+ of a group also started from a spiral grid over the whole group rather than
51
+ over `nTraj`, which made the result depend on the group size too; they now
52
+ start from the same per-orientation grid as the serial path. Seeded cardamom
53
+ spectra differ from 0.6.1. Unseeded runs are unaffected.
54
+
55
+ ### Added
56
+
57
+ - `DiffusionPar.seed` and `JumpPar.seed` accept a sequence of per-block seeds:
58
+ the trajectories split into equal blocks with independent random streams.
59
+
60
+ ### Tests
61
+
62
+ - The garlic CPU-vs-CUDA test compared the CPU with itself (garlic has no device
63
+ path) and is removed. salt and `sigeq` have real CPU-vs-CUDA tests.
64
+
65
+ ## [0.6.1] — 2026-11-04
66
+
67
+ Fixes for GitHub issues #5–#9. Each one was a case where torchspin returned a
68
+ plausible result without any warning that it was wrong. Two more defects found
69
+ while verifying them are fixed too: dict-style esfit ignored all but the last
70
+ element of each array field, and pepper_autograd returned NaN gradients for
71
+ an exactly isotropic A.
72
+
73
+ ### Changed — behavior differs from 0.6.0
74
+
75
+ - **esfit `autoscale='lsq'` with a negative unconstrained scale** (#6). The
76
+ scale is now the sign-constrained least-squares optimum: 0, with the
77
+ baseline refitted alone. EasySpin, and torchspin up to 0.6.0, took
78
+ `abs(scale)` but kept the baseline solved for the opposite sign. That
79
+ objective is not a least-squares fit, so optimizers walked away from the
80
+ true minimum (an inversion-recovery fit with `exp(-t/T)` ran to its bound).
81
+ esfit warns when the final fit has a negative scale. The old behavior is
82
+ `FitOptions(lsq_negative_scale='abs')`.
83
+ - **esfit uncertainties** (#5). A parameter that has no effect on the
84
+ residuals at the finite-difference step now gets `pstd = nan` and a
85
+ warning, not `pstd = 0`, which read as a perfectly determined parameter.
86
+ - **pepper with inputs that require grad** (#7) now returns a spectrum on the
87
+ autograd graph by dispatching to `pepper_autograd`. It used to return a
88
+ detached spectrum without any warning. Unsupported configurations raise an
89
+ error that names `pepper_autograd`.
90
+ - **saffron with a predefined `Sequence` and nonzero `Exp.tp`** (#9) now raises,
91
+ as `saffron.m` 351 does, in every simulation mode. 0.6.0 meant to do this,
92
+ but the check sat in the fast path, and nonzero `tp` routed to the
93
+ real-pulse engine first. Its predefined templates use fixed 16/32 ns pulses
94
+ and never read `Exp.tp`, so the requested pulse lengths were silently
95
+ ignored.
96
+
97
+ ### Fixed
98
+
99
+ - **Dict-style esfit fitted only the last element of each array field.**
100
+ `TorchSpinParameterHandler.to_dict` rebuilt each element from the original
101
+ `p0`, so varying `g[0,0]`, `A[0,0]` or `lw[0]` never reached the simulator.
102
+ Present since 0.3.0.
103
+ - **esfit was blind to line positions with garlic's default
104
+ `AccumMethod='binning'`** (#5). The binned spectrum is piecewise-constant in
105
+ g and A, so every finite-difference Jacobian was zero for them and levmar
106
+ never moved A. Dict-style esfit now runs garlic with `'linear'` when
107
+ `AccumMethod` is unset. levmar, trf and the uncertainty estimate warn when
108
+ a Jacobian column is dead, which also covers custom models that wrap garlic.
109
+ - **esfit baselines with `autoscale='none'` and `'maxabs'`.** `'none'` fitted
110
+ the baseline jointly with a free scale and then applied it at scale 1.
111
+ `'maxabs'` built `scale * x**sum(arange)` and not a polynomial. Both now fit
112
+ the polynomial to the data minus the scaled model.
113
+ - **pepper_autograd and natural-abundance nuclei** (#7). `Nucs=['Zr']` failed
114
+ in `nucdata`. Components are now expanded into isotopologues and summed with
115
+ `Sys.weight` × abundance, as in pepper. `Sys.weight` was previously ignored,
116
+ and lists of components are accepted.
117
+ - **Quadrupole shorthand `[e2qQ/h, eta]` dropped the graph** (#7). It was
118
+ converted with `float()`, so dL/dQ was silently zero in a fit. The principal
119
+ values are now built with torch ops.
120
+ - **NaN gradients in pepper_autograd's axial-grid interpolation.** When a
121
+ transition slot was missing at some orientations (e.g. exactly isotropic A),
122
+ `torch.where`'s backward computed 0·NaN. The forward output is unchanged.
123
+ - The preselection cutoff no longer triggers PyTorch's "converting a tensor
124
+ with requires_grad=True to a scalar" warning.
125
+
126
+ ### Added
127
+
128
+ - spidyan warnings (#8) for a user-set `IntTimeStep` coarser than Nyquist/2
129
+ (a π pulse is ~3 % off there and 40 % at Nyquist), and for `SimFreq` less
130
+ than 5 nutation frequencies below the lowest pulse carrier.
131
+ - `docs/pitfalls.md` (#8): perturbation errors at large A/ν (measured on ⁹¹Zr,
132
+ A/ν = 0.08), binned garlic spectra in fits, the lsq sign, satellite-assignment
133
+ minima, Q fits started at zero, and the pulse-simulation limits.
134
+ - `examples/fitting/large_hyperfine_fit.py`: a staged fit of a synthetic
135
+ natural-abundance Zr spectrum.
136
+ - `torchspin.autograd.inputs_require_grad`.
137
+
138
+ ### Fixed — a flaky tolerance in the real-pulse frame-rotation test
139
+
140
+ `test_frame_tilts_match_an_equivalent_sample_tilt` asserted that a tensor tilt
141
+ and an equal sample tilt agree to `1e-12` of the peak, copying EasySpin's own
142
+ `areequal(y1, y2, 1e-12, 'abs')`. That bound sits below the round-off floor of
143
+ torchspin's route, which conjugates the Hamiltonian into the lab-frame basis
144
+ rather than rotating the interaction tensors: the two Hamiltonians agree to
145
+ 2e-16 relative, but integrating that over the 0.3 µs detection window makes a
146
+ phase error growing linearly in time, 2e-11 absolute on a signal of magnitude
147
+ 12. The test passed on two CI runners and failed on a third with identical
148
+ code. It is now scored as a relative L2 error (measured 1.8e-12 against a
149
+ 1e-9 bound) plus a per-point bound at 1e-9 of the peak, and the mechanism is
150
+ written down in the docstring and in KNOWN_LIMITATIONS.md. Library code is
151
+ unchanged; both sides remain validated against MATLAB at ~1e-12.
152
+
7
153
  ## [0.6.0] — 2026-10-19
8
154
 
9
155
  Follow-up to 0.5.0: the pulse-EPR test suites now assert the relative L2 error
@@ -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.5.0"
6
- date-released: "2026-10-19"
5
+ version: "0.6.2"
6
+ date-released: "2026-11-08"
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.0
3
+ Version: 0.6.2
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>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "torchspin"
7
- version = "0.6.0"
7
+ version = "0.6.2"
8
8
  description = "Differentiable PyTorch port of EasySpin - EPR/ESR spin Hamiltonian and spectrum simulation"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -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.0+dev"
28
+ __version__ = "0.6.2+dev"
29
29
 
30
30
  from torchspin._compile import maybe_compile, set_compile_enabled, is_compile_available
31
31
  from torchspin.autograd import differentiable_spectrum
@@ -26,6 +26,11 @@ import torch
26
26
 
27
27
  _MIN_BATCH = 32 # below this the pool overhead is not worth it
28
28
  _CUSOLVER_BATCHED_MAX = 32 # syevjBatched limit
29
+ # Workspace the batched CUDA solver reserves per matrix. Measured on torch 2.14 / CUDA 13:
30
+ # about 1.1-1.5 MB per matrix at every size from 6x6 to 32x32, so an unchunked batch of
31
+ # 32768 6x6 matrices asked for 37 GB. Use the upper end, with headroom.
32
+ _CUDA_WS_PER_MATRIX = 2 * 2**20
33
+ _CUDA_MIN_CHUNK = 256
29
34
  _executors: dict = {}
30
35
 
31
36
  # torch.set_num_threads is process-global, so the save/set/restore in _pooled and
@@ -163,6 +168,30 @@ class _EighDegenerateSafe(torch.autograd.Function):
163
168
  return 0.5 * (gH + gH.conj().transpose(-2, -1))
164
169
 
165
170
 
171
+ def _cuda_chunk(nb: int, device) -> int:
172
+ """Matrices per batched CUDA eigensolver call that fit in half the free memory."""
173
+ try:
174
+ free, _ = torch.cuda.mem_get_info(device)
175
+ except Exception:
176
+ free = 4 * 2**30
177
+ return max(_CUDA_MIN_CHUNK, min(nb, int(0.5 * free) // _CUDA_WS_PER_MATRIX))
178
+
179
+
180
+ def _cuda_chunked(fn, H: torch.Tensor):
181
+ """Run a batched CUDA eigensolver in memory-bounded chunks (see _CUDA_WS_PER_MATRIX)."""
182
+ n = H.shape[-1]
183
+ nb = H.shape[:-2].numel()
184
+ chunk = _cuda_chunk(nb, H.device)
185
+ if chunk >= nb:
186
+ return fn(H)
187
+ flat = H.reshape(nb, n, n)
188
+ parts = [fn(flat[i:i + chunk]) for i in range(0, nb, chunk)]
189
+ if isinstance(parts[0], tuple):
190
+ return (torch.cat([p[0] for p in parts]).reshape(*H.shape[:-1]),
191
+ torch.cat([p[1] for p in parts]).reshape(H.shape))
192
+ return torch.cat(parts).reshape(*H.shape[:-1])
193
+
194
+
166
195
  def eigh(H: torch.Tensor):
167
196
  """Batched ``torch.linalg.eigh`` (see module docstring); on the autograd graph
168
197
  the backward is the degeneracy-safe variant (:class:`_EighDegenerateSafe`)."""
@@ -173,7 +202,7 @@ def eigh(H: torch.Tensor):
173
202
  nb = H.shape[:-2].numel()
174
203
  if H.is_cuda:
175
204
  if H.shape[-1] <= _CUSOLVER_BATCHED_MAX or nb < 4:
176
- return _safe_eigh(H)
205
+ return _cuda_chunked(_safe_eigh, H)
177
206
  E, V = eigh(H.cpu())
178
207
  return E.to(H.device), V.to(H.device)
179
208
  res = _pooled(_safe_eigh, H)
@@ -191,7 +220,7 @@ def eigvalsh(H: torch.Tensor):
191
220
  nb = H.shape[:-2].numel()
192
221
  if H.is_cuda:
193
222
  if H.shape[-1] <= _CUSOLVER_BATCHED_MAX or nb < 4:
194
- return _safe_eigvalsh(H)
223
+ return _cuda_chunked(_safe_eigvalsh, H)
195
224
  return eigvalsh(H.cpu()).to(H.device)
196
225
  res = _pooled(_safe_eigvalsh, H)
197
226
  if isinstance(res, torch.Tensor):
@@ -0,0 +1,53 @@
1
+ """Reproducible random streams for blocks of stochastic trajectories.
2
+
3
+ A seeded stochastic simulation must give the same result however its work is split:
4
+ across thread counts, orientation groups, processes or cluster tasks. To guarantee
5
+ that, every independent unit of work (one orientation's block of trajectories) gets
6
+ its own random stream, derived from the user's seed with
7
+ :class:`numpy.random.SeedSequence`. A unit then draws the same numbers whether it is
8
+ simulated alone or batched together with others.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Callable, List, Optional, Sequence, Tuple, Union
13
+
14
+ import numpy as np
15
+
16
+ SeedLike = Union[None, int, np.integer, np.random.SeedSequence, np.random.Generator]
17
+
18
+
19
+ def child_seeds(seed: Optional[int], n: int, stream: int = 0) -> Optional[List[np.random.SeedSequence]]:
20
+ """``n`` independent child seeds of ``seed`` for the given ``stream``.
21
+
22
+ Different ``stream`` values (e.g. 0 = local dynamics, 1 = global dynamics) give
23
+ unrelated families of seeds. Returns ``None`` when ``seed`` is ``None``, which keeps
24
+ unseeded runs non-deterministic.
25
+ """
26
+ if seed is None:
27
+ return None
28
+ return np.random.SeedSequence([int(seed), int(stream)]).spawn(int(n))
29
+
30
+
31
+ def traj_generators(seed: Union[SeedLike, Sequence[SeedLike]], n_traj: int) -> List[Tuple[np.random.Generator, int]]:
32
+ """Generators and their trajectory counts for ``n_traj`` trajectories.
33
+
34
+ A scalar seed (or ``None``) gives one generator for all trajectories, the
35
+ long-standing behavior. A sequence of ``B`` seeds splits the trajectories into
36
+ ``B`` consecutive equal blocks, each drawn from its own generator.
37
+ """
38
+ if seed is None or isinstance(seed, (int, np.integer, np.random.SeedSequence, np.random.Generator)):
39
+ return [(np.random.default_rng(seed), int(n_traj))]
40
+ seeds = list(seed)
41
+ if not seeds or n_traj % len(seeds):
42
+ raise ValueError(f"{len(seeds)} seed blocks do not divide {n_traj} trajectories evenly")
43
+ per = n_traj // len(seeds)
44
+ return [(np.random.default_rng(s), per) for s in seeds]
45
+
46
+
47
+ def draw(gens: List[Tuple[np.random.Generator, int]], fn: Callable[[np.random.Generator, int], np.ndarray],
48
+ axis: int) -> np.ndarray:
49
+ """``fn(generator, n)`` for every block, concatenated along the trajectory ``axis``."""
50
+ if len(gens) == 1:
51
+ g, n = gens[0]
52
+ return fn(g, n)
53
+ return np.concatenate([fn(g, n) for g, n in gens], axis=axis)
@@ -36,13 +36,36 @@ from typing import Optional
36
36
 
37
37
  import torch
38
38
 
39
- __all__ = ['differentiable_spectrum']
39
+ __all__ = ['differentiable_spectrum', 'inputs_require_grad']
40
40
 
41
41
 
42
42
  # ---------------------------------------------------------------------------
43
43
  # N-spin broadband helpers
44
44
  # ---------------------------------------------------------------------------
45
45
 
46
+ def inputs_require_grad(*objs) -> bool:
47
+ """True if any tensor field of the given SpinSystem/Experiment objects (or
48
+ lists of them) requires grad. Lists and tuples of tensors (e.g. ``lw``) are
49
+ searched one level deep."""
50
+ import dataclasses
51
+
52
+ def _rg(v) -> bool:
53
+ if torch.is_tensor(v):
54
+ return bool(v.requires_grad)
55
+ if isinstance(v, (list, tuple)):
56
+ return any(torch.is_tensor(u) and u.requires_grad for u in v)
57
+ return False
58
+
59
+ for obj in objs:
60
+ items = obj if isinstance(obj, (list, tuple)) else [obj]
61
+ for it in items:
62
+ if it is None or not dataclasses.is_dataclass(it):
63
+ continue
64
+ if any(_rg(getattr(it, f.name, None)) for f in dataclasses.fields(it)):
65
+ return True
66
+ return False
67
+
68
+
46
69
  def _broadband_spectrum(
47
70
  sys: 'SpinSystem',
48
71
  mwFreq_GHz: float,
@@ -36,6 +36,7 @@ from scipy.interpolate import interp1d
36
36
 
37
37
  from torchspin._cardamom_propagatedm import propagate_fast, propagate_istos
38
38
  from torchspin._cardamom_utils import spiral_grid
39
+ from torchspin._rng import child_seeds as _child_seeds
39
40
  from torchspin.constants import BMAGN, GFREE, PLANCK
40
41
  from torchspin.stochtraj_diffusion import (
41
42
  stochtraj_diffusion, DiffusionPar,
@@ -197,6 +198,14 @@ def cardamom(
197
198
  DiffGlobal = np.atleast_1d(np.asarray(DiffGlobal, dtype=np.float64))
198
199
  includeGlobalDynamics = DiffGlobal is not None
199
200
 
201
+ # --- Random streams ---
202
+ # One stream per orientation (local dynamics) and one per orientation (global
203
+ # dynamics), derived from par.seed: an orientation draws the same trajectories
204
+ # whether it is simulated alone or in a group, so seeded results do not depend
205
+ # on the group size, the thread count, or how orientations are distributed.
206
+ loc_seeds = _child_seeds(par.seed, nOrients, stream=0)
207
+ glob_seeds = _child_seeds(par.seed, nOrients, stream=1)
208
+
200
209
  # --- Main orientation loop ---
201
210
  TDSignals = []
202
211
 
@@ -208,6 +217,8 @@ def cardamom(
208
217
  # group size: amortises the per-step Python overhead, but large arrays
209
218
  # fall out of cache — scale the budget with the available threads
210
219
  import torch as _torch
220
+ # the group size may depend on the thread count: each orientation draws from
221
+ # its own seed stream (loc_seeds / glob_seeds), so seeded results do not
211
222
  budget = min(2e6, 2e5 * _torch.get_num_threads())
212
223
  G = max(1, min(nOrients, int(budget // max(1, par.nTraj * nStepsSpin))))
213
224
  for g0 in range(0, nOrients, G):
@@ -215,12 +226,17 @@ def cardamom(
215
226
  Gk = len(ids)
216
227
  if opt.Verbosity >= 1:
217
228
  print(f" Orientations {ids[0] + 1}-{ids[-1] + 1}/{nOrients}")
218
- RTrajLocal, _ = _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, repeats=Gk)
229
+ RTrajLocal, _ = _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, repeats=Gk,
230
+ seeds=None if loc_seeds is None else [loc_seeds[i] for i in ids])
219
231
  qLab = np.stack([_euler2quat_active(0.0, gridTheta[i], gridPhi[i]) for i in ids], axis=1) # (4, Gk)
220
232
  qLab_traj = np.repeat(np.repeat(qLab[:, np.newaxis, :], nStepsSpin, axis=1), par.nTraj, axis=2) # (4, nSteps, Gk*nTraj)
221
233
  if includeGlobalDynamics:
234
+ # start every orientation's block from the spiral grid over nTraj, as the
235
+ # per-orientation path does (a spiral over Gk*nTraj would make the
236
+ # result depend on the group size)
222
237
  diff_par = DiffusionPar(dt=dtSpin, nSteps=nStepsSpin, nTraj=Gk * par.nTraj,
223
- seed=None if par.seed is None else par.seed + 1)
238
+ OriStart=np.tile(_spiral_start(par.nTraj), (1, Gk)),
239
+ seed=None if glob_seeds is None else [glob_seeds[i] for i in ids])
224
240
  _, _, qGlobal = stochtraj_diffusion(DiffGlobal, diff_par)
225
241
  qLab_traj = _quatmult(qLab_traj, qGlobal)
226
242
  RLab = _quat_to_rotmat_batch(qLab_traj)
@@ -238,7 +254,8 @@ def cardamom(
238
254
 
239
255
  # Generate local trajectory
240
256
  RTrajLocal, qTrajLocal = _generate_local_trajectory(
241
- par, sys, Diff, dtSpatial, nStepsSpatial, md
257
+ par, sys, Diff, dtSpatial, nStepsSpatial, md,
258
+ seeds=None if loc_seeds is None else [loc_seeds[iOri]],
242
259
  )
243
260
 
244
261
  # Lab-frame rotation for this orientation
@@ -250,7 +267,7 @@ def cardamom(
250
267
  if includeGlobalDynamics:
251
268
  diff_par = DiffusionPar(
252
269
  dt=dtSpin, nSteps=nStepsSpin, nTraj=par.nTraj,
253
- seed=None if par.seed is None else par.seed + 1,
270
+ seed=None if glob_seeds is None else [glob_seeds[iOri]],
254
271
  )
255
272
  _, _, qGlobal = stochtraj_diffusion(DiffGlobal, diff_par)
256
273
  # Combine: qLab = qLab * qGlobal (Hamilton product, vectorised)
@@ -346,11 +363,23 @@ def _get_linewidth(sys) -> np.ndarray:
346
363
  return lw[:2]
347
364
 
348
365
 
349
- def _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, repeats: int = 1):
366
+ def _spiral_start(n_traj: int) -> np.ndarray:
367
+ """(3, n_traj) Euler angles of the spiral starting grid stochtraj_diffusion
368
+ builds for ``n_traj`` trajectories when no OriStart or potential is given."""
369
+ pts = np.linspace(-1, 1, n_traj)
370
+ return np.stack([np.sqrt(np.pi * n_traj) * np.arcsin(pts), np.arccos(pts),
371
+ np.sqrt(np.pi * n_traj) * np.arcsin(pts)], axis=0)
372
+
373
+
374
+ def _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, repeats: int = 1,
375
+ seeds=None):
350
376
  """Local trajectories for one orientation, or for ``repeats`` orientations at
351
377
  once (``repeats`` consecutive blocks of ``par.nTraj`` trajectories with the
352
- same starting orientations)."""
353
- """Generate local rotational trajectory based on the model."""
378
+ same starting orientations).
379
+
380
+ ``seeds`` holds one seed per block (``repeats`` entries), or is ``None`` for an
381
+ unseeded run.
382
+ """
354
383
  if par.Model == 'diffusion':
355
384
  Potential = getattr(sys, 'Potential', None)
356
385
  if Potential is not None:
@@ -365,14 +394,12 @@ def _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, rep
365
394
  OriStart = np.tile(OriStart, (1, par.nTraj))
366
395
  elif Potential is None:
367
396
  # the spiral starting grid stochtraj_diffusion would build for nTraj
368
- pts = np.linspace(-1, 1, par.nTraj)
369
- OriStart = np.stack([np.sqrt(np.pi * par.nTraj) * np.arcsin(pts), np.arccos(pts),
370
- np.sqrt(np.pi * par.nTraj) * np.arcsin(pts)], axis=0)
397
+ OriStart = _spiral_start(par.nTraj)
371
398
  if OriStart is not None:
372
399
  OriStart = np.tile(OriStart, (1, repeats))
373
400
  diff_par = DiffusionPar(
374
401
  dt=dtSpatial, nSteps=nStepsSpatial, nTraj=par.nTraj * repeats,
375
- OriStart=OriStart, seed=par.seed,
402
+ OriStart=OriStart, seed=seeds,
376
403
  )
377
404
  _, RTraj, qTraj = stochtraj_diffusion(Diff, diff_par, Potential=Potential)
378
405
  return RTraj, qTraj
@@ -389,7 +416,7 @@ def _generate_local_trajectory(par, sys, Diff, dtSpatial, nStepsSpatial, md, rep
389
416
  if Orientations is not None:
390
417
  Orientations = np.asarray(Orientations, dtype=np.float64)
391
418
 
392
- jump_par = JumpPar(dt=dtSpatial, nSteps=nStepsSpatial, nTraj=par.nTraj * repeats, seed=par.seed)
419
+ jump_par = JumpPar(dt=dtSpatial, nSteps=nStepsSpatial, nTraj=par.nTraj * repeats, seed=seeds)
393
420
  _, RTraj, qTraj, _ = stochtraj_jump(
394
421
  TransRates=TransRates, TransProb=TransProb,
395
422
  Orientations=Orientations, par=jump_par,