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(). H0 and energies are in cm^-1 (internal); f converts the fit’s units to cm^-1; g is the tuple (ggT, principal, g, gap_cm) of the ground doublet; mu the Zeeman operators.

Raises:
property g[source]#

(ggT, principal, g, gap_cm) of the ground doublet.

class torchspin.lft.fit.Dataset[source]#

Base class of a block of observations with its forward model.

Subclasses provide observed, sigma and calculate(ctx); residuals() returns (calc - obs) / sigma. name labels the block in JointOutcome (made unique by JointFit); forward_ad is False for blocks whose Jacobian comes from jacobian_block instead 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 value lies 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 JointFit order (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 by sqrt(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.

as_dict()[source]#

Return {name: value} for every parameter.

table()[source]#

Return a text table of values and standard errors with chi^2 and dof.

class torchspin.lft.fit.GValues(g, sigma_=0.01, name='g')[source]#

Principal g values of the ground doublet (effective S = 1/2).

Parameters:
  • g (sequence of 3 float) – Observed principal g values; compared after sorting ascending.

  • sigma_ (float or sequence of 3 float, default 0.01) – Uncertainties (sorted with g).

  • name (str, default 'g')

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:
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)
x0()[source]#

Start values of all parameters, shape (n_params,).

free_mask()[source]#

Boolean mask of the free (not fixed) parameters, shape (n_params,).

context(x)[source]#

Evaluation Context at the full parameter vector x (tensor, shape (n_params,)).

residuals_torch(x, datasets=None)[source]#

Weighted residuals (calc - obs) / sigma of all (or the given) data sets, on the graph.

residuals(x)[source]#

Weighted residuals at the full parameter vector x as a NumPy array.

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 Spectrum blocks. free: boolean mask (default free_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() (defaults method='trf', x_scale='jac', xtol = ftol = gtol = 1e-12).

Returns:

JointOutcome

Return type:

JointOutcome

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.

with_start(x)[source]#

Copy with the parameter start values replaced by x (full vector, shape (n_params,)).

class torchspin.lft.fit.JointOutcome(result, chi2, n_points, null_directions)[source]#

Outcome of JointFit.fit().

Variables:
  • result (FitResult) – The shared parameter result.

  • chi2 (dict of str to float) – chi^2 of every data set.

  • n_points (dict of str to int) – Number of points of every data set.

  • null_directions (list of dict) – Undetermined parameter combinations (null_directions()).

summary()[source]#

Return the parameter table, chi^2 per data set and undetermined directions as text.

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.Experiment of 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.SpinSystem keywords (Nucs, A in MHz, lw in mT, …); S and g come from the model (setting them raises ValueError).

  • scale (float or 'auto', default 'auto') – Amplitude: 'auto' fits it analytically (least-squares projection, differentiated exactly), a float fixes it.

  • name (str, default 'spectrum')

jacobian_block(g, dg_dx)[source]#

d residuals / d x = sum_k d r / d g_k . d g_k / d x over the 6 symmetric components.

g (3, 3) detached; dg_dx (3, 3, nfree).

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_units times 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 quantity is unknown or field <= 0 (chi_units is 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 rtol times 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 by max(abs(x_j), 1).

Return type:

list[dict[str, float]]