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'), withParamSpec.pack()/ParamSpec.unpack()between a flat tensor and aSpinSystembuilt 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,curryor a callable),(N, nPoints)output, optional process pool for no-grad data generation.SpectrumDataset— antorch.utils.data.IterableDatasetsampling 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), ...]}.fieldis aSpinSystemattribute ('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 (gis(1, 3)for one electron,Ais(nNuclei, 3)…); equal bounds fix an element.transformsmaps 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 ofnames.
- torchspin.ml.simulate(simulator, sys, exp, opt=None, **kw)[source]#
(x, y)from a simulator name or callable;yas 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)withYof shape(N, nPoints). Withgrad=Truethe rows stay on the autograd graph (paramsmustrequires_grad). Withworkers > 1orworkers='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 intorchspin.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-2was 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()(orsampler(n, generator)when given), simulated withsimulatorundertorch.no_grad, resampled tox_outif given, normalized (normalize), and corrupted with Gaussian noise of standard deviationnoise(relative to the normalized scale) plus an optional random polynomial baseline of degreebaseline_degreeand amplitudebaseline. Deterministic for a givenseed(per worker of aDataLoader, the worker id is folded into the seed).nitems per epoch (None= infinite).
- 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
ytoy_refwhenscaleis set.
- torchspin.ml.normalize(y, mode='maxabs', x=None)[source]#
Normalize spectra along the last axis (differentiable).
modeis'maxabs'(max(abs(y)) = 1),'area'(sum(abs(y)) * dx = 1, withdxfromx, else 1),'zscore'(zero mean, unit standard deviation) orNone(unchanged). Any other value raisesValueError.