esfit#
Least-squares fitting of simulated spectra to data with local optimizers
(Nelder-Mead simplex, Levenberg-Marquardt, trust-region, L-BFGS-B, Powell) and
global ones (particle swarm with a simplex polish, genetic algorithm, grid
search, Monte Carlo). FitOptions selects the method, the scaling,
baseline and residual target, and the stopping criteria; FitResult
holds the fitted parameters, the fitted spectrum, residuals and, where
available, standard errors and the parameter covariance.
- torchspin.esfit(data, model_fn, p0, vary=None, lb=None, ub=None, options=None)[source]#
Fit a model to data by least squares (port of EasySpin’s
esfit).The model output is scaled and given a polynomial baseline (
FitOptions.autoscale,FitOptions.baseline), the residualsfit - dataare transformed (FitOptions.target), and their RMSD is minimized over the varied parameters within their bounds.- Parameters:
data (array_like or Tensor) – Experimental data. Flattened to 1-D, so any shape works as long as the model returns the same number of values (
n_data).model_fn (callable) –
The model. Its calling convention depends on
p0:Array
p0:model_fn(p)withpthe full parameter vector, anumpy.ndarrayof shape(n_params,)(fixed entries included).Dict
p0and a torchspin simulator (model_fn.__name__ispepper,garlic,chiliorsalt, or the function is defined in atorchspinmodule):model_fn(p['Sys'], p['Exp']), ormodel_fn(p['Sys'], p['Exp'], p['Opt'])whenp0has an'Opt'entry; the second return value (the spectrum) is the model output. Forgarlic()an unsetOptions.AccumMethodis switched to'linear'(except in the fast-motion regime or withExp.mwPhase), because the default nearest-bin accumulation is piecewise constant in g and A.Dict
p0and any other callable:model_fn(p)withpa deep copy ofp0whose varied fields hold the trial values.
The output may be any array-like or tensor (detached and flattened); it must have
n_dataelements.p0 (array_like, shape (n_params,), or dict) – Start values. Array style: one float per parameter. Dict style: a mapping from names to objects, e.g.
{'Sys': SpinSystem(...), 'Exp': Experiment(...), 'Opt': Options(...)}; the fields named invary(orlb/ub) are read from these objects and must be scalars (int or float) or lists/arrays/tensors, which are varied element-wise in the shape the field has on the object. For aSpinSystemthat is the normalized shape, e.g.gis(nElectrons, 3),Ais(nNuclei, 3*nElectrons)andlwis[GaussianFWHM, LorentzianFWHM].vary (array_like, shape (n_params,), or dict, optional) – Allowed variation: the bounds are
p0 - varyandp0 + vary, andvary = 0fixes a parameter. Dict style mirrorsp0, e.g.{'Sys': {'lw': [0.0, 0.3]}}, each value in the shape of its field. In the dict style the lower bound of fields that cannot be negative (lw,lwpp,lwEndor,HStrain,HStrainL,gStrain,AStrain,DStrain,weight,initState,tcorr,Diff,T1,T2) is clipped at zero, as EasySpin’sesfitdoes. A plain vector carries no field names and is used as given, sovarylarger thanp0there means a negative lower bound. Give eithervaryorlb/ub.lb (array_like, shape (n_params,), or dict, optional) – Explicit lower and upper bounds, used exactly as given;
lb == ubfixes a parameter. Dict style: both are required, with the same keys and fields as each other, the layout ofvary, andp0within them. Array style: a missinglborubis-infor+inf, which only'lbfgsb','powell'and'trf'handle; the other methods raiseValueErrorfor an infinite bound.ub (array_like, shape (n_params,), or dict, optional) – Explicit lower and upper bounds, used exactly as given;
lb == ubfixes a parameter. Dict style: both are required, with the same keys and fields as each other, the layout ofvary, andp0within them. Array style: a missinglborubis-infor+inf, which only'lbfgsb','powell'and'trf'handle; the other methods raiseValueErrorfor an infinite bound.options (FitOptions, optional) – Algorithm, scaling, baseline, target, budget, parallelism and progress. Default
FitOptions().
- Returns:
FitResult – Best-fit active parameters (
pfit,pnames), the fitted curve and residuals (each of shape(n_data,)),scale,baseline,rmsd, uncertainties (pstd,ci95,cov,corr) and diagnostics. SeeFitResult.- Raises:
ValueError – If both
varyandlb/ubor neither are given; if an arrayvary,lborubdoes not have one entry per parameter; if every parameter is fixed; in the dict style, if a key is not inp0, an object has no such field, a shape does not match the field, only one oflb/ubis given, they name different keys or fields,lb > ub, orp0lies outside[lb, ub]; if a varied parameter has an infinite bound and the method needs finite ones; ifFitOptions.method,autoscale,lsq_negative_scale,target,workers,n_workersorbaselineis invalid (checked before any model evaluation); for'grid', if the grid has more thanmax_iterpoints. A model output with the wrong number of values raisesValueErroronly at the final evaluation, after the optimizer has run (see Notes).TypeError – In the dict style, if a varied field is neither a number nor a list/array/tensor.
- Warns:
UserWarning – If
autoscale='lsq'finds a negative scale at the fitted parameters; if a parameter has no effect on the residuals at the finite-difference step (itspstdis thennan); if parallel'trf'/'lbfgsb'probes are requested with SciPy < 1.16.- Return type:
See also
Notes
Before each evaluation the parameters are clipped to their bounds. During the optimization a model that raises
ValueError,RuntimeErrorornumpy.linalg.LinAlgErrorscores an RMSD of 1e10 instead of stopping the fit. The first such failure of a fit is reported with a warning, andFitResult.n_failed_evalscounts them all, so a configuration error does not go unnoticed even though the fit runs on.The local optimizers (
'levmar','trf','lbfgsb') and the uncertainty estimate use finite differences, so the model must be smooth in its parameters. A custom model that wraps garlic should passOptions(AccumMethod='linear')or'explicit'. See docs/pitfalls.md, “garlic’sAccumMethod='binning'in fits” and “Model sign withautoscale='lsq'”.Uncertainties: the Jacobian of the target-transformed residuals with respect to the active parameters is taken by central differences (step
1e-7 * max(|p|, 1)), the covariance is the HC1 sandwich estimator(J'J)^-1 J' diag(r^2) J (J'J)^-1 * n_data / (n_data - n_active), andci95ispfit +/- 1.96 * pstd.rare the untransformed residuals; fortarget='int'or'diff'the middle term isJ' T diag(r^2) T' JwithTthe transformation, which accounts for the correlation it gives the noise.Examples
Fit the position and width of a Gaussian line; the amplitude is absorbed by the least-squares scale:
>>> import numpy as np >>> from torchspin import esfit, FitOptions >>> x = np.linspace(-5, 5, 201) >>> def model(p): ... return np.exp(-0.5 * ((x - p[0]) / p[1]) ** 2) >>> data = 3.0 * model([0.5, 1.2]) >>> res = esfit(data, model, p0=[0.0, 1.0], vary=[2.0, 0.5], ... options=FitOptions(method='levmar')) >>> np.round(res.pfit, 3).tolist(), round(res.scale, 3) ([0.5, 1.2], 3.0)
Explicit bounds;
lb == ubfixes the width, so only the position is fitted:>>> res = esfit(data, model, p0=[0.0, 1.2], lb=[-1.0, 1.2], ub=[1.0, 1.2], ... options=FitOptions(method='levmar')) >>> res.pnames, res.p_fixed.tolist(), round(float(res.pfit[0]), 3) (['p0'], [False, True], 0.5)
Dict style with a torchspin simulator: fit the Lorentzian line width of a garlic spectrum (
lw = [GaussianFWHM, LorentzianFWHM]in mT; the Gaussian width is fixed byvary = 0):>>> from torchspin import SpinSystem, Experiment, garlic >>> exp = Experiment(mwFreq=9.5, Range=[335, 343], nPoints=256) >>> _, data = garlic(SpinSystem(S=0.5, g=2.003, lw=[0.0, 0.5]), exp) >>> p0 = {'Sys': SpinSystem(S=0.5, g=2.003, lw=[0.0, 0.4]), 'Exp': exp} >>> res = esfit(data, garlic, p0, vary={'Sys': {'lw': [0.0, 0.3]}}, ... options=FitOptions(method='levmar')) >>> res.pnames, round(float(res.pfit[0]), 2) (['Sys.lw[1]'], 0.5)
- class torchspin.FitOptions(method='simplex', autoscale='lsq', lsq_negative_scale='clip', baseline=-1, target='fcn', max_iter=2000, tol_fun=1e-06, tol_x=1e-06, verbosity=0, callback=None, compute_uncertainties=True, grid_points=10, mc_samples=1000, mc_temp_start=1.0, mc_temp_end=0.0001, ga_population=50, ga_mutation=0.1, ga_crossover=0.7, ga_elite=5, swarm_size=30, swarm_inertia=0.7, swarm_cognitive=1.4, swarm_social=1.4, lm_lambda=0.001, lm_delta=0.001, lm_gradient_tol=1e-05, lm_step_tol=1e-08, trf_diff_step=None, trf_x_scale='jac', trf_gradient_tol=1e-07, n_workers=1, workers='auto', devices=None, seed=None, progress=None, progress_every=None, progress_interval=1.0, max_time=None, stop_when=None)[source]#
Options for
esfit(): optimizer, scaling, baseline, target, budget.All fields have defaults, so
FitOptions()is a complete set of options. The dataclass does not validate its fields; an invalid value raises (or is ignored, see each entry) whenesfit()uses it.- Parameters:
method (str, default 'simplex') –
Optimization algorithm. Any other value makes
esfit()raiseValueError.'simplex': Nelder-Mead in parameters rescaled to [-1, 1] (local, derivative-free; port of EasySpin’sesfit_simplex).'levmar': Levenberg-Marquardt on the residual vector (local; forward-difference Jacobian with Broyden updates, port of EasySpin’sesfit_levmar).'trf': bounded trust-region reflective least squares on the residual vector (local; SciPyleast_squares(method='trf'), see thetrf_*fields).'lbfgsb': L-BFGS-B on the RMSD (local; finite-difference gradient).'powell': Powell’s method (local, derivative-free).'swarm': particle swarm only (global, no local polish).'global': particle swarm followed by a Nelder-Mead polish from the swarm’s best point; recommended for derivative CW EPR spectra, whose loss has many narrow local minima.'genetic': genetic algorithm (global).'montecarlo': uniform random sampling followed by simulated annealing around the best sample (global).'grid': systematic grid search between the bounds.
autoscale ({'lsq', 'maxabs', 'none'}, default 'lsq') – How the model output is scaled to the data before the residuals are formed.
'lsq': least-squares scale (constrained to be non-negative, as in EasySpin), solved jointly with the baseline.'maxabs':max|data| / max|model|.'none': scale 1. Other values raiseValueError. With'lsq'the model must carry the sign of the signal: fit an inversion-recovery curve with-exp(-t/T), notexp(-t/T).lsq_negative_scale ({'clip', 'abs'}, default 'clip') – What
autoscale='lsq'does when the unconstrained scale comes out negative (model anti-correlated with the data).'clip'returns the constrained least-squares optimum: scale 0 with the baseline refitted alone.'abs'reproduces EasySpin’scoeffs(1) = abs(coeffs(1)), which mirrors the model but keeps the baseline solved for the opposite sign, so the objective is not a least-squares fit of anything.esfit()warns if the final fit has a negative unconstrained scale.baseline (int, default -1) – Order of the polynomial baseline fitted together with the scale, on the abscissa
linspace(0, 1, n_data):-1no baseline,0constant,1linear,2quadratic, and so on.target ({'fcn', 'int', 'diff', 'auto'}, default 'fcn') – Transformation of the residual vector
fit - databefore the RMSD is computed.'fcn'(EasySpin’s default): the residuals as they are; with white noise this is the maximum-likelihood fit.'int': their cumulative sum (smooths the loss of derivative spectra with many resolved lines, which helps a poor start converge, but weights the noise as a random walk, so the fitted parameters scatter more than with'fcn').'diff': their first difference (numpy.diffwith a leading 0).'auto':'int'when the data look like a derivative spectrum (|mean(data)| < 0.1 * std(data)), else'fcn'; the choice is made from the data alone, not from the simulator’sHarmonic. For'int'and'diff'the reported uncertainties account for the noise correlation the transformation introduces. A rugged derivative fit can be started with'int'(ormethod='global') and finished with'fcn'from itspfit.max_iter (int, default 2000) – Iteration or evaluation budget. Its meaning depends on
method: SciPy’smaxiterfor'simplex','lbfgsb'and'powell'; LM iterations for'levmar'; SciPy’smax_nfevfor'trf'(see Notes); iterations ('swarm') or generations ('genetic'); for'global'the swarm phase getsmax(20, max_iter // 2)iterations and the simplex polishmax(200, max_iter - evaluations used by the swarm); for'montecarlo'the random samples are capped atmax_iterand the annealing runsmax(1, max_iter - samples)steps; for'grid'at mostmax_itergrid points are evaluated.tol_fun (float, default 1e-6) – Function tolerance. SciPy’s
fatol('simplex') orftol('lbfgsb','powell','trf'). For'swarm'and'genetic'the run stops once the best RMSD (in data units) falls belowtol_fun.tol_x (float, default 1e-6) – Parameter-step tolerance: SciPy’s
xtolfor'powell'and'trf', and the relative step threshold of'levmar'(in the [-1, 1]-rescaled parameters).'simplex'uses a fixedxatolof 1e-4 in rescaled parameters instead.verbosity (int, default 0) –
0: silent.1: a summary of the setup, phase headers, the final parameters and fit statistics, and SciPy’sdispoutput.2: also one line per iteration (best RMSD) for'swarm','global','genetic'and'montecarlo'. Printed to stdout.callback (callable or None, default None) – Called once per iteration by
'swarm','global'(swarm phase),'genetic'and'montecarlo'(annealing phase, about 20 times) with a dict{'method': str, 'iter': int (1-based), 'max_iter': int, 'best_f': float, 'best_x': numpy.ndarray};best_xholds the active parameters. Use it to drive live plots. An exception raised in the callback does not stop the fit; the first one per fit is reported with aRuntimeWarning. Useprogressfor a callback that works with every method.compute_uncertainties (bool, default True) – Estimate
pstd,ci95,covandcorrafter a successful fit (2 * n_activeextra model evaluations, seeesfit()Notes).Falseleaves thoseFitResultfieldsNone.grid_points (int, default 10) –
'grid': points per parameter axis (at least 2), fromlbtoubinclusive. The grid hasgrid_points ** n_activepoints; only the firstmax_iterof them, initertools.productorder, are evaluated.mc_samples (int, default 1000) –
'montecarlo': number of uniform random samples between the bounds (capped atmax_iter).mc_temp_start (float, default 1.0 and 1e-4) –
'montecarlo': start and end temperature of the annealing phase, decreased geometrically. The temperature sets both the acceptance probabilityexp(-dRMSD / T)and the proposal widthT * (ub - lb).mc_temp_end (float, default 1.0 and 1e-4) –
'montecarlo': start and end temperature of the annealing phase, decreased geometrically. The temperature sets both the acceptance probabilityexp(-dRMSD / T)and the proposal widthT * (ub - lb).ga_population (int, default 50) –
'genetic': population size (at leastga_elite + 2).ga_mutation (float, default 0.1) –
'genetic': per-parameter mutation probability; a mutation adds Gaussian noise with standard deviation0.05 * (ub - lb).ga_crossover (float, default 0.7) –
'genetic': probability of a uniform crossover between the two tournament-selected parents.ga_elite (int, default 5) –
'genetic': number of best individuals copied unchanged into the next generation (at least 1).swarm_size (int, default 30) –
'swarm'and'global': number of particles (at least 4).swarm_inertia (float, default 0.7) – Particle-swarm inertia weight.
swarm_cognitive (float, default 1.4) – Particle-swarm attraction to each particle’s own best position.
swarm_social (float, default 1.4) – Particle-swarm attraction to the swarm’s best position.
lm_lambda (float, default 1e-3) –
'levmar': initial damping, relative to the largest diagonal element ofJ.T @ J.lm_delta (float, default 1e-3) –
'levmar': forward-difference step for the Jacobian, in the parameters rescaled to [-1, 1] (EasySpinFitOpt.delta).lm_gradient_tol (float, default 1e-5) –
'levmar': stop when the infinity norm of the gradientJ.T @ rfalls below this value (EasySpinFitOpt.TolFun).lm_step_tol (float, default 1e-8) – Not used.
'levmar'takes its step tolerance fromtol_x.trf_diff_step (float or None, default None) –
'trf': relative finite-difference step for the Jacobian (SciPydiff_step;Noneis SciPy’s default, about 1.5e-8). Relative to the physical parameter values, unlikelm_delta.trf_x_scale ({'jac'} or float or ndarray, default 'jac') –
'trf': SciPyx_scale.'jac'scales from the Jacobian columns; an array needs one entry per active (non-fixed) parameter.trf_gradient_tol (float, default 1e-7) –
'trf': SciPygtol.tol_funandtol_xare passed asftolandxtol.n_workers (int or 'auto', default 1) – Parallel model evaluations.
1: sequential. An int > 1: up to that many workers.'auto': the cores this process may use (affinity and SLURM aware), at most 32, and at most one worker per ~0.5 GB of half the available memory. Population methods ('swarm','global','genetic','montecarlo','grid') evaluate each population concurrently;'levmar','trf','lbfgsb'and the uncertainty estimate evaluate the finite-difference probes of each Jacobian or gradient concurrently ('trf'and'lbfgsb'need SciPy >= 1.16 and otherwise warn and run sequentially).'simplex'and'powell'are always sequential.workers ({'auto', 'processes', 'threads'}, default 'auto') – Backend for
n_workers > 1.'auto'and'processes'use a spawned process pool with the cores split between the workers (each worker is a separate Python process with its own torch); the model is sent by value withcloudpickle(needed for models defined in a notebook), and a model that cannot be sent falls back to a thread pool.'threads'forces a thread pool, which gains little because torchspin’s forward models hold the GIL.devices (list or None, default None) – GPUs for process workers, e.g.
['cuda:0', 'cuda:1'](CUDA device strings, ints ortorch.device): each spawned worker is pinned to one of them, round-robin, throughCUDA_VISIBLE_DEVICES, so a model that usesdevice='cuda'runs on its own GPU.Noneleaves the workers’ GPU visibility unchanged. Ignored by the thread backend. A non-CUDA entry raisesValueErrorwhen the pool is created.seed (int or None, default None) – Seed of the NumPy random generator of
'montecarlo','genetic','swarm'and'global'.None: a different realization on every run. An int makes these fits reproducible (recommended for tutorials, regression tests and published numbers).progress (None, 'text', 'bar' or callable, default None) – Real-time progress for every method.
None: silent.'text': one flushed line per report (iteration, evaluations, current and best RMSD, elapsed time, evaluations per second, ETA when the budget is known), plus a resource summary at the start and a totals line at the end.'bar': atqdmbar (text iftqdmis missing). A callable is called asprogress(info)with a dict (keys'method', 'phase', 'iter', 'iter_total', 'n_evaluations', 'eval_total', 'rmsd', 'best_f', 'best_x', 'elapsed_s', 'evals_per_s', 'eta_s'); returningFalsestops the fit. An exception it raises does not stop the fit; the first one per fit is reported with aRuntimeWarning. Withn_workers > 1reports arrive per evaluation chunk, not per evaluation.progress_every (int or None, default None) – Report at least every this many model evaluations.
progress_interval (float, default 1.0) – Report at least every this many seconds (wall clock).
max_time (float or None, default None) – Wall-clock budget in seconds; the fit stops once it is exceeded.
stop_when (callable or None, default None) –
stop_when(info) -> boolwith the sameinfodict asprogress, checked after every evaluation;Truestops the fit. An exception it raises propagates out ofesfit(), since a stop condition that cannot be evaluated cannot be honored.
Notes
A stop (
max_time,stop_when, aprogresscallable returningFalse) or aKeyboardInterruptreturns the best parameters found so far, withFitResult.success=FalseandFitResult.interrupted=True; no uncertainties are computed for it.method='trf'minimizes the same target-transformed residual vector whose RMSD the other methods minimize, so the parameter mapping (array or dictp0, fixed parameters, bounds),autoscale,baseline,target, progress reporting and stopping apply unchanged. Its budgetmax_iteris SciPy’smax_nfev, the number of step evaluations; the finite-difference Jacobian probes (about one per active parameter per iteration) do not count against it, but they are counted inFitResult.n_evaluationsand drive the progress and stop checks. An exhausted budget returnssuccess=False(SciPy’s message “The maximum number of function evaluations is exceeded.”) withinterrupted=False.FitResult.n_iterationsis SciPy’s Jacobian-evaluation count (one per trust-region iteration).Examples
>>> from torchspin import FitOptions >>> opt = FitOptions(method='levmar', baseline=0) >>> opt.target, opt.max_iter ('fcn', 2000)
- class torchspin.FitResult(pfit, pnames, p_start, p_fixed, fit, fit_raw, residuals, scale, baseline, rmsd, ssr, n_params, n_data, algorithm, n_iterations, success, message, pstd=None, ci95=None, cov=None, corr=None, r_squared=None, reduced_chi_square=None, noise_std=None, n_evaluations=None, elapsed_s=None, interrupted=False, n_failed_evals=0)[source]#
Result of
esfit().“Active” parameters are those that were varied (
lb < ub); parameters fixed withvary = 0orlb == ubare not part ofpfit. All arrays are NumPy arrays on the CPU, in data units unless stated otherwise.- Parameters:
pfit (ndarray, shape (n_active,)) – Best-fit values of the active parameters, in the order of
pnames.pnames (list of str, length n_active) – Names of the active parameters:
'p0','p1', … (index into the fullp0vector) for array-style fits,'Sys.lw[1]','Sys.g[0,2]','Exp.mwFreq', … for dict-style fits.p_start (ndarray, shape (n_active,)) – Start values of the active parameters.
p_fixed (ndarray of bool, shape (n_total,)) – Fixed-parameter mask over all parameters, fixed ones included (array style: the order of
p0; dict style: the order of the fields invary/lb, arrays flattened in C order). Note that it is longer thanpfitwhen parameters are fixed.fit (ndarray, shape (n_data,)) – Fitted curve as compared with the data:
scale * fit_raw + baseline.fit_raw (ndarray, shape (n_data,)) – Model output at
pfit, flattened, before scaling and baseline.residuals (ndarray, shape (n_data,)) –
fit - data, before theFitOptions.targettransformation.scale (float) – Scale factor applied to
fit_raw(1.0 forautoscale='none').baseline (ndarray, shape (n_data,)) – Fitted polynomial baseline (zeros for
FitOptions.baseline=-1).rmsd (float) – Root-mean-square of the target-transformed residuals at
pfit: the quantity the optimizer minimizes.ssr (float) – Sum of squares of the target-transformed residuals (
n_data * rmsd**2).n_params (int) – Number of active parameters (
n_active).n_data (int) – Number of data points.
algorithm (str) –
FitOptions.methodused.n_iterations (int) – Iterations reported by the optimizer: SciPy’s
nitfor'simplex','lbfgsb'and'powell'; Jacobian evaluations for'trf'; LM iterations, swarm iterations or generations for'levmar','swarm','genetic'; the sum of both phases for'global'; model evaluations for'grid'and'montecarlo'; the tracker’s iteration count for an interrupted fit.success (bool) – SciPy’s convergence flag for
'simplex','lbfgsb','powell'and'trf'; alwaysTruefor the other methods unless the fit was interrupted (thenFalse).message (str) – Optimizer termination message.
pstd (ndarray, shape (n_active,), or None) – Standard deviations of the active parameters from the HC1 sandwich covariance.
nanfor a parameter that has no effect on the residuals at the finite-difference step, and for one that ended on a bound (esfit warns in both cases; the latter is held fixed in the covariance of the others).NonewhenFitOptions.compute_uncertaintiesisFalse, the fit did not succeed, or the covariance could not be computed.ci95 (ndarray, shape (n_active, 2), or None) –
[pfit - 1.96 * pstd, pfit + 1.96 * pstd]per parameter (normal approximation).Noneas forpstd.cov (ndarray, shape (n_active, n_active), or None) – Parameter covariance matrix (
nanrows/columns for parameters without effect or on a bound).Noneas forpstd.corr (ndarray, shape (n_active, n_active), or None) – Correlation matrix derived from
cov.Noneas forpstd.r_squared (float) – Coefficient of determination
1 - SS_res / SS_totof the untransformed residuals,SS_tottaken about the mean of the data (nanfor constant data).reduced_chi_square (float) –
sum(residuals**2) / max(n_data - n_active, 1)of the untransformed residuals: an estimate of the noise variance in data units squared, not a chi-square normalized by a known noise level.noise_std (float) –
sqrt(reduced_chi_square): estimated noise standard deviation in data units.n_evaluations (int or None) – Model evaluations of the optimizer, all methods and phases (the initial evaluation at
p0included; the final evaluation and the uncertainty estimate not).elapsed_s (float or None) – Optimizer wall time in seconds (excludes the initial evaluation at
p0and the uncertainty estimate).interrupted (bool, default False) –
Truewhen the fit was stopped early (KeyboardInterrupt,FitOptions.max_time,stop_whenor aprogresscallable returningFalse);pfitis then the best point found so far.n_failed_evals (int, default 0) – Objective evaluations at which the model raised
ValueError,RuntimeErrororLinAlgError. Each such evaluation is penalized with RMSD = 1e10 so the optimizer moves away; the first failure of a fit is reported with a warning. A nonzero count means part of the parameter space could not be simulated (a bug in the model, or parameter ranges outside its domain).
See also
See also
TorchSpin — EPR Spectral Fitting with esfit, TorchSpin — Real-World Fitting: Bad Initial Conditions and Multi-Parameter Fits,
TorchSpin — Real-Data Example: Rhombic Cu(II) Blue Copper Center and the interactive panel in
TorchSpin — interactive fitting panel (torchspin.fitgui) (torchspin.fitgui).