torchspin 0.6.4__tar.gz → 0.6.5__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 (129) hide show
  1. {torchspin-0.6.4 → torchspin-0.6.5}/CHANGELOG.md +25 -0
  2. {torchspin-0.6.4 → torchspin-0.6.5}/CITATION.cff +2 -2
  3. {torchspin-0.6.4 → torchspin-0.6.5}/PKG-INFO +44 -3
  4. {torchspin-0.6.4 → torchspin-0.6.5}/README.md +43 -2
  5. {torchspin-0.6.4 → torchspin-0.6.5}/pyproject.toml +1 -1
  6. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/__init__.py +1 -1
  7. torchspin-0.6.5/torchspin/_resources.py +115 -0
  8. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/esfit.py +11 -7
  9. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin.egg-info/PKG-INFO +44 -3
  10. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin.egg-info/SOURCES.txt +1 -0
  11. {torchspin-0.6.4 → torchspin-0.6.5}/LICENSE.md +0 -0
  12. {torchspin-0.6.4 → torchspin-0.6.5}/MANIFEST.in +0 -0
  13. {torchspin-0.6.4 → torchspin-0.6.5}/setup.cfg +0 -0
  14. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_cardamom_istos.py +0 -0
  15. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_cardamom_propagatedm.py +0 -0
  16. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_cardamom_utils.py +0 -0
  17. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_compile.py +0 -0
  18. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_linalg.py +0 -0
  19. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_omp.py +0 -0
  20. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/_rng.py +0 -0
  21. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/angmom.py +0 -0
  22. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/autograd.py +0 -0
  23. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/autoguess.py +0 -0
  24. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/batch.py +0 -0
  25. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/blochsteady.py +0 -0
  26. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/cardamom.py +0 -0
  27. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/chili.py +0 -0
  28. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/chili_sle.py +0 -0
  29. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/constants.py +0 -0
  30. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/convspec.py +0 -0
  31. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ctafft.py +0 -0
  32. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/curry.py +0 -0
  33. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/data/FourierSeriesCoefficients.txt +0 -0
  34. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/data/GaussianCascadeCoefficients.txt +0 -0
  35. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/data/isotopedata.txt +0 -0
  36. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/data/spacegroups.txt +0 -0
  37. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/dataproc.py +0 -0
  38. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/dipbackground.py +0 -0
  39. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/dipkernel.py +0 -0
  40. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/diptensor.py +0 -0
  41. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/endorfrq.py +0 -0
  42. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/endorfrq_perturb.py +0 -0
  43. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/eprload.py +0 -0
  44. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/eprsave.py +0 -0
  45. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/evolve.py +0 -0
  46. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ewrls.py +0 -0
  47. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/excitation.py +0 -0
  48. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/exciteprofile.py +0 -0
  49. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/experiment.py +0 -0
  50. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/exponfit.py +0 -0
  51. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/fastmotion.py +0 -0
  52. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/fdaxis.py +0 -0
  53. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/fitgui.py +0 -0
  54. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/garlic.py +0 -0
  55. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/gridcheck.py +0 -0
  56. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham.py +0 -0
  57. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_cf.py +0 -0
  58. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_ee.py +0 -0
  59. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_ez.py +0 -0
  60. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_ezho.py +0 -0
  61. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_hf.py +0 -0
  62. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_nn.py +0 -0
  63. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_nq.py +0 -0
  64. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_nz.py +0 -0
  65. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_oz.py +0 -0
  66. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_so.py +0 -0
  67. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ham_zf.py +0 -0
  68. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/hamsymm.py +0 -0
  69. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/initstate.py +0 -0
  70. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/isotopologues.py +0 -0
  71. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/levels.py +0 -0
  72. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/levelsplot.py +0 -0
  73. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/lineshape.py +0 -0
  74. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/lpsvd.py +0 -0
  75. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/makespec.py +0 -0
  76. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/mdhmm.py +0 -0
  77. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/mdload.py +0 -0
  78. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/mdtraj2oripot.py +0 -0
  79. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ml.py +0 -0
  80. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/mlpsvd.py +0 -0
  81. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/nucdata.py +0 -0
  82. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/nucfrq2d.py +0 -0
  83. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/orca2torchspin.py +0 -0
  84. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/ordering.py +0 -0
  85. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/oripotentialplot.py +0 -0
  86. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/orisel.py +0 -0
  87. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/pepper.py +0 -0
  88. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/pepper_autograd.py +0 -0
  89. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/photoselect.py +0 -0
  90. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/plegendre.py +0 -0
  91. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/propint.py +0 -0
  92. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/pulse.py +0 -0
  93. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/py.typed +0 -0
  94. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/rapidscan2spc.py +0 -0
  95. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfields.py +0 -0
  96. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfields_batch.py +0 -0
  97. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfields_eig.py +0 -0
  98. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfields_hybrid.py +0 -0
  99. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfields_perturb.py +0 -0
  100. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfreqs_matrix.py +0 -0
  101. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resfreqs_perturb.py +0 -0
  102. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resonator.py +0 -0
  103. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/resonatorprofile.py +0 -0
  104. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/rfmixer.py +0 -0
  105. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/rotations.py +0 -0
  106. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/rotutils.py +0 -0
  107. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/saffron.py +0 -0
  108. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/saffron_pathways.py +0 -0
  109. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/saffron_peaks.py +0 -0
  110. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/saffron_thyme.py +0 -0
  111. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/salt.py +0 -0
  112. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/sigeq.py +0 -0
  113. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/signalprocessing.py +0 -0
  114. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/sitetransforms.py +0 -0
  115. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/sphgrid.py +0 -0
  116. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/spidyan.py +0 -0
  117. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/spinladder.py +0 -0
  118. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/spinops.py +0 -0
  119. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/spinsystem.py +0 -0
  120. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/stackplot.py +0 -0
  121. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/stev.py +0 -0
  122. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/stochtraj_diffusion.py +0 -0
  123. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/stochtraj_jump.py +0 -0
  124. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/strainwidth.py +0 -0
  125. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/transmitter.py +0 -0
  126. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin/utils.py +0 -0
  127. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin.egg-info/dependency_links.txt +0 -0
  128. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin.egg-info/requires.txt +0 -0
  129. {torchspin-0.6.4 → torchspin-0.6.5}/torchspin.egg-info/top_level.txt +0 -0
@@ -6,6 +6,31 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.6.5] — 2026-11-09
10
+
11
+ ### Fixed
12
+
13
+ - **`FitOptions(n_workers='auto')` could start far more worker processes than
14
+ the machine or job could hold.** It meant one worker per core of the whole
15
+ machine (`os.cpu_count()`), and every worker is a separate Python process
16
+ with its own torch, about 0.3–0.5 GB before the model allocates anything. On
17
+ a 224-core node that is over 200 workers and roughly 80 GB, even inside a
18
+ SLURM job granted 16 cores and 8 GB. `'auto'` now takes the smallest of:
19
+ - the cores this process may use (CPU affinity, then `SLURM_CPUS_PER_TASK`);
20
+ - 32 (more workers did not make fits faster in our measurements);
21
+ - the workers that fit in half the available memory at 0.5 GB each, where
22
+ available memory honors the cgroup limit of a SLURM job or container and
23
+ the job's SLURM memory request;
24
+ - the number of tasks.
25
+
26
+ An explicit integer is used as given. In a 16-core SLURM job, `'auto'` now
27
+ gives 7 workers with `--mem=8G` and 2 with `--mem=3G`.
28
+
29
+ ### Documentation
30
+
31
+ - README: how to launch the interactive fitting panel (`torchspin.fitgui`),
32
+ and what `n_workers='auto'` costs in memory.
33
+
9
34
  ## [0.6.4] — 2026-11-09
10
35
 
11
36
  ### 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.4"
6
- date-released: "2026-11-08"
5
+ version: "0.6.5"
6
+ date-released: "2026-11-09"
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.4
3
+ Version: 0.6.5
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>
@@ -151,8 +151,49 @@ print('Best-fit g:', result.pfit)
151
151
  ```
152
152
 
153
153
  `progress='text'` prints RMSD, evaluation count and ETA as it runs, and
154
- interrupting the kernel returns the best fit so far. Population-based methods
155
- parallelize over processes with `FitOptions(n_workers='auto')`.
154
+ interrupting the kernel returns the best fit so far.
155
+
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
+ (about 0.3–0.5 GB), so `'auto'` uses the cores you were allocated, at most 32, and
160
+ no more workers than fit in half the free memory. A script that uses it needs the
161
+ usual `if __name__ == '__main__':` guard around the code that runs the fit.
162
+
163
+ ### Interactive fitting panel (`torchspin.fitgui`)
164
+
165
+ In JupyterLab (`pip install "torchspin[gui]"`), the same kind of fit runs in a panel
166
+ with parameter sliders, fix boxes, method controls, Start/Stop and a live plot of the
167
+ fit, residual and RMSD:
168
+
169
+ ```python
170
+ %matplotlib widget
171
+ import numpy as np
172
+ from torchspin import SpinSystem, Experiment, Options, pepper
173
+ from torchspin.esfit import FitOptions
174
+ from torchspin.fitgui import FitSession, FitPanel
175
+
176
+ exp = Experiment(mwFreq=9.5, Range=[330, 350], nPoints=1024, Harmonic=1)
177
+
178
+ def model(p): # p = [gx, gy, gz, Az (MHz), lwpp (mT)]
179
+ sys = SpinSystem(S=[0.5], g=p[:3], Nucs='14N', A=[[18, 18, p[3]]], lwpp=[p[4], 0])
180
+ return pepper(sys, exp, Options(GridSize=[31, 4], Verbosity=0))[1].numpy()
181
+
182
+ B = np.linspace(330, 350, 1024)
183
+ data = model([2.0085, 2.0060, 2.0025, 92.0, 0.35]) # or your measured spectrum
184
+ data = data + 0.02 * np.abs(data).max() * np.random.default_rng(1).standard_normal(data.size)
185
+
186
+ session = FitSession(data, model, p0=[2.011, 2.0085, 2.005, 101.0, 0.5],
187
+ vary=[0.004, 0.004, 0.004, 15.0, 0.25],
188
+ names=['gx', 'gy', 'gz', 'Az', 'lwpp'],
189
+ options=FitOptions(method='global', max_iter=100))
190
+ FitPanel(session, x=B, xlabel='B (mT)').show()
191
+ ```
192
+
193
+ Press **Start** to fit; **Stop** returns the best fit so far, and `session.result`
194
+ holds the result afterwards. The panel's `n_workers` box accepts `auto` for parallel
195
+ population fits. The full walkthrough is
196
+ [`examples/notebooks/09_fit_gui.ipynb`](examples/notebooks/09_fit_gui.ipynb).
156
197
 
157
198
  ### Differentiable spectrum
158
199
 
@@ -96,8 +96,49 @@ print('Best-fit g:', result.pfit)
96
96
  ```
97
97
 
98
98
  `progress='text'` prints RMSD, evaluation count and ETA as it runs, and
99
- interrupting the kernel returns the best fit so far. Population-based methods
100
- parallelize over processes with `FitOptions(n_workers='auto')`.
99
+ interrupting the kernel returns the best fit so far.
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
104
+ (about 0.3–0.5 GB), so `'auto'` uses the cores you were allocated, at most 32, and
105
+ no more workers than fit in half the free memory. A script that uses it needs the
106
+ usual `if __name__ == '__main__':` guard around the code that runs the fit.
107
+
108
+ ### Interactive fitting panel (`torchspin.fitgui`)
109
+
110
+ In JupyterLab (`pip install "torchspin[gui]"`), the same kind of fit runs in a panel
111
+ with parameter sliders, fix boxes, method controls, Start/Stop and a live plot of the
112
+ fit, residual and RMSD:
113
+
114
+ ```python
115
+ %matplotlib widget
116
+ import numpy as np
117
+ from torchspin import SpinSystem, Experiment, Options, pepper
118
+ from torchspin.esfit import FitOptions
119
+ from torchspin.fitgui import FitSession, FitPanel
120
+
121
+ exp = Experiment(mwFreq=9.5, Range=[330, 350], nPoints=1024, Harmonic=1)
122
+
123
+ def model(p): # p = [gx, gy, gz, Az (MHz), lwpp (mT)]
124
+ sys = SpinSystem(S=[0.5], g=p[:3], Nucs='14N', A=[[18, 18, p[3]]], lwpp=[p[4], 0])
125
+ return pepper(sys, exp, Options(GridSize=[31, 4], Verbosity=0))[1].numpy()
126
+
127
+ B = np.linspace(330, 350, 1024)
128
+ data = model([2.0085, 2.0060, 2.0025, 92.0, 0.35]) # or your measured spectrum
129
+ data = data + 0.02 * np.abs(data).max() * np.random.default_rng(1).standard_normal(data.size)
130
+
131
+ session = FitSession(data, model, p0=[2.011, 2.0085, 2.005, 101.0, 0.5],
132
+ vary=[0.004, 0.004, 0.004, 15.0, 0.25],
133
+ names=['gx', 'gy', 'gz', 'Az', 'lwpp'],
134
+ options=FitOptions(method='global', max_iter=100))
135
+ FitPanel(session, x=B, xlabel='B (mT)').show()
136
+ ```
137
+
138
+ Press **Start** to fit; **Stop** returns the best fit so far, and `session.result`
139
+ holds the result afterwards. The panel's `n_workers` box accepts `auto` for parallel
140
+ population fits. The full walkthrough is
141
+ [`examples/notebooks/09_fit_gui.ipynb`](examples/notebooks/09_fit_gui.ipynb).
101
142
 
102
143
  ### Differentiable spectrum
103
144
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "torchspin"
7
- version = "0.6.4"
7
+ version = "0.6.5"
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.4+dev"
28
+ __version__ = "0.6.5+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
@@ -0,0 +1,115 @@
1
+ """How many worker processes this process can afford: cores and memory.
2
+
3
+ ``n_workers='auto'`` used to mean one worker per core on the machine. Each worker
4
+ is a separate Python process with its own torch (about 0.3-0.4 GB before the model
5
+ allocates anything), so on a many-core workstation or cluster node 'auto' could ask
6
+ for tens of GB, and inside a SLURM allocation it ignored the cores actually granted.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+
13
+ #: Memory planned per worker process (torch + torchspin + a small model).
14
+ WORKER_BYTES = 512 * 2**20
15
+ #: Fraction of the available memory the workers may take.
16
+ MEMORY_FRACTION = 0.5
17
+ #: Beyond this, more workers did not make fits faster in our measurements.
18
+ MAX_AUTO_WORKERS = 32
19
+
20
+
21
+ def cpu_budget() -> int:
22
+ """Cores this process may use: CPU affinity (Linux), then SLURM, then the machine."""
23
+ n = None
24
+ if hasattr(os, 'sched_getaffinity'):
25
+ try:
26
+ n = len(os.sched_getaffinity(0))
27
+ except OSError:
28
+ n = None
29
+ slurm = os.environ.get('SLURM_CPUS_PER_TASK')
30
+ if slurm and slurm.isdigit():
31
+ n = min(n, int(slurm)) if n else int(slurm)
32
+ return max(1, n or os.cpu_count() or 1)
33
+
34
+
35
+ def _cgroup_limit() -> int | None:
36
+ """Bytes left under the tightest cgroup v2 memory limit above this process.
37
+
38
+ SLURM and container runtimes set the limit on a parent of the process's own
39
+ cgroup (e.g. the job, not the step's task), so every ancestor is checked.
40
+ """
41
+ try:
42
+ with open('/proc/self/cgroup') as f:
43
+ path = next((line.split('::', 1)[1].strip() for line in f if line.startswith('0::')), None)
44
+ except OSError:
45
+ return None
46
+ if path is None:
47
+ return None
48
+ best = None
49
+ parts = [p for p in path.split('/') if p]
50
+ for k in range(len(parts), -1, -1):
51
+ base = '/sys/fs/cgroup/' + '/'.join(parts[:k])
52
+ try:
53
+ with open(base + '/memory.max') as f:
54
+ limit = f.read().strip()
55
+ if limit == 'max':
56
+ continue
57
+ with open(base + '/memory.current') as f:
58
+ used = int(f.read().strip())
59
+ except (OSError, ValueError):
60
+ continue
61
+ left = max(0, int(limit) - used)
62
+ best = left if best is None else min(best, left)
63
+ return best
64
+
65
+
66
+ def _slurm_limit() -> int | None:
67
+ """The job's memory request from SLURM's environment, in bytes (an upper bound)."""
68
+ try:
69
+ if os.environ.get('SLURM_MEM_PER_NODE'):
70
+ return int(os.environ['SLURM_MEM_PER_NODE']) * 2**20
71
+ if os.environ.get('SLURM_MEM_PER_CPU'):
72
+ cpus = int(os.environ.get('SLURM_CPUS_ON_NODE') or os.environ.get('SLURM_CPUS_PER_TASK') or 1)
73
+ return int(os.environ['SLURM_MEM_PER_CPU']) * cpus * 2**20
74
+ except ValueError:
75
+ pass
76
+ return None
77
+
78
+
79
+ def available_memory() -> int | None:
80
+ """Bytes of memory new processes can use, or None if unknown."""
81
+ avail = None
82
+ if sys.platform.startswith('linux'):
83
+ try:
84
+ with open('/proc/meminfo') as f:
85
+ for line in f:
86
+ if line.startswith('MemAvailable:'):
87
+ avail = int(line.split()[1]) * 1024
88
+ break
89
+ except (OSError, ValueError):
90
+ pass
91
+ cg = _cgroup_limit()
92
+ if cg is not None:
93
+ avail = cg if avail is None else min(avail, cg)
94
+ slurm = _slurm_limit()
95
+ if slurm is not None:
96
+ avail = slurm if avail is None else min(avail, slurm)
97
+ if avail is None:
98
+ try:
99
+ import psutil # optional
100
+ avail = int(psutil.virtual_memory().available)
101
+ except Exception:
102
+ try: # macOS and other POSIX: physical memory as an upper bound
103
+ avail = os.sysconf('SC_PHYS_PAGES') * os.sysconf('SC_PAGE_SIZE')
104
+ except (ValueError, OSError, AttributeError):
105
+ avail = None
106
+ return avail
107
+
108
+
109
+ def auto_workers(n_tasks: int) -> int:
110
+ """Worker count for ``n_workers='auto'``: cores, memory and task count, at most 32."""
111
+ n = min(cpu_budget(), MAX_AUTO_WORKERS, max(1, int(n_tasks)))
112
+ mem = available_memory()
113
+ if mem is not None:
114
+ n = min(n, max(1, int(mem * MEMORY_FRACTION // WORKER_BYTES)))
115
+ return max(1, n)
@@ -159,9 +159,11 @@ class FitOptions:
159
159
  trf_x_scale: Union[str, float, np.ndarray] = 'jac'
160
160
  trf_gradient_tol: float = 1e-7
161
161
  # Parallelism for population-based methods (swarm, genetic, montecarlo,
162
- # grid, global). n_workers=1 is sequential; an int > 1 or 'auto' (one per
163
- # core) evaluates the population in a spawned process pool with one torch
164
- # thread per worker (workers='auto'|'processes'; 'threads' forces a thread
162
+ # grid, global). n_workers=1 is sequential; an int > 1 or 'auto' evaluates
163
+ # the population in a spawned process pool with one torch thread per worker.
164
+ # 'auto' = the cores this process may use (affinity / SLURM aware), at most
165
+ # 32, and no more than about 0.5 GB per worker within half the available
166
+ # memory: each worker is a separate Python process with its own torch (workers='auto'|'processes'; 'threads' forces a thread
165
167
  # pool, which gains little because the forward model holds the GIL).
166
168
  # Models defined in a notebook cell need cloudpickle (pip install
167
169
  # cloudpickle) to reach the workers; otherwise a thread pool is used.
@@ -1575,10 +1577,12 @@ class _CloudPickled:
1575
1577
 
1576
1578
 
1577
1579
  def _resolve_workers(n_workers, n: int) -> int:
1578
- """'auto' → all cores (capped by the population size); ints pass through."""
1580
+ """'auto' → the cores this process may use (affinity / SLURM aware), capped by the
1581
+ available memory (about 0.5 GB per worker, half the free memory), by 32 and by
1582
+ the population size; ints pass through."""
1579
1583
  if isinstance(n_workers, str):
1580
- import os
1581
- return max(1, min(os.cpu_count() or 1, n))
1584
+ from torchspin._resources import auto_workers
1585
+ return auto_workers(n)
1582
1586
  return int(n_workers or 1)
1583
1587
 
1584
1588
 
@@ -1590,7 +1594,7 @@ def _eval_population(
1590
1594
  ) -> np.ndarray:
1591
1595
  """Evaluate ``objective_fn`` on each row of ``X``.
1592
1596
 
1593
- ``n_workers > 1`` (or ``'auto'`` = one per core) evaluates the rows
1597
+ ``n_workers > 1`` (or ``'auto'``, see :class:`FitOptions`) evaluates the rows
1594
1598
  concurrently. ``workers='processes'`` uses a spawned process pool with one
1595
1599
  torch thread per worker — the effective option for torchspin forward models,
1596
1600
  whose Python-level work holds the GIL. The objective is pickled by
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torchspin
3
- Version: 0.6.4
3
+ Version: 0.6.5
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>
@@ -151,8 +151,49 @@ print('Best-fit g:', result.pfit)
151
151
  ```
152
152
 
153
153
  `progress='text'` prints RMSD, evaluation count and ETA as it runs, and
154
- interrupting the kernel returns the best fit so far. Population-based methods
155
- parallelize over processes with `FitOptions(n_workers='auto')`.
154
+ interrupting the kernel returns the best fit so far.
155
+
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
+ (about 0.3–0.5 GB), so `'auto'` uses the cores you were allocated, at most 32, and
160
+ no more workers than fit in half the free memory. A script that uses it needs the
161
+ usual `if __name__ == '__main__':` guard around the code that runs the fit.
162
+
163
+ ### Interactive fitting panel (`torchspin.fitgui`)
164
+
165
+ In JupyterLab (`pip install "torchspin[gui]"`), the same kind of fit runs in a panel
166
+ with parameter sliders, fix boxes, method controls, Start/Stop and a live plot of the
167
+ fit, residual and RMSD:
168
+
169
+ ```python
170
+ %matplotlib widget
171
+ import numpy as np
172
+ from torchspin import SpinSystem, Experiment, Options, pepper
173
+ from torchspin.esfit import FitOptions
174
+ from torchspin.fitgui import FitSession, FitPanel
175
+
176
+ exp = Experiment(mwFreq=9.5, Range=[330, 350], nPoints=1024, Harmonic=1)
177
+
178
+ def model(p): # p = [gx, gy, gz, Az (MHz), lwpp (mT)]
179
+ sys = SpinSystem(S=[0.5], g=p[:3], Nucs='14N', A=[[18, 18, p[3]]], lwpp=[p[4], 0])
180
+ return pepper(sys, exp, Options(GridSize=[31, 4], Verbosity=0))[1].numpy()
181
+
182
+ B = np.linspace(330, 350, 1024)
183
+ data = model([2.0085, 2.0060, 2.0025, 92.0, 0.35]) # or your measured spectrum
184
+ data = data + 0.02 * np.abs(data).max() * np.random.default_rng(1).standard_normal(data.size)
185
+
186
+ session = FitSession(data, model, p0=[2.011, 2.0085, 2.005, 101.0, 0.5],
187
+ vary=[0.004, 0.004, 0.004, 15.0, 0.25],
188
+ names=['gx', 'gy', 'gz', 'Az', 'lwpp'],
189
+ options=FitOptions(method='global', max_iter=100))
190
+ FitPanel(session, x=B, xlabel='B (mT)').show()
191
+ ```
192
+
193
+ Press **Start** to fit; **Stop** returns the best fit so far, and `session.result`
194
+ holds the result afterwards. The panel's `n_workers` box accepts `auto` for parallel
195
+ population fits. The full walkthrough is
196
+ [`examples/notebooks/09_fit_gui.ipynb`](examples/notebooks/09_fit_gui.ipynb).
156
197
 
157
198
  ### Differentiable spectrum
158
199
 
@@ -11,6 +11,7 @@ torchspin/_cardamom_utils.py
11
11
  torchspin/_compile.py
12
12
  torchspin/_linalg.py
13
13
  torchspin/_omp.py
14
+ torchspin/_resources.py
14
15
  torchspin/_rng.py
15
16
  torchspin/angmom.py
16
17
  torchspin/autograd.py
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes