torchspin.ml#

Machine-learning helpers: batched simulation over parameter sets, parameter packing, on-the-fly datasets and differentiable losses.

Every simulator in torchspin that is differentiable (pepper via torchspin.pepper_autograd(), garlic, salt, saffron, curry) accepts a SpinSystem whose parameter tensors may requires_grad. This module packages the plumbing around that for training and inference workflows:

  • ParamSpec — which spin-system fields are free, their shapes, ranges and transforms ('linear', 'log', 'softplus'), with ParamSpec.pack() / ParamSpec.unpack() between a flat tensor and a SpinSystem built from a template (on the autograd graph when the flat tensor requires grad).

  • simulate() / simulate_batch() — one call per parameter row (pepper, garlic, salt, saffron, curry or a callable), (N, nPoints) output, optional process pool for no-grad data generation.

  • SpectrumDataset — an torch.utils.data.IterableDataset sampling parameters from ranges (or a callable), simulating, normalizing, resampling to a fixed axis and adding noise, deterministic for a given seed.

  • cosine_loss(), rmsd(), normalize(), resample() — torch operations, so a network’s parameter prediction can be refined through the simulator with a physics loss.

Example:

from torchspin import SpinSystem, Experiment, Options
from torchspin.ml import ParamSpec, simulate_batch, SpectrumDataset

template = SpinSystem(S=[0.5], g=[[2.05, 2.05, 2.25]], Nucs='63Cu', A=[[30, 30, 500]], lw=[0.5, 0])
spec = ParamSpec({'g': [(2.0, 2.1), (2.0, 2.1), (2.15, 2.35)],
                  'A': [(20, 60), (20, 60), (350, 650)],
                  'lw': [(0.2, 1.5), (0.0, 0.0)]})
exp = Experiment(mwFreq=9.5, Range=[260, 360], nPoints=1024, Harmonic=1)
opt = Options(GridSize=[31, 4])
ds = SpectrumDataset(spec, template, exp, opt, simulator='pepper', n=1000, seed=0,
                     normalize='maxabs', noise=0.01)
x, params = next(iter(ds))          # x: (1024,), params: flat tensor
class torchspin.ml.ParamSpec(ranges, transforms=None)[source]#

Free parameters of a spin system: {field: [(low, high), ...]}.

field is a SpinSystem attribute ('g', 'A', 'D', 'Q', 'lw', 'lwpp', 'tcorr', 'HStrain', 'gStrain', 'AStrain', 'ee' …). The list gives one (low, high) per element of the flattened field as stored in the template (g is (1, 3) for one electron, A is (nNuclei, 3) …); equal bounds fix an element. transforms maps a field to 'linear' (default), 'log' (positive quantities spanning decades, e.g. tcorr) or 'softplus' (positive widths). Packed vectors hold the transformed free elements in the order of names.

pack(sys)[source]#

Flat (transformed) vector of the free elements of sys.

unpack(template, vec)[source]#

SpinSystem from template with the free elements replaced by vec (kept on the autograd graph when vec requires grad).

sample(n, generator=None)[source]#

(n, n_free) packed vectors drawn uniformly from the ranges (in the untransformed space; 'log' fields uniform in log10).

torchspin.ml.simulate(simulator, sys, exp, opt=None, **kw)[source]#

(x, y) from a simulator name or callable; y as a real float64 tensor.

torchspin.ml.simulate_batch(simulator, template, exp, opt, spec, params, *, grad=False, workers=0, **sim_kwargs)[source]#

Simulate every row of params ((N, n_free) packed vectors).

Returns (x, Y) with Y of shape (N, nPoints). With grad=True the rows stay on the autograd graph (params must requires_grad). With workers > 1 or workers='auto' (no-grad only) the rows are spread over a spawned process pool with one torch thread per worker. The pool is started on the first call and reused by later calls with the same worker count (and by esfit), so a data-generation loop pays the start-up cost once. 'auto' sizes it by the allocated cores and the available memory, as in torchspin.esfit.FitOptions.

For training sets of large spin systems, raise opt.Threshold (default 1e-4, as in EasySpin). Rhombic g with non-equivalent nuclei keeps hundreds of weak forbidden transitions per orientation, each costing an eigendecomposition. For Cu(II) with two 14N, Threshold=1e-2 was 3.6x faster and changed the spectrum by 0.4 % (normalized RMS).

class torchspin.ml.SpectrumDataset(spec, template, exp, opt, *, simulator='pepper', n=1000, seed=0, normalize='maxabs', x_out=None, noise=0.0, baseline=0.0, baseline_degree=1, sampler=None, dtype=torch.float32, sim_kwargs=None)[source]#

On-the-fly (spectrum, packed parameters) pairs.

Parameters are drawn with ParamSpec.sample() (or sampler(n, generator) when given), simulated with simulator under torch.no_grad, resampled to x_out if given, normalized (normalize), and corrupted with Gaussian noise of standard deviation noise (relative to the normalized scale) plus an optional random polynomial baseline of degree baseline_degree and amplitude baseline. Deterministic for a given seed (per worker of a DataLoader, the worker id is folded into the seed). n items per epoch (None = infinite).

make(vec, generator=None)[source]#

One sample: simulate vec, post-process, return (spectrum, vec).

torchspin.ml.cosine_loss(y, y_ref)[source]#

1 − cos(y, y_ref) along the last axis (shape-only, scale-free).

torchspin.ml.rmsd(y, y_ref, scale=True)[source]#

Root-mean-square deviation along the last axis, after a least-squares amplitude fit of y to y_ref when scale is set.

torchspin.ml.normalize(y, mode='maxabs', x=None)[source]#

Normalize spectra along the last axis (differentiable).

mode is 'maxabs' (max(abs(y)) = 1), 'area' (sum(abs(y)) * dx = 1, with dx from x, else 1), 'zscore' (zero mean, unit standard deviation) or None (unchanged). Any other value raises ValueError.

torchspin.ml.resample(x_new, x, y)[source]#

Linear interpolation of y(x) (uniform x) at x_new; differentiable in y. y may be (..., nX).