torchspin.lft.fit#
Joint least-squares fits of ONE d^n ligand-field model to several kinds of data, with exact Jacobians.
Telser’s programs fit one data type each (DDNFIT: band energies; DDNSUS: chi(T); DDNMAG:
M(B, T)), and EPR g values come from DDN/DDNPOW without fitting. Here a single parameter
vector goes through one differentiable Hamiltonian into every observable, the residuals of all
data sets (each divided by its own sigma) are minimized together, and the Jacobian is exact.
Different data constrain different parameter combinations (bands: B, Dq, low-symmetry
splittings; susceptibility: zeta, k, zero-field splitting; g: the ground-doublet admixture;
an EPR spectrum: g through the lineshape), so a direction one data type leaves undetermined
(JointOutcome.null_directions) can be fixed by another. Outline (T and chiT
are measured arrays):
from torchspin import lft
from torchspin.lft.fit import FitParameter, JointFit, Bands, Susceptibility, GValues
params = [FitParameter("B", 900, 500, 1200), FitParameter("Dq", 1200, 500, 2000), ...]
def model(p): # named scalar tensors -> lft.ddn keywords
return dict(B=p["B"], C=4.2 * p["B"], zeta=p["zeta"], k=p["k"].expand(3),
V=lft.crystal_field(p["Dq"], p["Ds"], p["Dt"]))
fit = JointFit(7, params, model, [Bands([5, 13], [8100, 17500], sigma_=50),
Susceptibility(T, chiT, quantity="chiT", chi_units="cgs", sigma_=0.02),
GValues([2.1, 2.3, 4.9], sigma_=0.01)], units="cm^-1")
out = fit.fit()
print(out.summary())
Units: the model’s energy keywords, and Bands energies, are in the fit’s units (default
‘MHz’; ‘cm^-1’ is natural for ligand-field work). Fields in mT, temperatures in K,
susceptibility in each block’s chi_units, magnetization in M_units.
Jacobians: forward-mode AD (torch.func.jacfwd) through torchspin.lft for bands, g,
chi and M (cost about one evaluation plus a small amount per parameter). Spectrum blocks go
through torchspin.pepper_autograd(), which does not support forward mode;
their Jacobian is the exact chain rule d(spectrum)/d(g) . d(g)/d(x), with d(spectrum)/d(g) for the
six independent g components from a double-backward Jacobian-vector product through pepper.
- class torchspin.lft.fit.Bands(states, energies, sigma_=1.0, name='bands')[source]#
Band energies, numbered as DDNFIT does.
- Parameters:
states (sequence of int) – 1-based state numbers over all states in ascending energy (every state of a degenerate level counts); each energy is relative to state 1.
energies (sequence of float) – Observed energies in the fit’s
units.sigma_ (float or sequence of float, default 1.0) – Uncertainty per energy (same units).
name (str, default 'bands')
- Raises:
ValueError – If a state number is below 1.
- class torchspin.lft.fit.Context(ops, kwargs, units, constants)[source]#
Quantities shared by the data sets at one parameter vector, computed on demand.
Built by
JointFit.context().H0andenergiesare in cm^-1 (internal);fconverts the fit’s units to cm^-1;gis the tuple(ggT, principal, g, gap_cm)of the ground doublet;muthe Zeeman operators.- Raises:
ValueError – If the model returns
field.TypeError – If the model returns keywords that
torchspin.lft.ddn.hamiltonian()does not take.
- class torchspin.lft.fit.Dataset[source]#
Base class of a block of observations with its forward model.
Subclasses provide
observed,sigmaandcalculate(ctx);residuals()returns(calc - obs) / sigma.namelabels the block inJointOutcome(made unique byJointFit);forward_adisFalsefor blocks whose Jacobian comes fromjacobian_blockinstead of forward-mode AD.
- class torchspin.lft.fit.FitParameter(name, value, lower=-inf, upper=inf, fixed=False)[source]#
A named fit parameter with start value, bounds and a fixed flag.
- Parameters:
name (str) – Name; the key under which the value reaches
model(p).value (float) – Start value, in the unit the model expects (energies in the fit’s
units).lower (float, default -inf, inf) – Bounds.
upper (float, default -inf, inf) – Bounds.
fixed (bool, default False) – Keep the parameter at
value.
- Raises:
ValueError – If
valuelies outside[lower, upper].
- class torchspin.lft.fit.FitResult(names, values, stderr, correlation, free, chi2, dof, jacobian, success, message, nfev)[source]#
Best-fit values with standard errors and correlations from the exact Jacobian.
- Variables:
names (list of str) – Parameter names, in
JointFitorder (all parameters).values (ndarray, shape (n_params,)) – Best-fit values (fixed parameters at their start values).
stderr (ndarray, shape (n_params,)) –
sqrt(diag((J^T J)^+))for the free parameters. The residuals are already divided by sigma, so these are 1-sigma errors if the sigmas are right (multiply bysqrt(chi2/dof)otherwise). 0 for fixed parameters, NaN for parameters in an undetermined direction (null_directions()).correlation (ndarray, shape (n_free, n_free)) – Correlation matrix of the free parameters.
free (ndarray of bool, shape (n_params,)) – Which parameters were varied.
chi2 (float) – Sum of squared weighted residuals at the solution.
dof (int) – Number of residuals minus number of free parameters.
jacobian (ndarray, shape (n_residuals, n_free)) – Exact Jacobian of the weighted residuals at the solution.
success (bool) – Convergence flag of
scipy.optimize.least_squares().message (str) – Its message.
nfev (int) – Number of residual evaluations.
- class torchspin.lft.fit.GValues(g, sigma_=0.01, name='g')[source]#
Principal g values of the ground doublet (effective S = 1/2).
- class torchspin.lft.fit.JointFit(n, parameters, model, datasets, units='MHz', constants=MAG_CONSTANTS, device='cpu')[source]#
Fit one d^n ligand-field model to several data sets with exact Jacobians.
- Parameters:
n (int) – Number of d electrons.
parameters (sequence of FitParameter) – The fit parameters (unique names).
model (callable) –
model(p)maps the dict of named 0-d tensors totorchspin.lft.ddn.hamiltonian()keywords (B,C,A,zeta,V,k,alpha,slater), energies inunits. It must use torch operations so that the Jacobian is exact.datasets (sequence of Dataset) –
Bands,GValues,Susceptibility,Magnetization,Spectrum; duplicate names get an index appended.units (str, default 'MHz') – Energy unit of the model keywords and of
Bands.constants (MagConstants, default MAG_CONSTANTS) –
torchspin.lft.ddnmag.MagConstants.device (str, default 'cpu')
- Raises:
ValueError – If parameter names are not unique.
Examples
Fit the tetragonal splitting Ds of a Cu(II) model to its g values:
>>> from torchspin import lft >>> from torchspin.lft.fit import FitParameter, JointFit, GValues >>> params = [FitParameter('Dq', 1200.0, fixed=True), FitParameter('Ds', 1500.0, 500.0, 4000.0), ... FitParameter('Dt', 300.0, fixed=True)] >>> def model(p): ... return dict(zeta=830.0, k=(0.8, 0.8, 0.8), V=lft.crystal_field(p['Dq'], p['Ds'], p['Dt'])) >>> fit = JointFit(9, params, model, [GValues([2.063, 2.063, 2.423], sigma_=0.001)], units='cm^-1') >>> out = fit.fit() >>> out.result.success, round(out.result.as_dict()['Ds'], -1) (True, 2030.0)
- residuals_torch(x, datasets=None)[source]#
Weighted residuals
(calc - obs) / sigmaof all (or the given) data sets, on the graph.
- calculate(x)[source]#
Calculated values of every data set at the full parameter vector
x, keyed by data-set name.
- jacobian(x, free=None)[source]#
Exact Jacobian d(residuals)/d(x[free]), shape (n_residuals, n_free).
Forward-mode AD for most blocks; the chain rule through pepper for
Spectrumblocks.free: boolean mask (defaultfree_mask()).
- fit(datasets=None, **kw)[source]#
Fit all data sets, or only those named.
- Parameters:
datasets (sequence of str, optional) – Names of the data sets to fit (default: all).
**kw – Passed to
scipy.optimize.least_squares()(defaultsmethod='trf',x_scale='jac',xtol = ftol = gtol = 1e-12).
- Returns:
JointOutcome
- Return type:
- subset(names)[source]#
Copy restricted to the named data sets (for identifiability comparisons).
- Raises:
ValueError – If a name is not a data set of this fit.
- class torchspin.lft.fit.JointOutcome(result, chi2, n_points, null_directions)[source]#
Outcome of
JointFit.fit().- Variables:
- class torchspin.lft.fit.Magnetization(field, T, values, sigma_=0.01, M_units='muB', grid=<factory>, name='magnetization')[source]#
Powder magnetization at (field, temperature) points.
- Parameters:
field (sequence of float) – Fields in mT, broadcast against
T.T (sequence of float) – Temperatures in K.
values (sequence of float) – Observed M in
M_units.sigma_ (float or sequence of float, default 0.01) – Uncertainties in
M_units.M_units ({'muB', 'emu/mol', 'SI'}, default 'muB') – Bohr magnetons per ion, emu/mol, or A m^2/mol.
grid (OrientationGrid, default gauss_hemisphere(6)) – Field directions of the powder average.
name (str, default 'magnetization')
- class torchspin.lft.fit.Spectrum(experiment, options, spectrum, sigma_=1.0, system=<factory>, scale='auto', name='spectrum')[source]#
A CW EPR powder spectrum simulated by
torchspin.pepper_autograd()from the ground-doublet g.Only g carries the model parameters into the spectrum.
- Parameters:
experiment (Experiment) –
torchspin.Experimentof the measured spectrum.options (Options) –
torchspin.Options(matrix method).spectrum (sequence of float, shape (nPoints,)) – Observed spectrum.
sigma_ (float or sequence of float, default 1.0) – Uncertainty per point.
system (dict, default {}) – Extra
torchspin.SpinSystemkeywords (Nucs,Ain MHz,lwin mT, …);Sandgcome from the model (setting them raisesValueError).scale (float or 'auto', default 'auto') – Amplitude:
'auto'fits it analytically (least-squares projection, differentiated exactly), a float fixes it.name (str, default 'spectrum')
- class torchspin.lft.fit.Susceptibility(T, values, sigma_=0.01, field=100.0, quantity='chiT', chi_units='cgs', grid=<factory>, chi0=0.0, name='susceptibility')[source]#
Powder magnetic susceptibility chi = M/H or chi T versus temperature.
- Parameters:
T (sequence of float) – Temperatures in K.
values (sequence of float) – Observed chi (
chi_units) or chi T (chi_unitstimes K).sigma_ (float or sequence of float, default 0.01) – Uncertainties, same units as
values.field (float, default 100.0) – Measuring field in mT (> 0).
quantity ({'chiT', 'chi'}, default 'chiT')
chi_units ({'cgs', 'SI'}, default 'cgs') – cm^3/mol or m^3/mol.
grid (OrientationGrid, default gauss_hemisphere(6)) – Field directions of the powder average.
chi0 (float, default 0.0) – Temperature-independent susceptibility added to chi, in
chi_units.name (str, default 'susceptibility')
- Raises:
ValueError – If
quantityis unknown orfield <= 0(chi_unitsis checked when evaluated).
- torchspin.lft.fit.null_directions(result, rtol=1e-6, min_coef=0.05)[source]#
Parameter combinations the data do not determine (free parameters only).
- Parameters:
result (FitResult) – A fit result with its Jacobian.
rtol (float, default 1e-6) – A right singular vector of the column-scaled Jacobian counts as undetermined when its singular value is below
rtoltimes the largest.min_coef (float, default 0.05) – Coefficients smaller than this (after normalizing the largest to 1) are left out.
- Returns:
list of dict – One
{name: coefficient}dict per undetermined direction. The coefficients are for unit-scaled parameters: each column of the Jacobian is scaled bymax(abs(x_j), 1).- Return type: