Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,7 @@ examples/**/*.hdf5
examples/**/*.npy
examples/**/*.npz
examples/**/*.csv

# Benchmark results (machine specific)
.benchmarks/
sg_execution_times.rst
47 changes: 47 additions & 0 deletions benchmarks/bench_bootstrap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Benchmarks of bootstrapped uncertainty quantification of two-spin dipolar signals.
"""
import pytest
import deerlab as dl
from conftest import run_cold, overlap

nsamples = 20 # Bootstrap samples per analysis


def _bootstrap_analysis(d, cores):
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1])
Vmodel = dl.dipolarmodel(d['t'], d['r'], experiment=experiment)
return dl.fit(Vmodel, d['V'], bootstrap=nsamples, bootcores=cores)


# ======================================================================
@pytest.mark.benchmark(group='bootstrap')
@pytest.mark.parametrize('cores', [1, 4], ids=['1core', '4cores'])
def test_4pdeer_bootstrap(benchmark, data_4pdeer, cores):
"4-pulse DEER, single pathway, bootstrapped confidence intervals"
d = data_4pdeer

results = run_cold(benchmark, lambda: _bootstrap_analysis(d, cores), rounds=3)

# results.P is the bootstrap 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()

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

def test_4pdeer_profile_analysis(benchmark, data_4pdeer):
"4-pulse DEER, single pathway, profile likelihood confidence intervals"
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)

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()
121 changes: 121 additions & 0 deletions benchmarks/bench_fitting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
Benchmarks of routine non-parametric fits of two-spin dipolar signals.
"""
import pytest
import deerlab as dl
from conftest import run_cold, overlap


# ======================================================================
@pytest.mark.benchmark(group='fit')
def test_4pdeer_single_pathway(benchmark, data_4pdeer):
"4-pulse DEER, single pathway, Tikhonov regularization"
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.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_single_pathway_qp(benchmark, data_4pdeer):
"4-pulse DEER, single pathway, Tikhonov regularization with quadprog as non-negative least-squares solver"
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.fit(Vmodel, d['V'],nnlsSolver='qp')

results = run_cold(benchmark, analysis)

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

@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"
d = data_4pdeer_long

def analysis():
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1])
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_single_pathway_long_parametric(benchmark, data_4pdeer_long):
"4-pulse DEER, single pathway, parametric two-Gaussian distribution, long evolution time"
d = data_4pdeer_long

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

results = run_cold(benchmark, analysis)

# A parametric fit has no results.P: evaluate the fitted distribution model instead
assert overlap(d['r'], results.evaluate(dl.dd_gauss2, d['r'])) > 0.9
# ======================================================================

@pytest.mark.benchmark(group='fit')
def test_4pdeer_global(benchmark, data_4pdeer, data_4pdeer_long):
"4-pulse DEER, single pathway, Tikhonov regularization, global fit of two datasets"
d1 = data_4pdeer
d2 = data_4pdeer_long

def analysis():
experiment1 = dl.ex_4pdeer(d1['tau1'], d1['tau2'], pathways=[1])
Vmodel1 = dl.dipolarmodel(d1['t'], d1['r'], experiment=experiment1)
experiment2 = dl.ex_4pdeer(d2['tau1'], d2['tau2'], pathways=[1])
Vmodel2 = dl.dipolarmodel(d2['t'], d2['r'], experiment=experiment2)
GlobalModel = dl.merge(Vmodel1, Vmodel2)
GlobalModel = dl.link(GlobalModel, conc=['conc_1', 'conc_2'], P=['P_1', 'P_2'])
return dl.fit(GlobalModel, [d1['V'], d2['V']])

results = run_cold(benchmark, analysis)

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

@pytest.mark.benchmark(group='fit')
def test_5pdeer_multiple_pathways(benchmark, data_5pdeer):
"Reverse 5-pulse DEER, two dipolar pathways, Tikhonov regularization"
d = data_5pdeer

def analysis():
experiment = dl.ex_rev5pdeer(d['tau1'], d['tau2'], d['tau3'], pathways=[1, 5])
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_compactness(benchmark, data_4pdeer):
"4-pulse DEER, single pathway, Tikhonov regularization with a compactness penalty"
d = data_4pdeer

def analysis():
experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1])
Vmodel = dl.dipolarmodel(d['t'], d['r'], experiment=experiment)
compactness = dl.dipolarpenalty(Pmodel=None, r=d['r'], type='compactness')
return dl.fit(Vmodel, d['V'], penalties=compactness)

results = run_cold(benchmark, analysis)

assert overlap(d['r'], results.P) > 0.9
# ======================================================================
66 changes: 66 additions & 0 deletions benchmarks/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""
Compare the performance of the current working tree against another git revision.

The base revision is checked out into a temporary git worktree and benchmarked by
putting it first on PYTHONPATH. Both runs use the benchmark code of the current
working tree, such that the exact same analyses are timed.

Usage (from anywhere in the repository):

python benchmarks/compare.py # compare against main
python benchmarks/compare.py v1.1.0 # compare against any branch, tag or commit
python benchmarks/compare.py main --fail 5 # fail if any mean time regresses by more than 5%
python benchmarks/compare.py main -- -k 4pdeer # pass extra arguments on to pytest
"""
import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path

root = Path(subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], text=True).strip())
storage = root/'.benchmarks'


def run_benchmarks(pytest_args, pythonpath=None):
env = dict(os.environ)
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


def latest_run():
"Run number of the most recently saved benchmark run"
runs = sorted(storage.glob('*/[0-9][0-9][0-9][0-9]_*.json'), key=os.path.getmtime)
return runs[-1].name.split('_')[0]


def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('base', nargs='?', default='main', help='git revision to compare against (default: main)')
parser.add_argument('--fail', type=float, default=10, metavar='PERCENT',
help='exit with an error if any mean time regresses by more than PERCENT (default: 10)')
parser.add_argument('pytest_args', nargs=argparse.REMAINDER, help='extra arguments for pytest, after --')
args = parser.parse_args()
pytest_args = [arg for arg in args.pytest_args if arg != '--']
label = args.base.replace('/', '-')

with tempfile.TemporaryDirectory() as tmp:
worktree = Path(tmp)/'base'
subprocess.run(['git', 'worktree', 'add', '--detach', '--quiet', str(worktree), args.base], cwd=root, check=True)
try:
print(f'\n=== Benchmarking base revision: {args.base}\n', flush=True)
if run_benchmarks([f'--benchmark-save=base-{label}', *pytest_args], pythonpath=worktree) != 0:
sys.exit(f'Benchmarks failed on the base revision {args.base}')
finally:
subprocess.run(['git', 'worktree', 'remove', '--force', str(worktree)], cwd=root, check=True)

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]))


if __name__ == '__main__':
main()
90 changes: 90 additions & 0 deletions benchmarks/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""
Shared fixtures for the DeerLab benchmark suite.

All datasets are simulated with a fixed noise seed, such that every run
(and every branch being compared) analyzes exactly the same data.
"""
import numpy as np
import pytest
import deerlab as dl
import deerlab.dipolarkernel
from deerlab.utils import ovl

# Ground-truth bimodal distance distribution shared by all benchmarks
r_true = np.linspace(1.5, 6.5, 300) # nm
P_true = dl.dd_gauss2(r_true, mean1=3.2, std1=0.25, mean2=4.2, std2=0.35, amp1=0.6, amp2=0.4)

# Low enough that the two Gaussians 1 nm apart are resolvable at mod≈0.35; at 0.05
# Tikhonov blurs them together and no fit reaches the overlap thresholds below.
noiselvl = 0.02
seed = 1


def clear_caches():
"Clear DeerLab's memoized kernels, such that each benchmark round starts cold, as a fresh script would"
for obj in vars(deerlab.dipolarkernel).values():
if callable(getattr(obj, 'cache_clear', None)):
obj.cache_clear()


def run_cold(benchmark, func, rounds=5, warmup_rounds=1):
"""
Benchmark ``func`` with the kernel caches cleared before every round.
Returns the output of the last round.
"""
return benchmark.pedantic(func, setup=clear_caches, rounds=rounds, iterations=1, warmup_rounds=warmup_rounds)


def overlap(r, P):
"Overlap index between a fitted distribution and the ground truth"
return ovl(P/np.trapezoid(P, r), np.interp(r, r_true, P_true))


def _simulate(t, r, experiment, spins=2,**params):
"Simulate a noisy signal with the non-parametric dipolar model of the given experiment"
model = dl.dipolarmodel(t, r,spins=spins, experiment=experiment)
P = np.interp(r, r_true, P_true)
V = model(**params, P=P)
V = V/np.max(V)
return V + dl.whitegaussnoise(t, noiselvl, seed=seed)


@pytest.fixture(scope='session')
def data_4pdeer():
"Single-pathway 4-pulse DEER dataset"
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])
V = _simulate(t, r, experiment, mod=0.35, reftime=tau1, conc=30)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2)

@pytest.fixture(scope='session')
def data_4pdeer_long():
"Single-pathway 4-pulse DEER dataset with a long evolution time"
tau1, tau2 = 0.3, 6.0 # μs
t = np.arange(0.1, 5.8, step=0.012) # μ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)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2)

@pytest.fixture(scope='session')
def data_5pdeer():
"Reverse 5-pulse DEER dataset with the main pathway and the 4pDEER-like pathway at t=tau2"
tau1, tau2, tau3 = 3.9, 3.7, 0.3 # μs
t = np.linspace(0.3, 6.5, 500) # μs
r = np.linspace(2, 6, 150) # nm
experiment = dl.ex_rev5pdeer(tau1, tau2, tau3, pathways=[1, 5])
V = _simulate(t, r, experiment, lam1=0.4, reftime1=tau3, lam5=0.08, reftime5=tau2, conc=80)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2, tau3=tau3)

@pytest.fixture(scope='session')
def data_4pdeer_3spin():
"Single-pathway 4-pulse DEER dataset for a 3-spin system"
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])
V = _simulate(t, r, experiment, mod=0.35, reftime=tau1, conc=30,spins=3)
return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2)
4 changes: 4 additions & 0 deletions benchmarks/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[pytest]
# Benchmarks are named bench_*.py such that the regular test suite never collects them
python_files = bench_*.py
addopts = --benchmark-only --benchmark-sort=name --benchmark-columns=min,mean,median,stddev,rounds --disable-warnings
Loading
Loading