torchspin 0.6.1__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.
- {torchspin-0.6.1 → torchspin-0.6.2}/CHANGELOG.md +56 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/CITATION.cff +2 -2
- {torchspin-0.6.1 → torchspin-0.6.2}/PKG-INFO +1 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/pyproject.toml +1 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/__init__.py +1 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/_linalg.py +31 -2
- torchspin-0.6.2/torchspin/_rng.py +53 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/cardamom.py +39 -12
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/pepper.py +18 -8
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfields_batch.py +4 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/sigeq.py +1 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/stochtraj_diffusion.py +21 -14
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/stochtraj_jump.py +11 -6
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin.egg-info/PKG-INFO +1 -1
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin.egg-info/SOURCES.txt +1 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/LICENSE.md +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/MANIFEST.in +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/README.md +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/setup.cfg +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/_cardamom_istos.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/_cardamom_propagatedm.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/_cardamom_utils.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/_compile.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/angmom.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/autograd.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/autoguess.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/batch.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/blochsteady.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/chili.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/chili_sle.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/constants.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/convspec.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ctafft.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/curry.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/data/FourierSeriesCoefficients.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/data/GaussianCascadeCoefficients.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/data/isotopedata.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/data/spacegroups.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/dataproc.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/dipbackground.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/dipkernel.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/diptensor.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/endorfrq.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/endorfrq_perturb.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/eprload.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/eprsave.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/esfit.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/evolve.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ewrls.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/excitation.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/exciteprofile.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/experiment.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/exponfit.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/fastmotion.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/fdaxis.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/fitgui.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/garlic.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/gridcheck.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_cf.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_ee.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_ez.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_ezho.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_hf.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_nn.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_nq.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_nz.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_oz.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_so.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ham_zf.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/hamsymm.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/initstate.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/isotopologues.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/levels.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/levelsplot.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/lineshape.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/lpsvd.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/makespec.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/mdhmm.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/mdload.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/mdtraj2oripot.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ml.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/mlpsvd.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/nucdata.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/nucfrq2d.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/orca2torchspin.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/ordering.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/oripotentialplot.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/orisel.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/pepper_autograd.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/photoselect.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/plegendre.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/propint.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/pulse.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/py.typed +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/rapidscan2spc.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfields.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfields_eig.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfields_hybrid.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfields_perturb.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfreqs_matrix.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resfreqs_perturb.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resonator.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/resonatorprofile.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/rfmixer.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/rotations.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/rotutils.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/saffron.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/saffron_pathways.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/saffron_peaks.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/saffron_thyme.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/salt.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/signalprocessing.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/sitetransforms.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/sphgrid.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/spidyan.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/spinladder.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/spinops.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/spinsystem.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/stackplot.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/stev.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/strainwidth.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/transmitter.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin/utils.py +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin.egg-info/dependency_links.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin.egg-info/requires.txt +0 -0
- {torchspin-0.6.1 → torchspin-0.6.2}/torchspin.egg-info/top_level.txt +0 -0
|
@@ -6,6 +6,62 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
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
|
+
|
|
9
65
|
## [0.6.1] — 2026-11-04
|
|
10
66
|
|
|
11
67
|
Fixes for GitHub issues #5–#9. Each one was a case where torchspin returned a
|
|
@@ -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
|
-
date-released: "2026-
|
|
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.
|
|
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>
|
|
@@ -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.
|
|
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
|
|
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
|
|
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,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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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=
|
|
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=
|
|
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,
|
|
@@ -18,6 +18,7 @@ from __future__ import annotations
|
|
|
18
18
|
|
|
19
19
|
import functools
|
|
20
20
|
import math
|
|
21
|
+
import threading
|
|
21
22
|
import warnings
|
|
22
23
|
from typing import Optional
|
|
23
24
|
|
|
@@ -216,6 +217,14 @@ def _interp_sph(
|
|
|
216
217
|
return result
|
|
217
218
|
|
|
218
219
|
|
|
220
|
+
# The (u, v, occurrence) key of every slot from the most recent _transition_slots
|
|
221
|
+
# call, kept in sync by _filter_slots and read by the separate='transitions' path.
|
|
222
|
+
# It is per thread: it used to be a function attribute shared by the whole process,
|
|
223
|
+
# so concurrent pepper calls (esfit workers='threads') could read each other's
|
|
224
|
+
# keys, which raised IndexError or mislabeled transitions.
|
|
225
|
+
_slot_state = threading.local()
|
|
226
|
+
|
|
227
|
+
|
|
219
228
|
def _transition_slots(all_B, all_I, all_W, all_pairs, n_orient):
|
|
220
229
|
"""Group per-orientation resonances into transition slots across the grid.
|
|
221
230
|
|
|
@@ -246,7 +255,7 @@ def _transition_slots(all_B, all_I, all_W, all_pairs, n_orient):
|
|
|
246
255
|
B_arrs[i][k] = Bn[i]; I_arrs[i][k] = In[i]
|
|
247
256
|
if Wn is not None and i < Wn.shape[0]:
|
|
248
257
|
W_arrs[i][k] = Wn[i]
|
|
249
|
-
|
|
258
|
+
_slot_state.keys = None # index-matched slots (perturbation path)
|
|
250
259
|
return B_arrs, I_arrs, W_arrs
|
|
251
260
|
slots: dict = {}
|
|
252
261
|
B_arrs: list = []; I_arrs: list = []; W_arrs: list = []
|
|
@@ -272,7 +281,7 @@ def _transition_slots(all_B, all_I, all_W, all_pairs, n_orient):
|
|
|
272
281
|
B_arrs[j][k] = Bn[i]; I_arrs[j][k] = In[i]
|
|
273
282
|
if Wn is not None and i < Wn.shape[0]:
|
|
274
283
|
W_arrs[j][k] = Wn[i]
|
|
275
|
-
|
|
284
|
+
_slot_state.keys = sorted(slots.keys(), key=lambda kk: slots[kk]) # (u, v, occurrence) per slot
|
|
276
285
|
return B_arrs, I_arrs, (W_arrs if have_widths else None)
|
|
277
286
|
|
|
278
287
|
|
|
@@ -286,9 +295,9 @@ def _filter_slots(B_arrs, I_arrs, W_arrs, threshold):
|
|
|
286
295
|
slot_max = np.array([np.nanmax(np.abs(I)) if np.isfinite(I).any() else 0.0 for I in I_arrs])
|
|
287
296
|
gmax = slot_max.max() if slot_max.size else 0.0
|
|
288
297
|
keep = [k for k in range(len(I_arrs)) if slot_max[k] >= threshold * gmax]
|
|
289
|
-
keys = getattr(
|
|
298
|
+
keys = getattr(_slot_state, 'keys', None)
|
|
290
299
|
if keys is not None:
|
|
291
|
-
|
|
300
|
+
_slot_state.keys = [keys[k] for k in keep]
|
|
292
301
|
return ([B_arrs[k] for k in keep], [I_arrs[k] for k in keep],
|
|
293
302
|
None if W_arrs is None else [W_arrs[k] for k in keep])
|
|
294
303
|
|
|
@@ -596,7 +605,8 @@ def _preselect_pairs(H0, mux, muy, muz, sys, exp, opt, B_center, freq_sweep=Fals
|
|
|
596
605
|
phi_t, theta_t, _, _ = sphgrid('D2h', 4)
|
|
597
606
|
geom = excitation_geometry(exp_mw_mode(exp))
|
|
598
607
|
Ex, Ey, Ez = -mux, -muy, -muz
|
|
599
|
-
|
|
608
|
+
dev = H0.device
|
|
609
|
+
max_rate = torch.zeros(n, n, dtype=torch.float64, device=dev)
|
|
600
610
|
for ph, th in zip(phi_t.tolist(), theta_t.tolist()):
|
|
601
611
|
st, ct, sp, cp = math.sin(th), math.cos(th), math.sin(ph), math.cos(ph)
|
|
602
612
|
muzL = st * (cp * mux + sp * muy) + ct * muz
|
|
@@ -610,7 +620,7 @@ def _preselect_pairs(H0, mux, muy, muz, sys, exp, opt, B_center, freq_sweep=Fals
|
|
|
610
620
|
ExL = ct * Exy - st * Ez
|
|
611
621
|
rate = ((V.conj().T @ ExL @ V).abs() ** 2 + (V.conj().T @ EyL @ V).abs() ** 2) / 2
|
|
612
622
|
max_rate = torch.maximum(max_rate, rate.real.to(torch.float64))
|
|
613
|
-
keep = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
|
|
623
|
+
keep = torch.triu(torch.ones(n, n, dtype=torch.bool, device=dev), diagonal=1)
|
|
614
624
|
if sys.nNuclei > 0:
|
|
615
625
|
nu = float(exp.mwFreq) * 1e3 if not freq_sweep else 1e9 # MHz (frequency sweeps: no exclusion)
|
|
616
626
|
A = sys.A.detach().cpu().numpy()
|
|
@@ -619,7 +629,7 @@ def _preselect_pairs(H0, mux, muy, muz, sys, exp, opt, B_center, freq_sweep=Fals
|
|
|
619
629
|
if hfi.max() < 0.5:
|
|
620
630
|
n_el = int(np.prod([2 * float(S_) + 1 for S_ in sys.S]))
|
|
621
631
|
n_nuc = n // n_el
|
|
622
|
-
el_idx = torch.arange(n) // n_nuc
|
|
632
|
+
el_idx = torch.arange(n, device=dev) // n_nuc
|
|
623
633
|
keep &= el_idx.unsqueeze(1) != el_idx.unsqueeze(0) # drop pure nuclear transitions
|
|
624
634
|
rates = max_rate[keep]
|
|
625
635
|
cutoff = thr * float(rates.detach().max()) if rates.numel() else 0.0
|
|
@@ -1324,7 +1334,7 @@ def _pepper_single(
|
|
|
1324
1334
|
_row_max: dict = {}
|
|
1325
1335
|
|
|
1326
1336
|
def _rid(i_t):
|
|
1327
|
-
keys = getattr(
|
|
1337
|
+
keys = getattr(_slot_state, 'keys', None)
|
|
1328
1338
|
return (keys[i_t][0], keys[i_t][1]) if keys is not None and i_t < len(keys) else i_t
|
|
1329
1339
|
|
|
1330
1340
|
def _row(i_t):
|
|
@@ -198,7 +198,10 @@ def resfields_batch(
|
|
|
198
198
|
comp = torch.zeros(int(cubic.sum()), 3, 3, dtype=rdtype, device=dev)
|
|
199
199
|
comp[:, 1, 0] = 1.0; comp[:, 2, 1] = 1.0
|
|
200
200
|
comp[:, 0, 0] = -C2n[cubic] / C3n[cubic]; comp[:, 0, 1] = -C1n[cubic] / C3n[cubic]; comp[:, 0, 2] = -C0n[cubic] / C3n[cubic]
|
|
201
|
-
|
|
201
|
+
# torch computes general (non-Hermitian) eigenvalues on CUDA one matrix at a
|
|
202
|
+
# time with a host sync each (hundreds of thousands per pepper call); one
|
|
203
|
+
# batched CPU call runs the same LAPACK routine as the CPU path
|
|
204
|
+
ev = torch.linalg.eigvals(comp.cpu()).to(dev) if comp.is_cuda else torch.linalg.eigvals(comp)
|
|
202
205
|
real = ev.imag.abs() < 1e-7 * (1 + ev.real.abs())
|
|
203
206
|
roots[cubic] = torch.where(real, ev.real, torch.full_like(ev.real, float('nan')))
|
|
204
207
|
quad = (~cubic) & (C2n.abs() > 1e-10)
|
|
@@ -19,6 +19,7 @@ from typing import Optional
|
|
|
19
19
|
import numpy as np
|
|
20
20
|
import torch
|
|
21
21
|
|
|
22
|
+
from torchspin._rng import draw, traj_generators
|
|
22
23
|
from torchspin.rotutils import euler2quat, quat2rotmat, quatmult
|
|
23
24
|
|
|
24
25
|
|
|
@@ -33,9 +34,14 @@ class DiffusionPar:
|
|
|
33
34
|
Attributes
|
|
34
35
|
----------
|
|
35
36
|
seed:
|
|
36
|
-
Optional
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
Optional seed for the random number generator. When set, the
|
|
38
|
+
generated trajectory is bit-reproducible across runs. When ``None``
|
|
39
|
+
(default), a fresh non-deterministic generator is used. A sequence
|
|
40
|
+
of ``B`` seeds splits the ``nTraj`` trajectories into ``B`` equal
|
|
41
|
+
consecutive blocks with independent streams, so a block draws the
|
|
42
|
+
same numbers whether it is generated alone or together with others
|
|
43
|
+
(used by cardamom to keep seeded results independent of how
|
|
44
|
+
orientations are grouped).
|
|
39
45
|
"""
|
|
40
46
|
dt: Optional[float] = None # time step (s)
|
|
41
47
|
nSteps: Optional[int] = None # number of steps
|
|
@@ -43,7 +49,7 @@ class DiffusionPar:
|
|
|
43
49
|
tMax: Optional[float] = None # total simulation time (s)
|
|
44
50
|
OriStart: Optional[np.ndarray] = None # (3, nTraj) Euler angles
|
|
45
51
|
Integrator: str = 'Euler-Maruyama' # or 'Leimkuhler-Matthews'
|
|
46
|
-
seed:
|
|
52
|
+
seed: object = None # int, SeedSequence, or a sequence of per-block seeds (None = non-deterministic)
|
|
47
53
|
|
|
48
54
|
|
|
49
55
|
# ---------------------------------------------------------------------------
|
|
@@ -97,7 +103,7 @@ def stochtraj_diffusion(
|
|
|
97
103
|
nTraj = par.nTraj
|
|
98
104
|
|
|
99
105
|
# --- Seeded RNG (reproducibility per DiffusionPar.seed) ---
|
|
100
|
-
|
|
106
|
+
_gens = traj_generators(par.seed, nTraj)
|
|
101
107
|
|
|
102
108
|
# --- Resolve time parameters ---
|
|
103
109
|
if dt is None and par.tMax is not None and nSteps is not None:
|
|
@@ -147,11 +153,11 @@ def stochtraj_diffusion(
|
|
|
147
153
|
OriStart = np.stack([gridPhi, gridTheta, gridPsi], axis=0)
|
|
148
154
|
else:
|
|
149
155
|
# Random starting orientations for potential case
|
|
150
|
-
OriStart = np.stack([
|
|
151
|
-
|
|
152
|
-
np.arccos(
|
|
153
|
-
|
|
154
|
-
], axis=0)
|
|
156
|
+
OriStart = draw(_gens, lambda g, n: np.stack([
|
|
157
|
+
g.uniform(0, 2 * np.pi, n),
|
|
158
|
+
np.arccos(g.uniform(-1, 1, n)),
|
|
159
|
+
g.uniform(0, 2 * np.pi, n),
|
|
160
|
+
], axis=0), axis=1)
|
|
155
161
|
|
|
156
162
|
# Convert starting Euler angles → quaternions
|
|
157
163
|
q0 = np.zeros((4, nTraj), dtype=np.float64)
|
|
@@ -165,7 +171,7 @@ def stochtraj_diffusion(
|
|
|
165
171
|
|
|
166
172
|
# --- Propagate ---
|
|
167
173
|
qTraj = _propagate(qTraj, Diff, dt, nSteps, nTraj,
|
|
168
|
-
par.Integrator, LMK, lam, interpGrad,
|
|
174
|
+
par.Integrator, LMK, lam, interpGrad, gens=_gens)
|
|
169
175
|
|
|
170
176
|
# Permute to (4, nSteps, nTraj) — matches MATLAB output convention
|
|
171
177
|
qTraj = np.transpose(qTraj, (0, 2, 1)) # (4, nSteps, nTraj)
|
|
@@ -192,12 +198,13 @@ def _propagate(
|
|
|
192
198
|
lam: np.ndarray | None,
|
|
193
199
|
interpGrad: object | None,
|
|
194
200
|
rng: Optional[np.random.Generator] = None,
|
|
201
|
+
gens: Optional[list] = None,
|
|
195
202
|
) -> np.ndarray:
|
|
196
203
|
"""Euler-Maruyama quaternion propagation (Eq. 61 in Sezer 2008)."""
|
|
197
204
|
# Pre-compute random angular steps (seeded via rng if provided)
|
|
198
|
-
if
|
|
199
|
-
|
|
200
|
-
randns =
|
|
205
|
+
if gens is None:
|
|
206
|
+
gens = [(rng if rng is not None else np.random.default_rng(), nTraj)]
|
|
207
|
+
randns = draw(gens, lambda g, n: g.standard_normal((3, n, nSteps)), axis=1)
|
|
201
208
|
scale = np.sqrt(2.0 * Diff * dt)[:, np.newaxis, np.newaxis]
|
|
202
209
|
|
|
203
210
|
if integrator == 'Leimkuhler-Matthews':
|
|
@@ -16,6 +16,7 @@ from typing import Optional
|
|
|
16
16
|
import numpy as np
|
|
17
17
|
from scipy.linalg import expm
|
|
18
18
|
|
|
19
|
+
from torchspin._rng import draw, traj_generators
|
|
19
20
|
from torchspin.stochtraj_diffusion import _euler2quat_active, _quat_to_rotmat_batch
|
|
20
21
|
|
|
21
22
|
|
|
@@ -30,15 +31,17 @@ class JumpPar:
|
|
|
30
31
|
Attributes
|
|
31
32
|
----------
|
|
32
33
|
seed:
|
|
33
|
-
Optional
|
|
34
|
-
|
|
34
|
+
Optional seed for the RNG. When set, the generated trajectory is
|
|
35
|
+
bit-reproducible across runs. A sequence of ``B`` seeds splits the
|
|
36
|
+
``nTraj`` trajectories into ``B`` equal consecutive blocks with
|
|
37
|
+
independent streams (see ``DiffusionPar.seed``).
|
|
35
38
|
"""
|
|
36
39
|
dt: float # time step (s) — required
|
|
37
40
|
nSteps: Optional[int] = None # number of steps
|
|
38
41
|
nTraj: int = 1 # number of trajectories
|
|
39
42
|
tMax: Optional[float] = None # total simulation time (s)
|
|
40
43
|
StatesStart: Optional[np.ndarray] = None # (nTraj,) starting states (1-based)
|
|
41
|
-
seed:
|
|
44
|
+
seed: object = None # int, SeedSequence, or a sequence of per-block seeds (None = non-deterministic)
|
|
42
45
|
|
|
43
46
|
|
|
44
47
|
# ---------------------------------------------------------------------------
|
|
@@ -152,7 +155,7 @@ def stochtraj_jump(
|
|
|
152
155
|
nSteps = 500
|
|
153
156
|
|
|
154
157
|
# --- Seeded RNG (reproducibility per JumpPar.seed) ---
|
|
155
|
-
|
|
158
|
+
_gens = traj_generators(par.seed, nTraj)
|
|
156
159
|
|
|
157
160
|
# --- Starting states ---
|
|
158
161
|
if par.StatesStart is not None:
|
|
@@ -160,7 +163,7 @@ def stochtraj_jump(
|
|
|
160
163
|
if starts.size == 1 and nTraj > 1:
|
|
161
164
|
starts = np.full(nTraj, starts[0], dtype=int)
|
|
162
165
|
else:
|
|
163
|
-
starts =
|
|
166
|
+
starts = draw(_gens, lambda g, n: g.integers(1, nStates + 1, size=n), axis=0)
|
|
164
167
|
|
|
165
168
|
# --- Cumulative transition probability matrix ---
|
|
166
169
|
cumulTPM = np.cumsum(TPM, axis=1)
|
|
@@ -169,8 +172,10 @@ def stochtraj_jump(
|
|
|
169
172
|
stateTraj = np.zeros((nSteps, nTraj), dtype=int)
|
|
170
173
|
stateTraj[0, :] = starts
|
|
171
174
|
|
|
175
|
+
# each trajectory draws its uniform numbers from its block's generator, in order
|
|
176
|
+
traj_rng = [g for g, n in _gens for _ in range(n)]
|
|
172
177
|
for iTraj in range(nTraj):
|
|
173
|
-
u =
|
|
178
|
+
u = traj_rng[iTraj].random(nSteps)
|
|
174
179
|
state = stateTraj[0, iTraj]
|
|
175
180
|
for iStep in range(1, nSteps):
|
|
176
181
|
# Find first state where cumulative prob exceeds random number
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: torchspin
|
|
3
|
-
Version: 0.6.
|
|
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>
|
|
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
|
|
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
|
|
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
|