differentiable_spectrum#
A powder CW EPR spectrum through which gradients flow to every spin
Hamiltonian parameter that is a tensor with requires_grad=True, for
gradient-based fitting, sensitivity analysis and machine learning.
- torchspin.differentiable_spectrum(g, lw_mT, mwFreq_GHz, B_range, nPoints=1024, Harmonic=1, GridSize=31, GridSymmetry='auto', device=None, S=0.5, Nucs=None, A=None, D=None, Temperature=None, method='pepper')[source]#
Differentiable CW EPR powder spectrum of a one-electron spin system.
Builds a
SpinSystem, anExperiment(field sweep) andOptionsfrom the arguments and, with the defaultmethod='pepper', evaluates them withtorchspin.pepper_autograd(), whose forward output equalstorchspin.pepper()to rounding.torch.autogradthen propagates gradients to every argument passed as a tensor withrequires_grad=True:g,A,D,lw_mTandTemperature.- Parameters:
g (Tensor, shape (3,)) – Principal g values
[gx, gy, gz](dimensionless), in the molecular frame (nogFrame). Must be exactly 1-D with three entries. Its device sets the defaultdeviceand its dtype the dtype ofspec.lw_mT (float or Tensor) – Gaussian line width, FWHM in mT (
Sys.lw = [lw_mT, 0]); must be positive. A 0-d tensor that requires grad gives line-width gradients.mwFreq_GHz (float) – Microwave frequency in GHz (converted with
float; not differentiable).B_range (tuple of float) – Field sweep
(B_min, B_max)in mT,B_min < B_max.nPoints (int, default 1024) – Number of points of the field axis.
Harmonic (int, default 1) – Detection harmonic: 0 absorption, 1 first derivative, 2 second derivative.
GridSize (int or list of int, default 31) –
Options.GridSize: an intN(knots along a quarter meridian, no interpolation) or[N, N_interp](EasySpin grid interpolation). The deprecated methods use only the first value.GridSymmetry (str, default 'auto') –
Options.GridSymmetry:'auto'(also''orNone) detects the symmetry from the Hamiltonian; otherwise one of EasySpin’s grid symmetries ('D2h','Dinfh','Ci','C1','O3', …).device (str, optional) – Torch device for the computation. Default
None=str(g.device).S (float, default 0.5) – Electron spin quantum number (one electron spin).
Nucs (list of str, optional) – Nuclear isotopes, e.g.
['1H']or['14N', '1H'](asSpinSystem.Nucs). DefaultNone: no nuclei.A (Tensor, optional) – Hyperfine couplings in MHz, any form
SpinSystem.Aaccepts for one electron spin, typically principal values(nNuclei, 3)or full tensors(3*nNuclei, 3); a 1-D(3,)tensor is one nucleus. Used only together withNucs(AwithoutNucsraisesValueError). Must be on the same device asg.D (Tensor, optional) – Zero-field splitting in MHz (needs
S >= 1): a 0-d or(1,)tensorD(E = 0),(2,)[D, E]or(3,)principal values[Dxx, Dyy, Dzz]. Must be on the same device asg.Temperature (float or Tensor, optional) – Temperature in K for Boltzmann populations. Default
None: infinite temperature (equal populations). A 0-d tensor that requires grad gives temperature gradients.method ({'pepper', 'broadband', 'analytical'}, default 'pepper') –
'pepper':pepper_autograd().'broadband'(diagonalize H(B) at every field point, soft Gaussian per transition) and'analytical'(closed-form S = 1/2 resonance fields; used only whenNucs,DareNoneandS = 0.5, otherwise the broadband model runs) are the earlier stand-alone models. They sum discrete orientations without interpolation or projection, carry orientation-grid ripple and are deprecated.
- Returns:
B_axis (torch.Tensor, shape (nPoints,)) – Field axis in mT,
linspace(B_min, B_max, nPoints), ong.device.spec (torch.Tensor, shape (nPoints,)) – Spectrum (pepper’s intensity scale and harmonic), dtype of
g, ong.device, on the autograd graph of the inputs that require grad.
- Raises:
ValueError – If
gis not of shape(3,),lw_mT <= 0,Harmonicis not 0, 1 or 2,AorDis on a different device thang,methodis unknown, or the constructedSpinSystem,ExperimentorOptionsrejects a value (e.g. an unknown isotope,B_min >= B_max,mwFreq_GHz <= 0, an unknownGridSymmetry).- Warns:
DeprecationWarning – For
method='broadband'andmethod='analytical'.- Return type:
See also
torchspin.pepper_autograd.pepper_autogradThe differentiable pepper path for arbitrary
SpinSystem,ExperimentandOptions.torchspin.pepperSame forward result; switches to the differentiable path itself when an input requires grad.
torchspin.esfitLeast-squares fitting.
Notes
For anything beyond one electron spin with principal g values (
gFrame, strains, Lorentzian widths, several electron spins, frequency sweeps), build theSpinSystemyourself and callpepper/pepper_autograd. See KNOWN_LIMITATIONS.md, “Autograd — differentiable pepper” for the gradient validation and the unsupported configurations.Examples
>>> import torch >>> from torchspin import differentiable_spectrum >>> g = torch.tensor([2.0, 2.1, 2.2], dtype=torch.float64, requires_grad=True) >>> B, spec = differentiable_spectrum(g, lw_mT=1.0, mwFreq_GHz=9.5, ... B_range=(300.0, 350.0), nPoints=256, ... GridSize=10) >>> B.shape, spec.shape, spec.requires_grad (torch.Size([256]), torch.Size([256]), True) >>> (grad_g,) = torch.autograd.grad(spec.pow(2).sum(), g) >>> grad_g.shape torch.Size([3])
Gradients with respect to a hyperfine tensor and the line width:
>>> A = torch.tensor([[20.0, 20.0, 80.0]], dtype=torch.float64, requires_grad=True) >>> lw = torch.tensor(1.0, dtype=torch.float64, requires_grad=True) >>> B, spec = differentiable_spectrum(g, lw, 9.5, (300.0, 350.0), nPoints=256, ... GridSize=10, Nucs=['1H'], A=A) >>> grad_A, grad_lw = torch.autograd.grad(spec.pow(2).sum(), [A, lw]) >>> grad_A.shape, grad_lw.shape (torch.Size([1, 3]), torch.Size([]))
See also
TorchSpin — GPU Acceleration & Automatic Differentiation, and torchspin.ml for training
and inference on top of the differentiable simulators.