TorchSpin — interactive fitting panel (torchspin.fitgui)#

An EasySpin-esfit-window-like panel inside JupyterLab: parameter sliders with bounds and “fix” boxes, method and budget controls, Start / Stop / Reset, and a live figure with the data, the current best fit, the residual and the RMSD trace. The fit runs in a background thread, so the kernel stays responsive and Stop returns the best fit so far.

Requirements: pip install "torchspin[gui]" (ipywidgets, matplotlib, ipympl). Use %matplotlib widget for a live canvas; with another backend the figure is refreshed as an image.

%matplotlib widget
import sys
from pathlib import Path
try:
    import torchspin  # noqa: F401
except ImportError:
    _root = Path.cwd()
    while not (_root / 'torchspin').exists() and _root != _root.parent:
        _root = _root.parent
    sys.path.insert(0, str(_root))
import numpy as np, torch
from torchspin import SpinSystem, Experiment, Options, pepper
from torchspin.esfit import FitOptions
from torchspin.fitgui import FitSession, FitPanel
torch.set_num_threads(min(torch.get_num_threads(), 32))

1. Synthetic data (nitroxide powder spectrum plus noise)#

rng = np.random.default_rng(1)
exp = Experiment(mwFreq=9.5, Range=[330, 350], nPoints=1024, Harmonic=1)
GRID = [31, 4]
TRUE = dict(g=[2.0085, 2.0060, 2.0025], Az=92.0, lwpp=0.35)

def simulate(gx, gy, gz, Az, lwpp):
    s = SpinSystem(S=[0.5], g=[gx, gy, gz], Nucs='14N', A=[[18.0, 18.0, Az]], lwpp=[lwpp, 0])
    return pepper(s, exp, Options(Verbosity=0, GridSize=GRID))

B, y_true = simulate(*TRUE['g'], TRUE['Az'], TRUE['lwpp']); B, y_true = B.numpy(), y_true.numpy()
data = y_true + 0.02 * np.abs(y_true).max() * rng.standard_normal(y_true.shape)

names = ['gx', 'gy', 'gz', 'Az', 'lwpp']
p0 = np.array([2.0110, 2.0085, 2.0050, 101.0, 0.50])     # deliberately off
vary = np.array([0.004, 0.004, 0.004, 15.0, 0.25])

def model(p):
    return simulate(*p)[1].numpy()

2. The panel#

Move the sliders to tune the dashed starting simulation, tick fix to hold a parameter, pick a method and press Start. Population methods use n_workers processes (auto = the allocated cores, at most 32 and about 0.5 GB of memory each).

session = FitSession(data, model, p0, vary=vary, names=names,
                     options=FitOptions(method='global', swarm_size=24, max_iter=25, n_workers='auto', seed=7,
                                        compute_uncertainties=False), progress_interval=0.5)
panel = FitPanel(session, x=B, xlabel='B (mT)')
panel.show()

3. Programmatic use#

The same session can be driven from code (this cell is what a non-interactive execution of the notebook runs): start, wait, refresh the panel, read the result.

import time
if not session.running and session.result is None:      # skip if you already pressed Start above
    panel.start(); session.join(); panel.refresh()
r = session.result
print(r.message)
print({n: round(float(v), 4) for n, v in zip(names, session.best_x)}, f'rmsd {r.rmsd:.4g}', f'{r.n_evaluations} evals', f'{r.elapsed_s:.1f} s')
print('truth:', TRUE)
Global: swarm 504 evals -> 2.9647e+02, polish 238 evals -> 2.9408e+02
{'gx': 2.007, 'gy': 2.0073, 'gz': 2.0026, 'Az': 91.574, 'lwpp': 0.4427} rmsd 294.1 743 evals 27.3 s
truth: {'g': [2.0085, 2.006, 2.0025], 'Az': 92.0, 'lwpp': 0.35}

Notes#

  • Stop sets a flag that esfit checks at the next evaluation (or the next chunk of a worker pool); the result is then the best fit so far with interrupted=True.

  • A kernel interrupt does not reach the background thread: use the Stop button.

  • Fixed parameters keep their slider value; session.best_x is always the full parameter vector.

  • panel.result is the FitResult; panel.p_current are the slider values (e.g. after hand tuning).