torchspin.lft.dpnfit#

DPNFIT: fit p^n ligand-field parameters to observed level (band) energies, with an exact Jacobian.

Telser’s DPNFIT model (DPNFITCAL.F SCALC) in torch: the parameter vector X maps to the p^n Hamiltonian of torchspin.lft.dpn; an observation assigned to state number IE (1-based, all states counted in ascending energy, every spin and every component) is compared with D(IE) - D(1). The residuals are differentiable in X, the Jacobian is exact (forward-mode AD, torch.func.jacfwd), and DpnFit.fit() runs scipy.optimize.least_squares (trust-region reflective, with bounds) on it.

X vector (NX = 1 for p^1/p^5, 3 otherwise; missing trailing slots read as 0, as in SCALC):

X[0]             zeta (abs(zeta) is used; d abs(zeta)/d zeta = +1 at 0)
X[1], X[2]       F2 (Slater F^2, as in DPN), Trees alpha             (not for p^1, p^5)
lf_type 'X'      Ds, Dr                                              (crystal field)
lf_type 'A'      nlam values per ligand: sigma, pi-s (y), pi-c (x)   (AOM)
lf_type 'P'      E(px), E(py), E(pz)                                 (orbital energies)

with DPNFIT’s fixed constraints: AOM pi factors (pi_factors per ligand: e_pi_s = f_ss e_sigma, e_pi_c = f_cs e_sigma, then e_pi_c = f_sc e_pi_s, each only if nonzero), ligand equivalences (isymm, 1-based, with blfact), and option P orbital equivalences (orbital_isymm). There are no k slots: k enters only with a field, as fixed input.

Units#

Every energy slot of X, the observed energies, and the energies returned are in units (default 'MHz'; 'cm^-1' for Telser-style input). A weight w multiplies the squared residual: residual = sqrt(w) (calc - obs); with w = 1/sigma^2 (sigma in units) the residuals are dimensionless. The field magnitude B0 is in mT; angles (ligand and field direction) in radians, or degrees with degrees=True.

Modes#

mode="exact" (default): the direct p^n calculation, torchspin constants, the geometric ligand field with every element, and the full Zeeman operator. mode="dpn" reproduces the compiled program (torchspin.lft.dpn.dpn_hamiltonian() with program='dpnfit'): DPN’s constants, the hole route for p^4/p^5 with -V and -zeta, the mirror-image AOM for p^1/p^2/p^4/p^5, the dropped <+-1|V|0> AOM elements (DPN-01), and the Zeeman defect (DPNFIT-01). Without a field and without tilted AOM ligands the two agree.

LOWSPN#

With lowspn=True the ground state must carry the spin spngrnd (the S of its dominant free-ion term, ties to the later term in DPN’s order). Where it does not, every weighted residual is replaced by sqrt(w) * 1e5 cm^-1 (lowspn_policy="penalty", default; DPNFIT itself returns a stale objective there, finding DPNFIT-02) with derivative 0, or the residuals are computed anyway ("ignore").

Uncertainties#

FitResult carries the exact Jacobian at the solution, (J^T J)^-1, residual-scaled standard errors, and the parameter combinations the data do not determine (null; e.g. e_sigma - e_pi of one ligand only). measurements repeats the statistics with each band counted once: DPNFIT inputs list every component of a degenerate level as a row with the same energy, which overstates the data by the degeneracy (rows with the same energy and weight on consecutive state numbers form one measurement; rows with a vanishing Jacobian, such as the ground level at 0, carry no information).

Not ported: the DPNFIT input reader and report, STEPIT itself, and the assignment monitor and level-crossing tracker of the NumPy program.

>>> from torchspin.lft import dpnfit
>>> m = dpnfit.DpnFitModel(2, lf_type="X", units="cm^-1")
>>> prob = dpnfit.DpnFit(m, states=[6, 11], energies=[10000.0, 25000.0], x0=[500.0, 40000.0, 0.0, 0.0, 0.0],
...                      free=[True, True, False, False, False])
>>> res = prob.fit()
>>> res.success, [round(float(v), 1) for v in res.x[:2]]
(True, [6493.4, 62946.6])
torchspin.lft.dpnfit.LOWSPN_PENALTY_CM = 100000.0#

penalty per weighted residual (cm^-1) when LOWSPN rejects the ground spin

class torchspin.lft.dpnfit.DpnFit(model, states, energies, weights=None, *, x0, free=None, lower=None, upper=None, step=None, spngrnd=0.5, lowspn=False, lowspn_policy='penalty')[source]#

A DPNFIT problem: model, observations, start vector and fit configuration.

Parameters:
  • model (DpnFitModel) – The fixed input.

  • states (sequence of int) – 1-based state numbers (DPNFIT’s IE: all states in ascending energy, state 1 the ground state).

  • energies (sequence of float) – Observed D(IE) - D(1) in model.units; negative values are set to 0, as DPNFIT does.

  • weights (sequence of float, optional) – Weights w multiplying the squared residuals (negative set to 0); default 1. With w = 1/sigma^2 the residuals are dimensionless.

  • x0 (sequence of float) – Start vector in DpnFitModel.parameter_names() order (extra entries are carried along unused).

  • free (sequence of bool, optional) – Fitted entries; default all.

  • lower (sequence of float, optional) – Bounds; default unbounded.

  • upper (sequence of float, optional) – Bounds; default unbounded.

  • step (sequence of float, optional) – Typical parameter changes (SciPy x_scale); default max(abs(x0), 1).

  • spngrnd (float, default 0.5) – Required ground-state spin for LOWSPN (clamped by spin_clamp()).

  • lowspn (bool, default False) – Enforce the ground-state spin (not for p^1/p^5).

  • lowspn_policy ({'penalty', 'ignore'}, default 'penalty') – Where the ground spin is wrong: replace every weighted residual by sqrt(w) * 1e5 cm^-1 with zero derivative, or compute the residuals anyway.

Raises:

ValueError – For state numbers outside 1..C(6, n) (DPNFIT does not check, finding DPNFIT-04), lengths of states, energies and weights that differ, or an unknown lowspn_policy.

Examples

>>> from torchspin.lft import dpnfit
>>> m = dpnfit.DpnFitModel(2, lf_type='X', units='cm^-1')
>>> prob = dpnfit.DpnFit(m, states=[6, 11], energies=[10000.0, 25000.0],
...                      x0=[500.0, 40000.0, 0.0, 0.0, 0.0], free=[True, True, False, False, False])
>>> [round(float(v), 1) for v in prob.evaluate(prob.x0).calc]
[757.0, 10133.7]
property n_states: int[source]#

Number of states, C(6, n).

parameter_names()[source]#

Names of the entries of x0 (model names, then X<i> for extra entries).

n_effective()[source]#

Rows that carry information: weight > 0 and not state 1 (always 0).

energies(x)[source]#

All energies relative to the lowest, ascending, in units (differentiable in x).

residual_function(x)[source]#

The torch residual function of the full X, with the LOWSPN branch decided at x.

residuals(x)[source]#

sqrt(w) (calc - obs) at X (tensor; differentiable unless the LOWSPN penalty is active).

jacobian(x, free=None)[source]#

Exact d residuals / d X[free] (n_residuals, n_free) by forward-mode AD.

evaluate(x)[source]#

Energies, spin labels, residuals and objective at X (NumPy).

fit(*, ftol=1e-12, xtol=1e-12, gtol=1e-12, max_nfev=None, verbose=0)[source]#

Least-squares fit of the free entries of X.

SciPy least_squares (trust-region reflective, bounds) with the exact forward-mode Jacobian, starting from x0 clamped strictly inside the bounds. An iterate that stops just inside a bound is moved onto it when that lowers the objective, and the other parameters are then re-optimized with it held there.

Parameters:
  • ftol (float, default 1e-12) – SciPy tolerances.

  • xtol (float, default 1e-12) – SciPy tolerances.

  • gtol (float, default 1e-12) – SciPy tolerances.

  • max_nfev (int, optional) – Maximum function evaluations (SciPy default if None).

  • verbose (int, default 0) – SciPy verbosity.

Returns:

FitResult

Return type:

FitResult

measurement_groups()[source]#

Row indices grouped into measurements (same energy and weight, consecutive states).

measurement_stats(result, rtol=1e-6)[source]#

Uncertainties with each measurement counted once (one representative row per group).

class torchspin.lft.dpnfit.DpnFitModel(n, lf_type='X', nlam=1, angles=<factory>, isymm=<factory>, blfact=<factory>, pi_factors=<factory>, orbital_isymm=(1, 2, 3), B0=0.0, theta=0.0, phi=0.0, k=(1.0, 1.0, 1.0), mode='exact', degrees=False, units='MHz', constants=None)[source]#

Fixed (non-fitted) input of DPNFIT: configuration, ligand-field model, field and units.

The fitted vector X is described in the module docstring; its names are parameter_names().

Parameters:
  • n (int) – Number of p electrons, 1 to 5.

  • lf_type ({'X', 'A', 'P'}, default 'X') – Ligand-field model: 'X' crystal field (Ds, Dr), 'A' AOM, 'P' orbital energies.

  • nlam (int, default 1) – AOM: bonding parameters per ligand in X (1 to 3: sigma, pi-s (y), pi-c (x)).

  • angles (sequence of sequence of float, default []) – AOM ligand directions, one (theta, phi, psi) triple per ligand, radians unless degrees.

  • isymm (sequence of int, default []) – 1-based ligand equivalences: ligand j copies ligand isymm[j] - 1 scaled by blfact[j]; isymm[j] = j + 1 is independent. With isymm empty no equivalences apply and no ligand counts as independent, so pi_factors are not applied either.

  • blfact (sequence of float, default []) – Scale factors of the equivalent ligands (default 1).

  • pi_factors (sequence of (f_ss, f_cs, f_sc), default []) – Per independent ligand: e_pi_s = f_ss e_sigma, e_pi_c = f_cs e_sigma, then e_pi_c = f_sc e_pi_s, each only if nonzero (needs nlam >= 3).

  • orbital_isymm (sequence of int, default (1, 2, 3)) – Option P equivalences: E(p_j) = E(p_i) where the entries are equal.

  • B0 (float, default 0.0) – Field magnitude in mT (0: no field).

  • theta (float, default 0.0) – Field direction, radians unless degrees.

  • phi (float, default 0.0) – Field direction, radians unless degrees.

  • k (sequence of float, default (1.0, 1.0, 1.0)) – Orbital reduction factors (fixed; enter only with a field).

  • mode ({'exact', 'dpn'}, default 'exact') – 'exact': the direct p^n calculation; 'dpn': the compiled program’s matrix (module docstring).

  • degrees (bool, default False) – angles, theta and phi are in degrees.

  • units (str, default 'MHz') – Energy unit of X and of the energies.

  • constants (Constants, optional) – Default: TORCHSPIN_CONSTANTS ('exact') or DPN_CONSTANTS ('dpn').

Raises:

ValueError – For an unknown mode, lf_type or units, or n outside 1..5.

Examples

>>> from torchspin.lft import dpnfit
>>> m = dpnfit.DpnFitModel(2, lf_type='X', units='cm^-1')
>>> m.parameter_names(), m.n_states
(['zeta', 'F2', 'alpha', 'Ds', 'Dr'], 15)
property np_: int[source]#

n for n <= 3, else 6 - n.

Type:

DPNFIT’s NP

property nlig: int[source]#

Number of AOM ligands (rows of angles).

property offset: int[source]#

Index (0-based) of the first ligand-field slot (DPNFIT’s NX).

property n_states: int[source]#

Number of states, C(6, n).

parameter_names()[source]#

Names of the X slots, in order ('zeta', 'F2', 'alpha', then the ligand-field slots).

property n_parameters: int[source]#

Number of X slots.

bonding(x)[source]#

(nlig, 3) (e_sigma, e_pi_s(y), e_pi_c(x)) after pi factors and equivalences, in units.

orbital_energies(x)[source]#

Option P: (E(px), E(py), E(pz)) after the equivalences, in units.

ligand_field(x)[source]#

Real-orbital ligand-field matrix (px, py, pz), geometric convention, in units.

field()[source]#

Field vector in mT, None at zero field.

hamiltonian(x)[source]#

Complex Hermitian H(X) in units (size C(6, n) in both modes).

class torchspin.lft.dpnfit.Evaluation(x, energies, calc, residuals, objective, spins, dominant, ground_spin_ok)[source]#

DPNFIT’s SCALC at one X (returned by DpnFit.evaluate()); NumPy arrays.

Variables:
  • x (ndarray) – The X vector.

  • energies (ndarray, shape (N,)) – All N energies relative to the lowest, ascending, in units.

  • calc (ndarray, shape (n_obs,)) – Calculated energies of the observed states.

  • residuals (ndarray, shape (n_obs,)) – sqrt(w) (calc - obs) (with the LOWSPN penalty if active).

  • objective (float) – sum w (calc - obs)^2 (DPNFIT’s FOBJ, before any LOWSPN penalty).

  • spins (ndarray or None, shape (N,)) – S of the dominant free-ion term of each state (None for p^1, p^5).

  • dominant (list of str) – Label of the dominant term of each state.

  • ground_spin_ok (bool) – Whether the LOWSPN condition holds (True without LOWSPN).

x: ndarray#

Alias for field number 0

energies: ndarray#

Alias for field number 1

calc: ndarray#

Alias for field number 2

residuals: ndarray#

Alias for field number 3

objective: float#

Alias for field number 4

spins: ndarray | None#

Alias for field number 5

dominant: list[str]#

Alias for field number 6

ground_spin_ok: bool#

Alias for field number 7

class torchspin.lft.dpnfit.FitResult(names, x, free, objective, initial_objective, residuals, n_data, jac, cov_unscaled, nfev, njev, success, message, at_bound, null, measurements=None, final=None)[source]#

Result of DpnFit.fit(); arrays over all parameters (fixed included) unless noted.

Variables:
  • names (list of str) – Parameter names.

  • x (ndarray) – Best-fit X (fixed entries unchanged).

  • free (ndarray of bool) – Fitted entries.

  • initial_objective (objective,) – Sum of squared residuals at the solution and at the start.

  • residuals (ndarray, shape (n_obs,)) – sqrt(w) (calc - obs) at the solution.

  • n_data (int) – Informative rows (w > 0, state != 1).

  • jac (ndarray, shape (n_obs, n_free)) – Exact Jacobian at the solution.

  • cov_unscaled (ndarray, shape (n_free, n_free)) – (J^T J)^-1 (NaN when a direction is undetermined).

  • njev (nfev,) – Function and Jacobian evaluations.

  • success (bool) – SciPy’s success flag.

  • message (str) – SciPy’s message.

  • at_bound (ndarray of bool, shape (n_free,)) – Free parameters at a bound.

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

  • measurements (MeasurementStats or None) – Statistics with each band counted once.

  • final (Evaluation or None) – DpnFit.evaluate() at the solution.

  • dof (n_free,) – Properties: number of free parameters, n_data - n_free.

  • cov (ndarray) – Property: s^2 (J^T J)^-1 with s^2 = objective / dof.

  • stderr_unscaled (stderr,) – Properties: standard errors over all parameters (NaN for fixed).

  • correlation (ndarray) – Property: correlation matrix of the free parameters.

property cov: ndarray[source]#

s^2 (J^T J)^-1 with s^2 = objective / dof (free x free).

class torchspin.lft.dpnfit.MeasurementStats(groups, informative, n_measurements, objective, cov_unscaled, stderr, stderr_unscaled)[source]#

Uncertainties with the repeated components of one band counted once.

Variables:
  • groups (list of list of int) – Row indices grouped into measurements.

  • informative (list of bool) – Whether each group carries information.

  • n_measurements (int) – Number of informative measurements.

  • objective (float) – Sum of squared residuals over the representative rows.

  • cov_unscaled (ndarray, shape (n_free, n_free)) – (J^T J)^-1 over the representative rows (NaN if undetermined).

  • stderr (ndarray, shape (n_parameters,)) – Residual-scaled standard errors (NaN for fixed or undetermined).

  • stderr_unscaled (ndarray, shape (n_parameters,)) – sqrt(diag((J^T J)^-1)): right for weights 1/sigma^2.

  • dof (int) – Property: measurements minus determined parameters.

torchspin.lft.dpnfit.null_directions(jac, names, rtol=1e-7)[source]#

Combinations of parameters that the data do not determine.

Columns of jac are normalized first; each right singular vector with a singular value below rtol times the largest (and each all-zero column) is returned.

Parameters:
  • jac (array_like, shape (n_rows, n_params)) – Jacobian.

  • names (sequence of str) – Column names.

  • rtol (float, default 1e-7) – Relative singular-value threshold.

Returns:

list of dict – {name: coefficient} per undetermined direction (unit length, in parameter units).

Return type:

list[dict[str, float]]

Examples

>>> import numpy as np
>>> from torchspin.lft import dpnfit
>>> (d,) = dpnfit.null_directions(np.array([[1.0, 1.0], [2.0, 2.0]]), ['a', 'b'])
>>> {k: round(v, 4) for k, v in d.items()}
{'a': 0.7071, 'b': -0.7071}
torchspin.lft.dpnfit.spin_clamp(np_, s)[source]#

The ground-state spin as DPNFIT stores it (DPNFIT.F ll. 217-226).

Parameters:
  • np_ (int) – DPNFIT’s NP (n for n <= 3, else 6 - n).

  • s (float) – Requested ground-state spin.

Returns:

float – 0.5 for NP = 1; 0 or 1 for NP = 2; 0.5 or 1.5 for NP = 3.

Return type:

float