Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
33fc9c5
Merge remote-tracking branch 'upstream/main' into main
HKaras Dec 5, 2022
a4a5001
Merge branch 'JeschkeLab:main' into main
HKaras Mar 11, 2023
8ae74cf
Merge remote-tracking branch 'upstream/main' into main
HKaras May 22, 2023
bd3f25b
Merge branch 'JeschkeLab:main' into main
HKaras Aug 1, 2023
ff53ac1
Merge branch 'JeschkeLab:main' into main
HKaras Aug 9, 2023
108a62a
Merge branch 'JeschkeLab:main' into main
HKaras Aug 10, 2023
2546b42
Push patch into V1.1 (#467)
HKaras Nov 3, 2023
59a6584
Removes katex and others (#471)
HKaras Apr 14, 2024
e5cb1e2
Dipolarkernal speedup (#473)
HKaras Jun 12, 2024
5668946
Adding support for scipy 1.14 and tests for Python 3.12 (#474)
HKaras Jul 1, 2024
6a0b992
Numpy2 support (#479)
HKaras Jul 2, 2024
19a491f
Regparam grid bug fix (#477)
HKaras Jul 15, 2024
564c9ae
Merge branch 'main' of https://github.com/HKaras/DeerLab
HKaras Jul 31, 2024
523b3aa
Merge branch 'main' of https://github.com/HKaras/DeerLab
HKaras Jul 31, 2024
5ab22db
Merge branch 'JeschkeLab:main' into main
HKaras Apr 13, 2026
e8b5807
Merge branch 'JeschkeLab:main' into main
HKaras May 31, 2026
b641a7e
Adding a benchmark libary
HKaras Dec 3, 2026
7d1ff97
Gitignore update
HKaras Dec 3, 2026
328086b
Replace Memoization with native python implementation
HKaras Dec 3, 2026
f506e71
Evaluate the model once per residual
HKaras Dec 3, 2026
1d703d0
Exact Jacobian for the linear parameters in uncertainty propagation
HKaras Dec 3, 2026
40d8f36
Benchmarks added
HKaras Dec 3, 2026
8408887
Compute the linear degrees of freedom once
HKaras Dec 3, 2026
20d7c31
Fix the formula for the linear degrees of freedom
HKaras Dec 3, 2026
7e3778f
Fix the information criteria and complex-valued statistics in `goodne…
HKaras Dec 3, 2026
55b8d41
Skip the identity product for non-parametric distributions
HKaras Dec 3, 2026
6f6f4c0
Vectorize `link` and `merge`
HKaras Dec 3, 2026
ca1d509
Reuse the fit at the optimal penalty weight
HKaras Dec 3, 2026
eb9913a
Reproducible bootstrap: draw the samples in the calling process, seed…
HKaras Dec 3, 2026
135bb40
Fix the test that decides when to re-optimize α
HKaras Dec 3, 2026
329da75
Add 4pDEER three-pathway benchmark
HKaras Dec 3, 2026
d72f8ce
Fix benchmark compare
HKaras Dec 3, 2026
a3b5d53
benchmark profile analysis
HKaras Dec 3, 2026
fd115c1
Warm-start the bootstrap and profile fits
HKaras Dec 3, 2026
3d49a7f
Merge branch 'main' into SpeedUp
HKaras Dec 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions benchmarks/bench_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from conftest import run_cold, overlap

nsamples = 20 # Bootstrap samples per analysis
nprofile = 10 # Profile grid points per non-linear parameter


def _bootstrap_analysis(d, cores):
Expand All @@ -30,18 +31,19 @@ def test_4pdeer_bootstrap(benchmark, data_4pdeer, cores):

# ======================================================================

@pytest.mark.benchmark(group='bootstrap')
def test_4pdeer_profile_analysis(benchmark, data_4pdeer):
"4-pulse DEER, single pathway, profile likelihood confidence intervals"
"4-pulse DEER, single pathway, profile likelihood confidence intervals of the non-linear parameters"
d = data_4pdeer

def analysis():
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1])
Vmodel = dl.dipolarmodel(d['t'], d['r'], experiment=experiment)
return dl.profile_analysis(Vmodel, d['V'], alpha=0.05)
return dl.profile_analysis(Vmodel, d['V'], samples=nprofile)

results = run_cold(benchmark, analysis, rounds=3)

# results.P is the profile median, which is smoother than a single fit
assert overlap(d['r'], results.P) > 0.85
Pci = results.PUncert.ci(95)
assert (Pci[:, 0] <= results.P + 1e-8).all() and (Pci[:, 1] >= results.P - 1e-8).all()
# Each profile-likelihood 95% confidence interval contains the true value used in the simulation
for parameter, truth in d['truth'].items():
ci = results[parameter].ci(95)
assert ci[0] <= truth <= ci[1], f'{parameter}: true value {truth} outside the 95% CI {ci}'
52 changes: 52 additions & 0 deletions benchmarks/bench_fitting.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
"""
Benchmarks of routine non-parametric fits of two-spin dipolar signals.
"""
import numpy as np
import pytest
import deerlab as dl
from conftest import run_cold, overlap


def phased_dipolarmodel(t, r, experiment):
"""
Complex-valued dipolar model: the non-parametric dipolar model of ``dipolarmodel``
multiplied by exp(-i·phase), with the receiver phase as an extra non-linear parameter.
"""
Vmodel = dl.dipolarmodel(t, r, experiment=experiment)
nonlin = [str(name) for name in Vmodel._parameter_list(order='vector') if not np.any(getattr(Vmodel, name).linear)]

def Vphased(*args):
return Vmodel.nonlinmodel(*args[:-1])*np.exp(-1j*args[-1])

model = dl.Model(Vphased, signature=nonlin + ['phase'])
for name in nonlin:
param = getattr(Vmodel, name)
getattr(model, name).set(lb=param.lb, ub=param.ub, par0=param.par0, unit=param.unit, description=param.description)
model.phase.set(lb=-np.pi/2, ub=np.pi/2, par0=0, unit='rad', description='Receiver phase')
model.addlinear('P', vec=len(r), lb=0, normalization=lambda P: P/np.trapezoid(P, r))
return model


# ======================================================================
@pytest.mark.benchmark(group='fit')
def test_4pdeer_single_pathway(benchmark, data_4pdeer):
Expand Down Expand Up @@ -38,6 +59,37 @@ def analysis():
assert overlap(d['r'], results.P) > 0.9
# ======================================================================

@pytest.mark.benchmark(group='fit')
def test_4pdeer_3pathways(benchmark, data_4pdeer_3pathways):
"4-pulse DEER, three dipolar pathways (pathway 3 refocuses at t=0), Tikhonov regularization"
d = data_4pdeer_3pathways

def analysis():
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1, 2, 3])
Vmodel = dl.dipolarmodel(d['t'], d['r'], experiment=experiment)
return dl.fit(Vmodel, d['V'])

results = run_cold(benchmark, analysis)

assert overlap(d['r'], results.P) > 0.9
# ======================================================================

@pytest.mark.benchmark(group='fit')
def test_4pdeer_complex(benchmark, data_4pdeer_complex):
"4-pulse DEER, single pathway, complex-valued data with the receiver phase fitted, Tikhonov regularization"
d = data_4pdeer_complex

def analysis():
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1])
Vmodel = phased_dipolarmodel(d['t'], d['r'], experiment)
return dl.fit(Vmodel, d['V'])

results = run_cold(benchmark, analysis)

assert overlap(d['r'], results.P) > 0.9
assert abs(results.phase - d['phase']) < 0.05
# ======================================================================

@pytest.mark.benchmark(group='fit')
def test_4pdeer_single_pathway_long(benchmark, data_4pdeer_long):
"4-pulse DEER, single pathway, Tikhonov regularization, long evolution time"
Expand Down
7 changes: 5 additions & 2 deletions benchmarks/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ def run_benchmarks(pytest_args, pythonpath=None):
if pythonpath is not None:
env['PYTHONPATH'] = os.pathsep.join(filter(None, [str(pythonpath), env.get('PYTHONPATH')]))
command = [sys.executable, '-m', 'pytest', str(root/'benchmarks'), f'--benchmark-storage={storage}', *pytest_args]
return subprocess.run(command, cwd=root, env=env).returncode
# `python -m` puts the working directory first on sys.path, ahead of PYTHONPATH: run from the
# checkout being benchmarked, otherwise the base run would import the working tree's deerlab
cwd = pythonpath if pythonpath is not None else root
return subprocess.run(command, cwd=cwd, env=env).returncode


def latest_run():
Expand Down Expand Up @@ -59,7 +62,7 @@ def main():

print('\n=== Benchmarking current working tree\n', flush=True)
sys.exit(run_benchmarks(['--benchmark-save=head', f'--benchmark-compare={latest_run()}',
f'--benchmark-compare-fail=mean:{args.fail}%', *pytest_args]))
f'--benchmark-compare-fail=mean:{args.fail:g}%', *pytest_args]))


if __name__ == '__main__':
Expand Down
36 changes: 34 additions & 2 deletions benchmarks/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,15 @@


def clear_caches():
"Clear DeerLab's memoized kernels, such that each benchmark round starts cold, as a fresh script would"
"""
Clear DeerLab's memoized kernels, such that each benchmark round starts cold, as a fresh script would,
and seed NumPy's global random generator, such that analyses that draw random numbers (e.g. the
bootstrap resampling) are reproducible.
"""
for obj in vars(deerlab.dipolarkernel).values():
if callable(getattr(obj, 'cache_clear', None)):
obj.cache_clear()
np.random.seed(seed)


def run_cold(benchmark, func, rounds=5, warmup_rounds=1):
Expand Down Expand Up @@ -56,9 +61,36 @@ def data_4pdeer():
t = np.linspace(0.1, 3.8, 250) # μs
r = np.linspace(2, 6, 150) # nm
experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1])
V = _simulate(t, r, experiment, mod=0.35, reftime=tau1, conc=30)
truth = dict(mod=0.35, reftime=tau1, conc=30)
V = _simulate(t, r, experiment, **truth)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2, truth=truth)

@pytest.fixture(scope='session')
def data_4pdeer_3pathways():
"4-pulse DEER dataset with three dipolar pathways (refocusing at tau1, tau1+tau2 and 0)"
tau1, tau2 = 0.3, 4.0 # μs
t = np.linspace(0.1, 3.8, 250) # μs
r = np.linspace(2, 6, 150) # nm
experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1, 2, 3])
V = _simulate(t, r, experiment, lam1=0.35, reftime1=tau1, lam2=0.05, reftime2=tau1 + tau2,
lam3=0.05, reftime3=0, conc=30)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2)

@pytest.fixture(scope='session')
def data_4pdeer_complex():
"Single-pathway 4-pulse DEER dataset, complex-valued with a receiver phase offset, as acquired in quadrature"
tau1, tau2 = 0.3, 4.0 # μs
t = np.linspace(0.1, 3.8, 250) # μs
r = np.linspace(2, 6, 150) # nm
phase = np.pi/5 # rad
experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1])
model = dl.dipolarmodel(t, r, experiment=experiment)
V = model(mod=0.35, reftime=tau1, conc=30, P=np.interp(r, r_true, P_true))
V = V/np.max(V)*np.exp(-1j*phase)
# Independent noise on the real and imaginary channels
V = V + dl.whitegaussnoise(t, noiselvl, seed=seed) + 1j*dl.whitegaussnoise(t, noiselvl, seed=seed + 1)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2, phase=phase)

@pytest.fixture(scope='session')
def data_4pdeer_long():
"Single-pathway 4-pulse DEER dataset with a long evolution time"
Expand Down
3 changes: 3 additions & 0 deletions benchmarks/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@ This is implemented using [`pytest-benchmark`](https://pytest-benchmark.readthed
| Group | Benchmark | File |
|---|---|---|
| `fit` | Single pathway 4pDEER | `bench_fitting.py` |
| `fit` | 4pDEER with three pathways (1, 2, 3) | `bench_fitting.py` |
| `fit` | Single pathway 4pDEER, complex-valued data with receiver phase | `bench_fitting.py` |
| `fit` | Single pathway 4pDEER, long trace | `bench_fitting.py` |
| `fit` | Single pathway 4pDEER, long trace, parametric (`dd_gauss2`) | `bench_fitting.py` |
| `fit` | Global fit of two 4pDEER traces | `bench_fitting.py` |
| `fit` | Multiple pathways 5pDEER | `bench_fitting.py` |
| `fit` | Compactness criterion (4pDEER) | `bench_fitting.py` |
| `bootstrap` | Bootstrapped 4pDEER (1 core) | `bench_bootstrap.py` |
| `bootstrap` | Bootstrapped 4pDEER (4 cores) | `bench_bootstrap.py` |
| `bootstrap` | Profile-likelihood analysis of 4pDEER (10 grid points per non-linear parameter) | `bench_bootstrap.py` |

Planned: multivariate (three-spin) 4pDEER.

Expand Down
18 changes: 7 additions & 11 deletions deerlab/bootstrap_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,13 @@ def sample():
shapeout.append(np.shape(out))
evals.append(out[np.newaxis,:])

# Main bootstrap function
def bootsample():
# Get bootstrap sample
Vsample = sample()
# Run the analysis function
out = fcn(Vsample)
return out

# Run bootsample() for all samples in series (cores=1) or in parallel (cores>1)
if verbose : print(f'Bootstrap analysis with {cores} cores:')
out = _ProgressParallel(n_jobs=cores,total=nSamples,use_tqdm=verbose)(delayed(bootsample)() for _ in range(nSamples))
# Draw all bootstrap samples here, in the calling process, such that the result does not
# depend on the number of cores and can be reproduced by seeding np.random
Vsamples = [sample() for _ in range(nSamples)]

# Run the analysis function for all samples in series (cores=1) or in parallel (cores>1)
if verbose : print(f'Bootstrap analysis with {cores} cores:')
out = _ProgressParallel(n_jobs=cores,total=nSamples,use_tqdm=verbose)(delayed(fcn)(Vsample) for Vsample in Vsamples)

# Post-process the outputs
for varargout in out:
Expand Down
36 changes: 25 additions & 11 deletions deerlab/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,10 @@ def ci(self,coverage):

elif self.type=='profile':
# Compute likelihood-profile-based confidence intervals
for n,profile in enumerate(self.profile):
# (profile_analysis stores a single profile as a dict and the fitted value as a scalar)
profiles = self.profile if isinstance(self.profile,list) else [self.profile]
parfit = np.atleast_1d(self.__parfit)
for n,profile in enumerate(profiles):

# Construct interpolator for the profile
profileinterp = interp1d(profile['x'], profile['y'], kind='slinear', fill_value=1e6,bounds_error=False)
Expand All @@ -516,8 +519,8 @@ def getprofile_at(value):
return ci_bound
#-----------------------------------------------------------------
# Get the upper and lower bounds of the confidence interval
confint[n,0] = getCIbound(profile['x'].min(),self.__parfit[n])
confint[n,1] = getCIbound(profile['x'].max(),self.__parfit[n])
confint[n,0] = getCIbound(profile['x'].min(),parfit[n])
confint[n,1] = getCIbound(profile['x'].max(),parfit[n])

# Remove singleton dimensions
confint = np.squeeze(confint)
Expand All @@ -526,7 +529,7 @@ def getprofile_at(value):


#--------------------------------------------------------------------------------
def propagate(self,model,lb=None,ub=None,samples=None):
def propagate(self,model,lb=None,ub=None,samples=None,jacobian=None):
"""
Uncertainty propagation.

Expand All @@ -548,7 +551,11 @@ def propagate(self,model,lb=None,ub=None,samples=None):
Upper bounds of the values returned by ``model``, by default assumed unconstrained.
samples : int, optional
Number of samples to use when propagating a bootstraped uncertainty. If not provided, default value is 1000.

jacobian : ndarray, optional
Jacobian of ``model`` with respect to the parameters at the mean, with shape (number of model outputs, number of parameters).
Complex-valued if ``model`` is complex-valued. Only used for ``'moment'`` uncertainties. If not provided, it is
estimated by finite differences, which costs one evaluation of ``model`` per parameter.

Returns
-------
modeluq : :ref:`UQResult`
Expand Down Expand Up @@ -578,12 +585,19 @@ def propagate(self,model,lb=None,ub=None,samples=None):

if self.type=='moment':

if iscomplex:
model_ = model
model = lambda p: np.concatenate([model_(p).real,model_(p).imag])

# Get jacobian of model to be propagated with respect to parameters
J = Jacobian(model,parfit,self.lb,self.ub)
if jacobian is not None:
J = np.atleast_2d(jacobian)
if iscomplex:
J = np.concatenate([J.real,J.imag])
else:
if iscomplex:
model_ = model
def model(p):
y = model_(p)
return np.concatenate([y.real,y.imag])

# Get jacobian of model to be propagated with respect to parameters
J = Jacobian(model,parfit,self.lb,self.ub)

# Clip at boundaries
modelfit = np.maximum(modelfit,lb)
Expand Down
60 changes: 57 additions & 3 deletions deerlab/dipolarkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import numexpr as ne
import types
import warnings
from memoization import cached
import threading
from collections import OrderedDict
from functools import wraps
# DeerLab dependencies
from deerlab.dipolarbackground import dipolarbackground
from deerlab.utils import sophegrid
Expand Down Expand Up @@ -268,6 +270,7 @@ def dipolarkernel(t, r, *, pathways=None, mod=None, bg=None, method='fresnel', e
# Clear cache of memoized function is requested
if clearcache:
elementarykernel_twospin.cache_clear()
_elementarykernel_twospin_interp.cache_clear()

# If not specified, assume the free-electron g-values
if g is None:
Expand Down Expand Up @@ -435,7 +438,58 @@ def K0_3spin(tdip):

return K
#==============================================================================
@cached(max_size=100)

def _cachekey(arg):
"""
Exact, hashable cache key for an argument. Arrays are keyed by their shape, dtype and raw bytes,
so that two arrays share a key only if they are identical. Lists and tuples are keyed element-wise.
Other objects (numbers, strings, None, callables) are used as they are.
"""
if isinstance(arg, np.ndarray):
return (np.ndarray, arg.shape, arg.dtype.str, arg.tobytes())
if isinstance(arg, (list, tuple)):
return (type(arg), tuple(_cachekey(a) for a in arg))
return arg

def _arraycache(max_size=100):
"""
Least-recently-used cache for functions taking numpy arrays as arguments. Unlike
keying on ``str()`` of the arguments, the keys are exact (see ``_cachekey``).
The decorated function has a ``cache_clear()`` method.
"""
def decorator(func):
cache = OrderedDict()
lock = threading.Lock()

@wraps(func)
def wrapper(*args):
try:
key = _cachekey(args)
hash(key)
except TypeError:
# Unhashable argument: compute without caching
return func(*args)
with lock:
if key in cache:
cache.move_to_end(key)
return cache[key]
value = func(*args)
with lock:
cache[key] = value
if len(cache) > max_size:
cache.popitem(last=False)
return value

def cache_clear():
with lock:
cache.clear()

wrapper.cache_clear = cache_clear
return wrapper
return decorator

#==============================================================================
@_arraycache(max_size=100)
def _elementarykernel_twospin_interp(tinterp,r,method,excbandwidth,gridsize,g,orisel,complex):
"""
Construct interpolator, this way elementarykernel_twospin is executed only once independently of how many pathways there are
Expand All @@ -462,7 +516,7 @@ def _echomodulation(ωr,tdip,cosθ,ωex,complex):
return echomod
#==============================================================================

@cached(max_size=100)
@_arraycache(max_size=100)
def elementarykernel_twospin(tdip,r,method,ωex,gridsize,g,Pθ,complex):
#==============================================================================
"Calculates the elementary two-spin dipolar interaction kernel (cached for speed)"
Expand Down
4 changes: 4 additions & 0 deletions deerlab/dipolarmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,10 @@ def Vtwospin_nonlinear_fcn(*nonlin):
excbandwidth=excbandwidth, orisel=orisel,
g=g, method=kernelmethod, gridsize=gridsize)

# Non-parametric distribution: its non-linear part is the identity matrix
if Pnonparametric:
return Kdipolar

# Compute the non-linear part of the distance distribution
Pnonlin = Pmodel.nonlinmodel(*[r]*Nconstants,*nonlin[Psubset])

Expand Down
Loading
Loading