diff --git a/.gitignore b/.gitignore index e06f9135..dea12637 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,7 @@ examples/**/*.hdf5 examples/**/*.npy examples/**/*.npz examples/**/*.csv + +# Benchmark results (machine specific) +.benchmarks/ +sg_execution_times.rst \ No newline at end of file diff --git a/benchmarks/bench_bootstrap.py b/benchmarks/bench_bootstrap.py new file mode 100644 index 00000000..17c597ea --- /dev/null +++ b/benchmarks/bench_bootstrap.py @@ -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() \ No newline at end of file diff --git a/benchmarks/bench_fitting.py b/benchmarks/bench_fitting.py new file mode 100644 index 00000000..b2ef2d34 --- /dev/null +++ b/benchmarks/bench_fitting.py @@ -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 +# ====================================================================== diff --git a/benchmarks/compare.py b/benchmarks/compare.py new file mode 100644 index 00000000..66aa7978 --- /dev/null +++ b/benchmarks/compare.py @@ -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() diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py new file mode 100644 index 00000000..c41bd917 --- /dev/null +++ b/benchmarks/conftest.py @@ -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) \ No newline at end of file diff --git a/benchmarks/pytest.ini b/benchmarks/pytest.ini new file mode 100644 index 00000000..5e349eef --- /dev/null +++ b/benchmarks/pytest.ini @@ -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 diff --git a/benchmarks/readme.md b/benchmarks/readme.md new file mode 100644 index 00000000..7c3750dc --- /dev/null +++ b/benchmarks/readme.md @@ -0,0 +1,83 @@ +# DeerLab Benchmarking Suite + +This folder contains a collection of benchmark problems for DeerLab. The purpose of these benchmarks is to see how changes to DeerLab affect the performance. This suite should be run for each pull request on both the main branch and the pull request branch, and the results should be compared to see if there are any performance regressions. + +This is implemented using [`pytest-benchmark`](https://pytest-benchmark.readthedocs.io). + +## Benchmarks + +| Group | Benchmark | File | +|---|---|---| +| `fit` | Single pathway 4pDEER | `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` | + +Planned: multivariate (three-spin) 4pDEER. + +Design choices: + +- **Simulated data with a fixed noise seed** (see `conftest.py`), so every run and every branch analyzes identical data. +- **Each benchmark times a complete analysis** as a user would write it: building the experiment and model, then fitting. +- **Cold caches.** DeerLab memoizes dipolar kernels. The caches are cleared before every round, so each round costs the same as a fresh script. +- **Results are checked.** After timing, each benchmark asserts that the fitted distribution still overlaps the ground truth. A change that makes a fit faster by breaking it fails the benchmark instead of looking like a speed-up. + +The full suite takes about 2 minutes. + +## Example Usage + +Install the requirements: + +```bash +pip install -r benchmarks/requirements.txt +``` + +Run the benchmark set from the repository root: + +```bash +pytest benchmarks +``` + +Run a subset, e.g. only the fitting benchmarks: + +```bash +pytest benchmarks -k fit +``` + +### Comparing against main + +`compare.py` benchmarks another git revision (default `main`) and then the current working tree, and prints both side by side. The base revision is checked out into a temporary git worktree, so you do not need to switch branches. Both runs use the benchmark code of the current working tree. It exits with an error if any mean time regresses by more than 10%. + +```bash +python benchmarks/compare.py # compare against main +python benchmarks/compare.py v1.1.0 # any branch, tag or commit +python benchmarks/compare.py main --fail 5 # stricter regression threshold (%) +python benchmarks/compare.py main -- -k 4pdeer # extra pytest arguments after -- +``` + +This requires DeerLab to be installed in editable mode (`pip install -e .`). + +### Manual comparison + +Results are saved in `.benchmarks/` (git-ignored) at the repository root. + +```bash +pytest benchmarks --benchmark-save=main # on the main branch +pytest benchmarks --benchmark-compare # on the PR branch: compare with the latest saved run +pytest-benchmark compare # list and compare saved runs +``` + +Timings depend on the machine, so only compare runs made on the same machine. + +## Adding a benchmark + +Add a `test_*` function to a `bench_*.py` file. Benchmark files are named `bench_*.py` so that the regular test suite does not collect them. Then: + +1. Use or add a dataset fixture in `conftest.py`. +2. Wrap the analysis in a function and time it with `run_cold(benchmark, analysis)`. +3. Assert on the result after timing it. +4. Assign a group with `@pytest.mark.benchmark(group=...)`. diff --git a/benchmarks/requirements.txt b/benchmarks/requirements.txt new file mode 100644 index 00000000..8e371063 --- /dev/null +++ b/benchmarks/requirements.txt @@ -0,0 +1 @@ +pytest-benchmark>=5.0