From 2546b4290fe4530575462fb343182e29bba069a3 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Fri, 3 Nov 2023 12:20:13 +0100 Subject: [PATCH 01/24] Push patch into V1.1 (#467) * Increase version number and update changelog (#455) * Bugfixes 4th sep (#460) * Fix normalisation in rice model Closes #459 * Remove three spin anaysis Closes #427 * Improved installation instructions * Caution about difference in definition of cost function Closes #450 * Bump Version * Bug for non linearly constrained problems When a problem is not linearly constrained and not non-negative, the linear solver outputs a result class not the solution. * Keeping changelog up-to date * Fixing Sophgrid bug (#464) * Fixing Sophgrid bug * Add unit test for sophgrid * Update changelog.rst for new release (#466) --- VERSION | 2 +- deerlab/dd_models.py | 2 +- deerlab/solvers.py | 8 +- deerlab/utils.py | 8 +- docsrc/source/changelog.rst | 12 +++ docsrc/source/installation.rst | 23 +++-- .../advanced/ex_long_threespin_analysis.py | 95 ------------------- test/test_utils.py | 16 ++++ 8 files changed, 55 insertions(+), 111 deletions(-) delete mode 100644 examples/advanced/ex_long_threespin_analysis.py create mode 100644 test/test_utils.py diff --git a/VERSION b/VERSION index 795460fce..0f1acbd56 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v1.1.0 +v1.1.2 diff --git a/deerlab/dd_models.py b/deerlab/dd_models.py index afcd381d9..dc32cbaab 100644 --- a/deerlab/dd_models.py +++ b/deerlab/dd_models.py @@ -125,7 +125,7 @@ def _multirice3dfun(r,nu,sig): r = r.T s2 = sig**2 I_scaled = spc.ive(n/2-1, nu*r/s2) - P = nu**(n/2-1)/s2*r**(n/2)*np.exp(-(r**2+nu**2)/(2*s2)+nu*r/s2)*I_scaled + P = nu**(1-n/2)/s2*r**(n/2)*np.exp(-(r**2+nu**2)/(2*s2)+nu*r/s2)*I_scaled P[P<0] = 0 # Normalization diff --git a/deerlab/solvers.py b/deerlab/solvers.py index 8c1c6a298..1052d7b39 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -426,6 +426,11 @@ def snlls(y, Amodel, par0=None, lb=None, ub=None, lbl=None, ubl=None, nnlsSolver * ``0`` : Work silently (default). * ``1`` : Display progress including the non-linear least-squares' solver termination report. * ``2`` : Display progress including the non-linear least-squares' solver iteration details. + + .. caution:: + + The verbose output from the non-linear least-squares solver uses a different definition of the cost function than DeerLab. + DeerLab uses the sum of squares of the residuals divided by the number of data points, whereas the non-linear least-squares solver uses the sum of squares of the residuals divided by 2. Returns ------- @@ -594,7 +599,8 @@ def linear_problem(y,A,optimize_alpha,alpha): if optimize_alpha: - output = dl.selregparam((y-yfrozen)[mask], Ared[mask,:], linSolver, regparam, + linsolver_result = lambda AtA, Aty: parseResult(linSolver(AtA, Aty)) + output = dl.selregparam((y-yfrozen)[mask], Ared[mask,:], linsolver_result, regparam, weights=weights[mask], regop=L, candidates=regparamrange, noiselvl=noiselvl,searchrange=regparamrange,full_output=True) alpha = output[0] diff --git a/deerlab/utils.py b/deerlab/utils.py index 5079bd5b6..3b7f69d13 100644 --- a/deerlab/utils.py +++ b/deerlab/utils.py @@ -833,7 +833,7 @@ def sophegrid(octants,maxphi,size): weights = np.zeros(nOrientations) sindth2 = np.sin(dtheta/2) - w1 = 0.5 + w1 = 1.0 # North pole (z orientation) phi[0] = 0 @@ -841,7 +841,7 @@ def sophegrid(octants,maxphi,size): weights[0] = maxphi*(1 - np.cos(dtheta/2)) # All but equatorial slice - Start = 2 + Start = 1 for iSlice in np.arange(2,size): nPhi = nOct*(iSlice-1) + 1 dPhi = maxphi/(nPhi - 1) @@ -854,13 +854,13 @@ def sophegrid(octants,maxphi,size): # Equatorial slice nPhi = nOct*(size - 1) + 1 dPhi = maxphi/(nPhi - 1) - idx = Start + (np.arange(0,nPhi) - 1) + idx = Start + np.arange(0,nPhi) phi[idx] = np.linspace(0,maxphi,nPhi) theta[idx] = np.pi/2 weights[idx] = sindth2*dPhi*np.concatenate([[w1], np.ones(nPhi-2), [0.5]]) # Border removal - rmv = np.cumsum(nOct*np.arange(1,size-1)+1)+1 + rmv = np.cumsum(nOct*np.arange(1,size)+1) phi = np.delete(phi,rmv) theta = np.delete(theta,rmv) weights = np.delete(weights,rmv) diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index 9da8425ee..894c269fb 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -24,6 +24,18 @@ Release Notes - |fix| : Something which was not working as expected or leading to errors has been fixed. - |api| : This will require changes in your scripts or code. +Release ``v1.1.2`` - November 2023 +------------------------------------------ +- |fix| : Fixes an issue with sophgrid (:pr:`463`). +- |fix| : Fixes an error in the normalisation of the rice models (:pr:`459`). +- |fix| : Removes the broken three spin example (:pr:`427`). +- |fix| : Fixes an error in the linear solver for linearly constrained not non-negative problems. + +Release ``v1.1.1`` - August 2023 +------------------------------------------ +- |fix| : Fixes an error in the `FitResult.evaluate` function. (:pr:`454`) + + Release ``v1.1.0`` - August 2023 ------------------------------------------ - |api| : The definition of the dipolar time axis for RIDME has changed to match the one for 4-pulse DEER (:pr:`436`). diff --git a/docsrc/source/installation.rst b/docsrc/source/installation.rst index dd974a469..95257bc3f 100644 --- a/docsrc/source/installation.rst +++ b/docsrc/source/installation.rst @@ -45,7 +45,7 @@ DeerLab installs the following packages: * `joblib `_ - Library lightweight pipelining and parallelization. * `tqdm `_ - A lightweight package for smart progress meters. * `dill `_ - An extension of Python's pickle module for serializing and de-serializing python objects. -* `quadprog `_ - A quadratic programming solver +* `quadprog `_ - A quadratic programming solver (Only for Python versions < 3.11) Importing DeerLab ------------------ @@ -74,9 +74,6 @@ Any DeerLab version released after v0.10.0 can be installed via ``pip`` using th python -m pip install deerlab==x.y.z -DeerLab version prior to 0.10 are written in MATLAB and are still available from an `archived repository `_. -Download and installation instruction for the MATLAB environment are provided in the released documentation. MATLAB releases have been deprecated and no further support is provided. - Installing from source ***************************** @@ -130,10 +127,18 @@ On a **Windows** computer, if you are trying to run a DeerLab function, you migh ImportError: DLL load failed: The specified module could not be found. -This happens when the MKL libraries have not been properly linked in ``numpy``, ``scipy`` or ``cvxopt`` -installations (typically ``numpy``). This can happen due to firewall restrictions, -user rights, or internet connection issues during the DeerLab installation. To solve this, the -best solution is to manually install as follows. +This issue can occur when a specific python package is not installled properly. This typicaly happens when installing the MKL linked libaries but can +occur when installing packages normaly from PyPI. This can happen due to firewall restrictions, +user rights, or internet connection issues during the DeerLab installation. + +If your where installing packages from PyPI (i.e. via pip) then please uninstall the package and reinstall it. + +.. code-block:: text + + python -m pip uninstall + python -m pip install + +If you were trying to install the MKL linked libraries then please follow the instructions below. 1) Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy @@ -167,7 +172,7 @@ During installation on certain systems (e.g. some computation clusters) using on the following error might be raised during the installation: .. code-block:: text - + Error while finding module specification for 'setup.py' (ModuleNotFoundError: __path__ attribute not found on 'setup' while trying to find 'setup.py') diff --git a/examples/advanced/ex_long_threespin_analysis.py b/examples/advanced/ex_long_threespin_analysis.py deleted file mode 100644 index cdbde8261..000000000 --- a/examples/advanced/ex_long_threespin_analysis.py +++ /dev/null @@ -1,95 +0,0 @@ -#%% -""" -Analyzing 4-pulse DEER data acquired on three-spin systems -============================================================================ - -As in the publication referenced below, this example will take two 4-pulse DEER signals acquired -on the same protein sample conatining three nitroxide spins with different attenuation levels of the pump -pulse power. - -For the original model and more information on these systems please refer to: -L. Fábregas Ibáñez, M. H. Tessmer, G. Jeschke, and S. Stoll. -Dipolar pathways in multi-spin and multi-dimensional dipolar EPR spectroscopy -Phys. Chem. Chem. Phys., 24 2022, 22645-22660 -""" -#%% -import numpy as np -import deerlab as dl - -# Load experimental data -files = [f'../data/triradical_protein_deer_{dB}dB.DTA' for dB in [0,6,9]] - -# Experiment information -t0 = 0.280 # Start time, μs -tau1 = 0.40 # First interpulse delay, μs -tau2 = 9.00 # Second interpulse delay, μs - -# Construct 4-pulse DEER experiment model -my4pdeer = dl.ex_4pdeer(tau1,tau2,pathways=[1]) - -# Loop over the different datasets -Vmodels,Vexps,ts,Vexps_sub,ts_sub = [],[],[],[],[] -for n,file in enumerate(files): - # Load the dataset - t,Vexp, descriptor = dl.deerload(file,full_output=True) - t = t[:-80] - Vexp = Vexp[:-80] - # Adjust the Start time - t = t - t[0] + t0 - - # Pre-processing - Vexp = dl.correctphase(Vexp) - Vexp /= np.max(Vexp) - - # Store the pre-processed datasets in a list - Vexps.append(Vexp) - ts.append(t) - - # Subsampling - # (required for efficient analysis in densely sampled datasets) - sampling = np.arange(0,len(t),4) # Take every 4th point - t_sub = t[sampling] - Vexp_sub = Vexp[sampling] - - # Store the subsampled datasets in a list - Vexps_sub.append(Vexp_sub) - ts_sub.append(t_sub) - - # Construct the three-spin dipolar model - Vmodel = dl.dipolarmodel(t_sub,spins=3,experiment=my4pdeer, minamp=0.01) - - # Add dipolar model to list of models - Vmodels.append(Vmodel) - -# Construct a global dipolar model describing all datasets -Vglobal = dl.merge(*Vmodels) -Vglobal = dl.link(Vglobal, - rmean1=[f'rmean1_{n+1}' for n in range(len(Vmodels))], - rmean2=[f'rmean2_{n+1}' for n in range(len(Vmodels))], - rmean3=[f'rmean3_{n+1}' for n in range(len(Vmodels))], - chol11=[f'chol11_{n+1}' for n in range(len(Vmodels))], - chol22=[f'chol22_{n+1}' for n in range(len(Vmodels))], - chol33=[f'chol33_{n+1}' for n in range(len(Vmodels))], - chol21=[f'chol21_{n+1}' for n in range(len(Vmodels))], - chol31=[f'chol31_{n+1}' for n in range(len(Vmodels))], - chol32=[f'chol32_{n+1}' for n in range(len(Vmodels))], - conc=[f'conc_{n+1}' for n in range(len(Vmodels))], - reftime1=[f'reftime1_{n+1}' for n in range(len(Vmodels))], -) -# Freeze the Cholesky-factors accounting for the correlation coefficients -# to zero (not always applicable) -Vglobal.chol21.freeze(0) -Vglobal.chol31.freeze(0) -Vglobal.chol32.freeze(0) - -# Fit the model to the data -results = dl.fit(Vglobal, Vexps_sub, reg=False, ftol=1e-5) - -# %% -# Plot the fitted datasets -results.plot(axis=ts_sub,xlabel='time (μs)') - -# Print the fit summary -print(results) - -# %% diff --git a/test/test_utils.py b/test/test_utils.py new file mode 100644 index 000000000..2df9a899f --- /dev/null +++ b/test/test_utils.py @@ -0,0 +1,16 @@ +import numpy as np +from deerlab import sophegrid + + +# ====================================================================== +# Test sophegrid function + +def test_sophegrid(): + # Test that the function returns the values and weights summing to 1 + # Comparison taken from EasySpin 6.0 + phi, theta, weights = sophegrid(4,np.pi*2,3) + + assert np.allclose(weights.sum(),1) + assert np.allclose(phi, np.array([0,0,1.57079632679490,3.14159265358979,4.71238898038469,0,0.785398163397448,1.57079632679490,2.35619449019235,3.14159265358979,3.92699081698724,4.71238898038469,5.49778714378214])) + assert np.allclose(theta, np.array([0,0.785398163397448,0.785398163397448,0.785398163397448,0.785398163397448,1.57079632679490,1.57079632679490,1.57079632679490,1.57079632679490,1.57079632679490,1.57079632679490,1.57079632679490,1.57079632679490])) + assert np.allclose(weights*4*np.pi, np.array([0.956558005801449,1.70021769237074,1.70021769237074,1.70021769237074,1.70021769237074,0.601117729884346,0.601117729884346,0.601117729884346,0.601117729884346,0.601117729884346,0.601117729884346,0.601117729884346,0.601117729884346])) \ No newline at end of file From 59a6584c8345084fb4ffda00a619ab3917f97ac0 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Sun, 14 Apr 2024 02:15:34 +0100 Subject: [PATCH 02/24] Removes katex and others (#471) * Fixing Sophgrid bug * Add unit test for sophgrid * Minor doc update * Bump version Number * Remove unnecessary doc files * Update changelog --- VERSION | 2 +- deerlab/fitresult.py | 2 ++ deerlab/solvers.py | 1 + deerlab/utils.py | 1 + docsrc/package-lock.json | 19 ------------------- docsrc/source/changelog.rst | 4 ++++ 6 files changed, 9 insertions(+), 20 deletions(-) delete mode 100644 docsrc/package-lock.json diff --git a/VERSION b/VERSION index 0f1acbd56..99a4aef0c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v1.1.2 +v1.1.3 diff --git a/deerlab/fitresult.py b/deerlab/fitresult.py index 80c99bcc5..4841f9e67 100644 --- a/deerlab/fitresult.py +++ b/deerlab/fitresult.py @@ -42,6 +42,8 @@ class FitResult(dict): * ``stats['aic']`` - Akaike information criterion * ``stats['aicc']`` - Corrected Akaike information criterion * ``stats['bic']`` - Bayesian information criterion + * ``stats['autocorr']`` - Autocorrelation based on Durbin–Watson statistic + nonlin : ndarray Fitted non-linear parameters. [:ref:`snlls` specific attribute] diff --git a/deerlab/solvers.py b/deerlab/solvers.py index 1052d7b39..523afbe15 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -462,6 +462,7 @@ def snlls(y, Amodel, par0=None, lb=None, ub=None, lbl=None, ubl=None, nnlsSolver * ``stats['aic']`` - Akaike information criterion * ``stats['aicc']`` - Corrected Akaike information criterion * ``stats['bic']`` - Bayesian information criterion + * ``stats['autocorr']`` - Autocorrelation based on Durbin–Watson statistic success : bool Whether or not the optimizer exited successfully. cost : float diff --git a/deerlab/utils.py b/deerlab/utils.py index 3b7f69d13..eb06134dd 100644 --- a/deerlab/utils.py +++ b/deerlab/utils.py @@ -282,6 +282,7 @@ def goodness_of_fit(x,xfit,Ndof,noiselvl): stats['aic'] - Akaike information criterion stats['aicc'] - Corrected Akaike information criterion stats['bic'] - Bayesian information criterion + stats['autocorr'] - Autocorrelation based on Durbin–Watson statistic """ sigma = noiselvl Ndof = np.maximum(Ndof,1) diff --git a/docsrc/package-lock.json b/docsrc/package-lock.json deleted file mode 100644 index 02c9db5b6..000000000 --- a/docsrc/package-lock.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "requires": true, - "lockfileVersion": 1, - "dependencies": { - "commander": { - "version": "2.20.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", - "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" - }, - "katex": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/katex/-/katex-0.11.0.tgz", - "integrity": "sha512-RQsU3HSMjLW9AdPpi2zaBwM123goCbUcUbBJfmjcAdA982RgtEUNMmrf+3y8anGjgJLantcNLa/VSK73xztQBg==", - "requires": { - "commander": "^2.19.0" - } - } - } -} diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index 894c269fb..252ef0fcf 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -24,6 +24,10 @@ Release Notes - |fix| : Something which was not working as expected or leading to errors has been fixed. - |api| : This will require changes in your scripts or code. +Release ``v1.1.3`` - Ongoing +------------------------------------------ +- |fix| : Removes unnecessary files from the docs + Release ``v1.1.2`` - November 2023 ------------------------------------------ - |fix| : Fixes an issue with sophgrid (:pr:`463`). From e5cb1e2a3eb64e7be2d255f78c507cb4261f70cb Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Wed, 12 Jun 2024 19:31:44 +0200 Subject: [PATCH 03/24] Dipolarkernal speedup (#473) * Seperate Kinterpolator into its own function Interpolation in Scipy is very slow, currently the same interpolation is being rerun for every calculation of the dipolarkernal. This is now cached to speed it up. * Only run orientation selection on grid and integral based kernals This hunk of code is not needed when fresnel integrals are used so does not need to be evaluated * Update changelog --- deerlab/dipolarkernel.py | 29 ++++++++++++++++++----------- docsrc/source/changelog.rst | 1 + 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/deerlab/dipolarkernel.py b/deerlab/dipolarkernel.py index 33d815f1b..8ee3d3873 100644 --- a/deerlab/dipolarkernel.py +++ b/deerlab/dipolarkernel.py @@ -367,7 +367,7 @@ def dipolarkernel(t, r, *, pathways=None, mod=None, bg=None, method='fresnel', e if tinterp is not None: # Construct interpolator, this way elementarykernel_twospin is executed only once independently of how many pathways there are - Kinterpolator = [interp1d(tinterp,elementarykernel_twospin(tinterp,r_q,method,excbandwidth,gridsize,g,orisel,complex),axis=0,kind='cubic') for r_q in r] + Kinterpolator = _elementarykernel_twospin_interp(tinterp,r,method,excbandwidth,gridsize,g,orisel,complex) withinInterpolation = lambda tdip: np.all((np.max(tinterp) >= np.max(tdip)) & (np.min(tinterp) <= np.min(tdip))) # Define kernel matrix auxiliary functions @@ -435,8 +435,14 @@ def K0_3spin(tdip): return K #============================================================================== - - +@cached(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 + Cached for performance reasons, interpolation is slow. + """ + Kinterpolator = [interp1d(tinterp,elementarykernel_twospin(tinterp,r_q,method,excbandwidth,gridsize,g,orisel,complex),axis=0,kind='cubic') for r_q in r] + return Kinterpolator #============================================================================== # TWO-SPIN ELEMENTARY DIPOLAR KERNEL @@ -468,14 +474,15 @@ def elementarykernel_twospin(tdip,r,method,ωex,gridsize,g,Pθ,complex): ωr = (μ0/2)*μB**2*g[0]*g[1]/h*1e21/(r**3) # rad μs^-1 # Orientation selection - orientationselection = Pθ is not None - if orientationselection: - # Ensure zero-derivatives at [0,π/2] - θ = np.linspace(0,π/2,50) # rad - Pθ_ = make_interp_spline(θ, Pθ(θ),bc_type="clamped") - # Ensure normalization of probability density function (∫P(cosθ)dcosθ=1) - Pθnorm,_ = quad(lambda cosθ: Pθ_(np.arccos(cosθ)),0,1,limit=1000) - Pθ = lambda θ: Pθ_(θ)/Pθnorm + if method != 'fresnel': + orientationselection = Pθ is not None + if orientationselection: + # Ensure zero-derivatives at [0,π/2] + θ = np.linspace(0,π/2,50) # rad + Pθ_ = make_interp_spline(θ, Pθ(θ),bc_type="clamped") + # Ensure normalization of probability density function (∫P(cosθ)dcosθ=1) + Pθnorm,_ = quad(lambda cosθ: Pθ_(np.arccos(cosθ)),0,1,limit=1000) + Pθ = lambda θ: Pθ_(θ)/Pθnorm def elementarykernel_fresnel(tdip): #------------------------------------------------------------------------ diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index 252ef0fcf..3aa922321 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -27,6 +27,7 @@ Release Notes Release ``v1.1.3`` - Ongoing ------------------------------------------ - |fix| : Removes unnecessary files from the docs +- |efficiency| : Improves the performance of the ``dipolarkernel`` function by 10-30% (:pr:`473`), by caching the interpolation of he effective dipolar evolution time vector. Release ``v1.1.2`` - November 2023 ------------------------------------------ From 56689462e484504ce5561e19659ba58fcd499d3c Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 1 Jul 2024 17:21:18 +0200 Subject: [PATCH 04/24] Adding support for scipy 1.14 and tests for Python 3.12 (#474) * Update for 3.12 * Updated workflows and changelog * Upload to 3.12 --- .github/workflows/ci_PR.yml | 2 +- .github/workflows/ci_scheduled.yml | 2 +- .github/workflows/package_upload.yml | 4 ++-- deerlab/diststats.py | 2 +- docsrc/source/changelog.rst | 1 + 5 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci_PR.yml b/.github/workflows/ci_PR.yml index 63de2eec9..88374ad6f 100644 --- a/.github/workflows/ci_PR.yml +++ b/.github/workflows/ci_PR.yml @@ -12,7 +12,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.10','3.11'] + python-version: ['3.11','3.12'] steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/ci_scheduled.yml b/.github/workflows/ci_scheduled.yml index 0659c65fc..b101659cf 100644 --- a/.github/workflows/ci_scheduled.yml +++ b/.github/workflows/ci_scheduled.yml @@ -12,7 +12,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.8, 3.9, "3.10", "3.11", "3.12"] + python-version: [3.8, 3.9, "3.10", "3.11", "3.12","3.12"] steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/package_upload.yml b/.github/workflows/package_upload.yml index 69be3f252..4a3b99777 100644 --- a/.github/workflows/package_upload.yml +++ b/.github/workflows/package_upload.yml @@ -11,10 +11,10 @@ jobs: steps: - name: Checkout uses: actions/checkout@v1 - - name: Set up Python 3.10 + - name: Set up Python 3.11 uses: actions/setup-python@v1 with: - python-version: "3.10" + python-version: "3.11" - name: Install pypa/build run: >- python -m pip install build --user diff --git a/deerlab/diststats.py b/deerlab/diststats.py index 9368de5bc..3497e7b5b 100644 --- a/deerlab/diststats.py +++ b/deerlab/diststats.py @@ -7,7 +7,7 @@ import warnings import copy from scipy.signal import find_peaks -from scipy.integrate import cumtrapz +from scipy.integrate import cumulative_trapezoid as cumtrapz def diststats(r, P, Puq=None, verbose=False, threshold=None): r""" diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index 3aa922321..d8edd8c8b 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -28,6 +28,7 @@ Release ``v1.1.3`` - Ongoing ------------------------------------------ - |fix| : Removes unnecessary files from the docs - |efficiency| : Improves the performance of the ``dipolarkernel`` function by 10-30% (:pr:`473`), by caching the interpolation of he effective dipolar evolution time vector. +- |fix| : add support for Python 3.12 Release ``v1.1.2`` - November 2023 ------------------------------------------ From 6a0b992516dd53b6a8af79300f2520b3d5db14aa Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Tue, 2 Jul 2024 07:57:54 +0200 Subject: [PATCH 05/24] Numpy2 support (#479) * Update for 3.12 * Updated workflows and changelog * Upload to 3.12 * Numpy 2.0 compatibility updates * Update Changelog --- deerlab/classes.py | 2 +- deerlab/dd_models.py | 2 +- deerlab/diststats.py | 2 +- docsrc/source/changelog.rst | 4 +++- test/test_dipolarkernel.py | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/deerlab/classes.py b/deerlab/classes.py index 7e9b3e149..39063cbf4 100644 --- a/deerlab/classes.py +++ b/deerlab/classes.py @@ -381,7 +381,7 @@ def percentile(self,p): cdf = np.cumsum(pdf) cdf /= max(cdf) # Eliminate duplicates - cdf, index = np.lib.arraysetops.unique(cdf,return_index=True) + cdf, index = np.unique(cdf,return_index=True) # Interpolate requested percentile x[n] = np.interp(p/100,cdf,values[index]) diff --git a/deerlab/dd_models.py b/deerlab/dd_models.py index dc32cbaab..1c4d6d3ff 100644 --- a/deerlab/dd_models.py +++ b/deerlab/dd_models.py @@ -110,7 +110,7 @@ def _multigaussfun(r,r0,sig): P = np.sqrt(1/(2*np.pi))*1/sig*np.exp(-0.5*((r.T-r0)/sig)**2) if not np.all(P==0): # Normalization - P = np.squeeze(P)/np.sum([np.trapz(c,r) for c in P.T]) + P = np.squeeze(P)/np.sum([np.trapezoid(c,r) for c in P.T]) else: P = np.squeeze(P) return P diff --git a/deerlab/diststats.py b/deerlab/diststats.py index 3497e7b5b..22d5d0229 100644 --- a/deerlab/diststats.py +++ b/deerlab/diststats.py @@ -109,7 +109,7 @@ def normalize(P): # Percentile function def pctile(r,P,p): cdf = cumtrapz(normalize(P),r,initial=0) - cdf, index = np.lib.arraysetops.unique(cdf,return_index=True) + cdf, index = np.unique(cdf,return_index=True) rpctile = np.interp(p/100,cdf,r[index]) return rpctile # Expectation operator function diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index d8edd8c8b..c1aa84ca7 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -28,7 +28,9 @@ Release ``v1.1.3`` - Ongoing ------------------------------------------ - |fix| : Removes unnecessary files from the docs - |efficiency| : Improves the performance of the ``dipolarkernel`` function by 10-30% (:pr:`473`), by caching the interpolation of he effective dipolar evolution time vector. -- |fix| : add support for Python 3.12 +- |fix| : Add support for Python 3.12 +- |fix| : Adds support for Numpy 2.0 + Release ``v1.1.2`` - November 2023 ------------------------------------------ diff --git a/test/test_dipolarkernel.py b/test/test_dipolarkernel.py index 8f7c505af..2d198541c 100644 --- a/test/test_dipolarkernel.py +++ b/test/test_dipolarkernel.py @@ -1,6 +1,6 @@ import numpy as np -from numpy import pi, inf, NaN +from numpy import pi, inf from deerlab.bg_models import bg_hom3d,bg_exp from deerlab.dd_models import dd_gauss from deerlab.dipolarkernel import dipolarkernel,elementarykernel_twospin From 19a491fbe0783d61faeda5a37e0c6820074737c4 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Mon, 15 Jul 2024 13:50:49 +0200 Subject: [PATCH 06/24] Regparam grid bug fix (#477) * Update for 3.12 * Updated workflows and changelog * Upload to 3.12 * Fix bug in regparam grid search Regparam would never build the grid correctly. Now using grid or Brent is automatically determined from number of elements in the regparamrange. * Add extra error messages * Update changelog * Updated Example * Updated test The test has been updated. The previous convergence criteria was unreliable and only worked based on a coincidence. * Prepare For Release * Remove duplicate python version --- .github/workflows/ci_scheduled.yml | 2 +- LICENSE | 2 +- deerlab/selregparam.py | 41 ++++++++++++------- deerlab/solvers.py | 4 +- docsrc/source/changelog.rst | 5 ++- examples/intermediate/ex_selregparam.py | 54 ++++++++++++++++++++++++- test/test_selregparam.py | 9 +++-- 7 files changed, 91 insertions(+), 26 deletions(-) diff --git a/.github/workflows/ci_scheduled.yml b/.github/workflows/ci_scheduled.yml index b101659cf..0659c65fc 100644 --- a/.github/workflows/ci_scheduled.yml +++ b/.github/workflows/ci_scheduled.yml @@ -12,7 +12,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.8, 3.9, "3.10", "3.11", "3.12","3.12"] + python-version: [3.8, 3.9, "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v3 diff --git a/LICENSE b/LICENSE index a2fb8b56d..1c241f0ed 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019-2023 Luis Fabregas, Stefan Stoll, Gunnar Jeschke, and other contributors +Copyright (c) 2019-2024 Luis Fabregas, Stefan Stoll, Gunnar Jeschke, and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/deerlab/selregparam.py b/deerlab/selregparam.py index 27a800cfd..fffe61f99 100644 --- a/deerlab/selregparam.py +++ b/deerlab/selregparam.py @@ -8,8 +8,8 @@ import math as m import deerlab as dl -def selregparam(y, A, solver, method='aic', algorithm='brent', noiselvl=None, - searchrange=[1e-8,1e2],regop=None, weights=None, full_output=False, candidates=None): +def selregparam(y, A, solver, method='aic', algorithm='auto', noiselvl=None, + searchrange=[1e-8,1e2],regop=None, weights=None, full_output=False): r""" Selection of optimal regularization parameter based on a selection criterion. @@ -52,6 +52,8 @@ def selregparam(y, A, solver, method='aic', algorithm='brent', noiselvl=None, * ``'ncp'`` - Normalized Cumulative Periodogram (NCP) * ``'gml'`` - Generalized Maximum Likelihood (GML) * ``'mcl'`` - Mallows' C_L (MCL) + + If ``'lr'`` or ``'lc'`` is specified, the search algorithm is automatically set to ``'grid'``. weights : array_like, optional Array of weighting coefficients for the individual datasets in global fitting. @@ -60,18 +62,16 @@ def selregparam(y, A, solver, method='aic', algorithm='brent', noiselvl=None, algorithm : string, optional Search algorithm: + * ``'auto'`` - Automatically, selects algrothium based on the searchrange. If the searchrange has two elements its set to ``'brent'`` otherwise to ``'grid'``. * ``'grid'`` - Grid-search, slow. * ``'brent'`` - Brent-algorithm, fast. - The default is ``'brent'``. - - searchrange : two-element list, optional - Search range for the optimization of the regularization parameter with the ``'brent'`` algorithm. - If not specified the default search range defaults to ``[1e-8,1e2]``. + The default is ``'auto'``. - candidates : list, optional - List or array of candidate regularization parameter values to be evaluated with the ``'grid'`` algorithm. - If not specified, these are automatically computed from a grid within ``searchrange``. + searchrange : list, optional + Either the search range for the optimization of the regularization parameter with the ``'brent'`` algorithm. + Or if more than two values are specified, then it is interpreted as candidates for the ``'grid'`` algorithm. + If not specified the default search range defaults to ``[1e-8,1e2]`` and the ``'brent'`` algorithm. regop : 2D array_like, optional Regularization operator matrix, the default is the second-order differential operator. @@ -108,6 +108,13 @@ def selregparam(y, A, solver, method='aic', algorithm='brent', noiselvl=None, # If multiple datasets are passed, concatenate the datasets and kernels y, A, weights,_,__, noiselvl = dl.utils.parse_multidatasets(y, A, weights, noiselvl) + if algorithm == 'auto' and len(searchrange) == 2: + algorithm = 'brent' + elif algorithm == 'auto' and len(searchrange) > 2: + algorithm = 'grid' + elif algorithm == 'auto' and len(searchrange) < 2: + raise ValueError("`searchrange` must have at least two elements if `algorithm` is set to `'auto'") + # The L-curve criteria require a grid-evaluation if method == 'lr' or method == 'lc': algorithm = 'grid' @@ -121,9 +128,11 @@ def selregparam(y, A, solver, method='aic', algorithm='brent', noiselvl=None, evalalpha = lambda alpha: _evalalpha(alpha, y, A, L, solver, method, noiselvl, weights) # Evaluate functional over search range, using specified search method - if algorithm == 'brent': - + if algorithm == 'brent': + # Search boundaries + if len(searchrange) != 2: + raise ValueError("Search range must have two elements for the 'brent' algorithm.") lga_min = m.log10(searchrange[0]) lga_max = m.log10(searchrange[1]) @@ -148,10 +157,10 @@ def register_ouputs(optout): elif algorithm=='grid': # Get range of potential alpha values candidates - if candidates is None: + if len(searchrange) == 2: alphaCandidates = 10**np.linspace(np.log10(searchrange[0]),np.log10(searchrange[1]),60) else: - alphaCandidates = np.atleast_1d(candidates) + alphaCandidates = np.atleast_1d(searchrange) # Evaluate the full grid of alpha-candidates functional,residuals,penalties,alphas_evaled = tuple(zip(*[evalalpha(alpha) for alpha in alphaCandidates])) @@ -176,6 +185,10 @@ def register_ouputs(optout): # Find minimum of the selection functional alphaOpt = alphaCandidates[np.argmin(functional)] + functional = np.array(functional) + residuals = np.array(residuals) + penalties = np.array(penalties) + alphas_evaled = np.array(alphas_evaled) else: raise KeyError("Search method not found. Must be either 'brent' or 'grid'.") diff --git a/deerlab/solvers.py b/deerlab/solvers.py index 523afbe15..5fa940135 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -602,8 +602,8 @@ def linear_problem(y,A,optimize_alpha,alpha): if optimize_alpha: linsolver_result = lambda AtA, Aty: parseResult(linSolver(AtA, Aty)) output = dl.selregparam((y-yfrozen)[mask], Ared[mask,:], linsolver_result, regparam, - weights=weights[mask], regop=L, candidates=regparamrange, - noiselvl=noiselvl,searchrange=regparamrange,full_output=True) + weights=weights[mask], regop=L, noiselvl=noiselvl, + searchrange=regparamrange,full_output=True) alpha = output[0] alpha_stats['alphas_evaled'] = output[1] alpha_stats['functional'] = output[2] diff --git a/docsrc/source/changelog.rst b/docsrc/source/changelog.rst index c1aa84ca7..cbd4db7c6 100644 --- a/docsrc/source/changelog.rst +++ b/docsrc/source/changelog.rst @@ -24,12 +24,13 @@ Release Notes - |fix| : Something which was not working as expected or leading to errors has been fixed. - |api| : This will require changes in your scripts or code. -Release ``v1.1.3`` - Ongoing +Release ``v1.1.3`` - July 2024 ------------------------------------------ - |fix| : Removes unnecessary files from the docs - |efficiency| : Improves the performance of the ``dipolarkernel`` function by 10-30% (:pr:`473`), by caching the interpolation of he effective dipolar evolution time vector. -- |fix| : Add support for Python 3.12 +- |api| : Removes the `candidates` input from `selregparam` and integrates its function into `regparamrange`. - |fix| : Adds support for Numpy 2.0 +- |fix| : Add support for Python 3.12 Release ``v1.1.2`` - November 2023 diff --git a/examples/intermediate/ex_selregparam.py b/examples/intermediate/ex_selregparam.py index 417c284d1..929d851ca 100644 --- a/examples/intermediate/ex_selregparam.py +++ b/examples/intermediate/ex_selregparam.py @@ -33,7 +33,7 @@ t = t + tmin # Distance vector -r = np.linspace(1.5,7,50) # nm +r = np.linspace(1.5,7,100) # nm # Construct the model Vmodel = dl.dipolarmodel(t,r, experiment=dl.ex_4pdeer(tau1,tau2, pathways=[1])) @@ -101,7 +101,7 @@ # %% # Over and Under selection of the regularisation parameter -# -------------------------------------------------------- +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Here we will demonstrate the effect of selecting a regularisation parameter # that is either too small or too large. @@ -145,8 +145,58 @@ # As we can see when the regularisation parameter is too small we still get a high # quality fit in the time domain, however, our distance domain data is now way too # spikey and non-physical. + # In contrast when the regularisation parameter is too large we struggle to get # a good fit, however, we get a much smoother distance distribution. # This could have been seen from the selection functional above. The effect of # lower regularisation parameter had a smaller effect on the functional than the # effect of going to a larger one. + +# Plotting the full L-Curve +# ++++++++++++++++++++++++++ +# Normally the selection of the regularisation parameter is done through a Brent optimisation +# algorithm. This results in the L-Curve being sparsely sampled. However, the full L-Curve can be +# generated by evaluating the functional at specified regularisation paramters. + +# This has the disadvantage of being computationally expensive, however, it can be useful. + +regparamrange = 10**np.linspace(np.log10(1e-6),np.log10(1e1),60) # Builds the range of regularisation parameters +results_grid= dl.fit(Vmodel,Vexp,regparam='bic',regparamrange=regparamrange) +print(results_grid) + +fig, axs =plt.subplots(1,3, figsize=(9,4),width_ratios=(1,1,0.1)) +alphas = results_grid.regparam_stats['alphas_evaled'][:] +funcs = results_grid.regparam_stats['functional'][:] + + +idx = np.argsort(alphas) + +axs[0].semilogx(alphas[idx], funcs[idx],marker='.',ls='-') +axs[0].set_title(r"$\alpha$ selection functional"); +axs[0].set_xlabel("Regularisation Parameter") +axs[0].set_ylabel("Functional Value ") + +# Just the final L-Curve +x = results_grid.regparam_stats['residuals'] +y = results_grid.regparam_stats['penalties'] +idx = np.argsort(x) + + +axs[1].loglog(x[idx],y[idx]) + +n_points = results_grid.regparam_stats['alphas_evaled'].shape[-1] +lams = results_grid.regparam_stats['alphas_evaled'] +norm = mpl.colors.LogNorm(vmin=lams[:].min(), vmax=lams.max()) +for i in range(n_points): + axs[1].plot(x[i], y[i],marker = '.', ms=8, color=cmap(norm(lams[i]))) + +i_optimal = np.argmin(np.abs(lams - results_grid.regparam)) +axs[1].annotate(fr"$\alpha =$ {results_grid.regparam:.2g}", xy = (x[i_optimal],y[i_optimal]),arrowprops=dict(facecolor='black', shrink=0.05, width=5), xytext=(20, 20),textcoords='offset pixels') +fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),cax=axs[2]) +axs[1].set_ylabel("Penalties") +axs[2].set_ylabel("Regularisation Parameter") +axs[1].set_xlabel("Residuals") +axs[1].set_title("L-Curve"); +fig.tight_layout() + +# %% diff --git a/test/test_selregparam.py b/test/test_selregparam.py index 30a64ee9d..74ad7fd25 100644 --- a/test/test_selregparam.py +++ b/test/test_selregparam.py @@ -102,10 +102,11 @@ def test_unconstrained(dataset,design_matrix,regularization_matrix): #======================================================================= def test_manual_candidates(dataset,design_matrix,regularization_matrix): "Check that the alpha-search range can be manually passed" - alphas = np.linspace(-8,2,60) - alpha_manual = np.log10(selregparam(dataset,design_matrix,cvxnnls,method='aic',candidates=alphas,regop=regularization_matrix)) - alpha_auto = np.log10(selregparam(dataset,design_matrix,cvxnnls,method='aic',regop=regularization_matrix)) - assert abs(alpha_manual-alpha_auto)<1e-4 + alphas = np.logspace(-8,3,60,base=10) + alpha_manual = np.log10(selregparam(dataset,design_matrix,cvxnnls,method='aic',searchrange=alphas,regop=regularization_matrix)) + alpha_auto = np.log10(selregparam(dataset,design_matrix,cvxnnls,method='aic',searchrange=(1e-8,1e-3), regop=regularization_matrix)) + + assert abs(alpha_manual-alpha_auto)<1 #======================================================================= #======================================================================= From b641a7ef44caa2064b75c7a06cdb43d5fae1cefa Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 09:39:38 +0100 Subject: [PATCH 07/24] Adding a benchmark libary --- benchmarks/bench_bootstrap.py | 47 +++++++++++++ benchmarks/bench_fitting.py | 121 ++++++++++++++++++++++++++++++++++ benchmarks/compare.py | 66 +++++++++++++++++++ benchmarks/conftest.py | 90 +++++++++++++++++++++++++ benchmarks/pytest.ini | 4 ++ benchmarks/readme.md | 83 +++++++++++++++++++++++ benchmarks/requirements.txt | 1 + 7 files changed, 412 insertions(+) create mode 100644 benchmarks/bench_bootstrap.py create mode 100644 benchmarks/bench_fitting.py create mode 100644 benchmarks/compare.py create mode 100644 benchmarks/conftest.py create mode 100644 benchmarks/pytest.ini create mode 100644 benchmarks/readme.md create mode 100644 benchmarks/requirements.txt diff --git a/benchmarks/bench_bootstrap.py b/benchmarks/bench_bootstrap.py new file mode 100644 index 000000000..17c597eae --- /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 000000000..b2ef2d340 --- /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 000000000..66aa79787 --- /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 000000000..c41bd917d --- /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 000000000..5e349eef1 --- /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 000000000..7c3750dc2 --- /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 000000000..8e3710639 --- /dev/null +++ b/benchmarks/requirements.txt @@ -0,0 +1 @@ +pytest-benchmark>=5.0 From 7d1ff9756bba850b225fb770caa5040141005784 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 09:47:37 +0100 Subject: [PATCH 08/24] Gitignore update --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index e06f9135a..dea12637d 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 From 328086b8212173565b74a8ee18179d3361332e67 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 10:25:53 +0100 Subject: [PATCH 09/24] Replace Memoization with native python implementation - ~25% speed-up on fitting - Fixes issues due to arrays > 1000 elements being cut or small difference being rounded --- deerlab/dipolarkernel.py | 60 ++++++++++++++++++++++++++++++++-- docsrc/source/installation.rst | 1 - setup.py | 1 - 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/deerlab/dipolarkernel.py b/deerlab/dipolarkernel.py index ae59cf63e..64ef6a864 100644 --- a/deerlab/dipolarkernel.py +++ b/deerlab/dipolarkernel.py @@ -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 @@ -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: @@ -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 @@ -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)" diff --git a/docsrc/source/installation.rst b/docsrc/source/installation.rst index 95257bc3f..9902c444f 100644 --- a/docsrc/source/installation.rst +++ b/docsrc/source/installation.rst @@ -37,7 +37,6 @@ Next, install DeerLab and all its dependencies via:: DeerLab installs the following packages: * `matplotlib `_ - A comprehensive library for creating data visualizations with Python -* `memoization `_ - A powerful caching library for Python * `pytest `_ - A Python testing framework * `cvxopt `_ - Free software package for convex optimization * `numpy `_ - The fundamental package for scientific computing with Python diff --git a/setup.py b/setup.py index 46872106c..5f596b44b 100644 --- a/setup.py +++ b/setup.py @@ -26,7 +26,6 @@ 'dill>=0.3.0', 'tqdm>=4.51.0', 'matplotlib>=3.6.0', - 'memoization>=0.3.1', 'pytest>=6.2.2', 'setuptools>=53.0.0', 'numexpr>=2.7.3', From f506e718943e451949813e52b813db2c4dd7f509 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 10:26:31 +0100 Subject: [PATCH 10/24] Evaluate the model once per residual Speedup: 5 to 30% --- deerlab/classes.py | 4 +++- deerlab/solvers.py | 9 +++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/deerlab/classes.py b/deerlab/classes.py index 4dd1e3be1..06be904d8 100644 --- a/deerlab/classes.py +++ b/deerlab/classes.py @@ -580,7 +580,9 @@ def propagate(self,model,lb=None,ub=None,samples=None): if iscomplex: model_ = model - model = lambda p: np.concatenate([model_(p).real,model_(p).imag]) + 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) diff --git a/deerlab/solvers.py b/deerlab/solvers.py index da46fd0cc..c4017d00f 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -512,9 +512,10 @@ def snlls(y, Amodel, par0=None, lb=None, ub=None, lbl=None, ubl=None, nnlsSolver Amodel__ = Amodel if np.iscomplexobj(A0): # If the design matrix is complex-valued - Amodel = lambda p: np.concatenate([Amodel__(p).real,Amodel__(p).imag]) - A0 = np.concatenate([A0.real,A0.imag]) - A0 = Amodel(par0) + def Amodel(p): + A = Amodel__(p) + return np.concatenate([A.real,A.imag]) + A0 = np.concatenate([A0.real,A0.imag]) if not complexy: # If the data is not complex-valued y = np.concatenate([y,np.zeros_like(y)]) @@ -677,7 +678,7 @@ def ResidualsFcn(p): regparam_prev = alpha # Compute residual vector - res = weights*(Amodel(p)@xfit - y) + res = weights*(A@xfit - y) # Apply mask to residual res = res[mask] From 1d703d06558971aa571fd1c599d0db68392422ed Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 10:43:19 +0100 Subject: [PATCH 11/24] Exact Jacobian for the linear parameters in uncertainty propagation --- deerlab/classes.py | 29 ++++++++++++++++--------- deerlab/fitresult.py | 22 ++++++++++++++++++- deerlab/model.py | 4 +++- deerlab/solvers.py | 50 +++++++++++++++++++++++++++++++++----------- 4 files changed, 81 insertions(+), 24 deletions(-) diff --git a/deerlab/classes.py b/deerlab/classes.py index 06be904d8..10ed7e770 100644 --- a/deerlab/classes.py +++ b/deerlab/classes.py @@ -526,7 +526,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. @@ -548,7 +548,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` @@ -578,14 +582,19 @@ def propagate(self,model,lb=None,ub=None,samples=None): if self.type=='moment': - 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) + 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) diff --git a/deerlab/fitresult.py b/deerlab/fitresult.py index 4d1ee66a6..c66a8eded 100644 --- a/deerlab/fitresult.py +++ b/deerlab/fitresult.py @@ -4,6 +4,7 @@ import matplotlib.pyplot as plt import difflib from deerlab.classes import UQResult +from deerlab.utils import Jacobian from deerlab.model import Model @@ -249,8 +250,27 @@ def propagate(self, model, *constants, lb=None, ub=None,samples=None): modelparam, fitparams, fitparam_idx = self._extract_params_from_function(model) + response = lambda param: model(*constants,*[param[s] for s in fitparam_idx]) + + jacobian = None + paramuq = self.paramUncert + if paramuq.type=='moment': + # Finite differences only over the parameters used by the model, the rest give zero columns + used = np.unique(np.concatenate([np.atleast_1d(s) for s in fitparam_idx]).astype(int)) + iscomplex = np.iscomplexobj(response(paramuq.mean)) + def response_used(param_used): + param = np.array(paramuq.mean, dtype=float) + param[used] = param_used + y = np.atleast_1d(response(param)) + return np.concatenate([y.real,y.imag]) if iscomplex else y + Jused = Jacobian(response_used, paramuq.mean[used], paramuq.lb[used], paramuq.ub[used]) + if iscomplex: + Jused = Jused[:Jused.shape[0]//2] + 1j*Jused[Jused.shape[0]//2:] + jacobian = np.zeros((Jused.shape[0],len(paramuq.mean)),dtype=Jused.dtype) + jacobian[:,used] = Jused + # Propagate the uncertainty from that subset to the model - modeluq = self.paramUncert.propagate(lambda param: model(*constants,*[param[s] for s in fitparam_idx]),lb,ub,samples) + modeluq = paramuq.propagate(response,lb,ub,samples,jacobian=jacobian) return modeluq diff --git a/deerlab/model.py b/deerlab/model.py index 0518a7e11..522652d0b 100644 --- a/deerlab/model.py +++ b/deerlab/model.py @@ -658,7 +658,9 @@ def _getparamuq(self,uq_full,paramidx): else: # Propagate the full UQ through the subset model if uq_full.type=='moment': - param_uq = uq_full.propagate(subset_model,lb=param_lb, ub=param_ub) + # The Jacobian of the selection is the selection matrix: no finite differences needed + selection = np.eye(len(uq_full.mean))[paramidx] + param_uq = uq_full.propagate(subset_model,lb=param_lb, ub=param_ub, jacobian=selection) elif uq_full.type=='bootstrap': param_uq = UQResult('bootstrap',data=uq_full.samples[:,paramidx],lb=param_lb, ub=param_ub) else: diff --git a/deerlab/solvers.py b/deerlab/solvers.py index c4017d00f..196f97f48 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -178,19 +178,21 @@ def _prepare_linear_lsq(A,lb,ub,reg,L,tol,maxiter,nnlsSolver): # =========================================================================================== # =========================================================================================== -def _model_evaluation(ymodels,parfit,paruq,uq,modeluq): +def _model_evaluation(ymodels,parfit,paruq,uq,modeluq,yjacobians=None): """ Model evaluation ================ Evaluates the model(s) response(s) at the fitted solution and propagates the uncertainty in the fit - parameters to the model response. + parameters to the model response. If given, ``yjacobians`` are functions returning the Jacobian of + each model response, which is then used instead of finite differences. """ modelfit, modelfituq = [],[] - for ymodel in ymodels: + for n,ymodel in enumerate(ymodels): modelfit.append(ymodel(parfit)) - if uq and modeluq: - modelfituq.append(paruq.propagate(ymodel)) + if uq and modeluq: + jacobian = yjacobians[n]() if yjacobians is not None else None + modelfituq.append(paruq.propagate(ymodel,jacobian=jacobian)) else: modelfituq.append(UQResult('void')) return modelfit, modelfituq @@ -787,7 +789,9 @@ def uq_subset(uq_full,subset,subset_lb,subset_ub): "Get the uncertainty quantification for a subset of parameters" subset_model = lambda x: x[subset] - uq_subset = uq_full.propagate(subset_model,lb=subset_lb, ub=subset_ub) + # The Jacobian of the selection is the selection matrix: no finite differences needed + selection = np.eye(len(uq_full.mean))[subset] + uq_subset = uq_full.propagate(subset_model,lb=subset_lb, ub=subset_ub, jacobian=selection) return uq_subset #----------------------------------------------------------------------------- @@ -843,14 +847,36 @@ def uq_subset(uq_full,subset,subset_lb,subset_ub): nonlin_idx = np.arange(len(nonlinfit)) lin_idx = np.arange(len(nonlinfit),len(parfit)) Amodel = _Amodel # Use the model with the full parameter set + def Asubset(n,pnonlin): + "Design matrix of the n-th model response, y_n = Asubset(n,pnonlin)@plin" + A = Amodel(pnonlin) + An = A[subsets[n]] + if complexy: + An = An + 1j*A[imagsubsets[n]] + return An def ymodel(n): - return lambda p: (Amodel(p[nonlin_idx])@p[lin_idx])[subsets[n]] - if complexy: - ymodel_ = ymodel - def ymodel(n): - return lambda p: ymodel_(n)(p) + 1j*(Amodel(p[nonlin_idx])@p[lin_idx])[imagsubsets[n]] + return lambda p: Asubset(n,p[nonlin_idx])@p[lin_idx] + def yjacobian(n): + "Jacobian of the n-th model response: finite differences for the non-linear parameters, exact for the linear ones" + def jacobian(): + if len(nonlin_idx)>0: + fcn = lambda pnonlin: Asubset(n,pnonlin)@linfit + if complexy: + Nreal = len(subsets[n]) + def fcn_stacked(pnonlin): + yn = fcn(pnonlin) + return np.concatenate([yn.real,yn.imag]) + Jstacked = Jacobian(fcn_stacked,nonlinfit,lb,ub) + Jnonlin = Jstacked[:Nreal] + 1j*Jstacked[Nreal:] + else: + Jnonlin = Jacobian(fcn,nonlinfit,lb,ub) + else: + Jnonlin = np.zeros((len(subsets[n]),0)) + return np.concatenate([Jnonlin,Asubset(n,nonlinfit)],axis=1) + return jacobian ymodels = [ymodel(n) for n in range(len(subsets))] - modelfit,modelfituq = _model_evaluation(ymodels,parfit,paramuq,uq,modeluq) + yjacobians = [yjacobian(n) for n in range(len(subsets))] + modelfit,modelfituq = _model_evaluation(ymodels,parfit,paramuq,uq,modeluq,yjacobians) # Make lists of data and fits ys = [y[subset] for subset in subsets] From 40d8f36582e0937a0db09aeb99cd7bb36caeb2be Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:06:07 +0100 Subject: [PATCH 12/24] Benchmarks added --- benchmarks/bench_fitting.py | 37 +++++++++++++++++++++++++++++++++++++ benchmarks/conftest.py | 15 +++++++++++++++ benchmarks/readme.md | 1 + 3 files changed, 53 insertions(+) diff --git a/benchmarks/bench_fitting.py b/benchmarks/bench_fitting.py index b2ef2d340..c749d49ea 100644 --- a/benchmarks/bench_fitting.py +++ b/benchmarks/bench_fitting.py @@ -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): @@ -38,6 +59,22 @@ def 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" diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py index c41bd917d..a87de0b52 100644 --- a/benchmarks/conftest.py +++ b/benchmarks/conftest.py @@ -59,6 +59,21 @@ def data_4pdeer(): 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_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" diff --git a/benchmarks/readme.md b/benchmarks/readme.md index 7c3750dc2..04a507255 100644 --- a/benchmarks/readme.md +++ b/benchmarks/readme.md @@ -9,6 +9,7 @@ This is implemented using [`pytest-benchmark`](https://pytest-benchmark.readthed | Group | Benchmark | File | |---|---|---| | `fit` | Single pathway 4pDEER | `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` | From 84088875d7b0c615818f05da165d1d28630839a3 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:06:23 +0100 Subject: [PATCH 13/24] Compute the linear degrees of freedom once --- deerlab/solvers.py | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/deerlab/solvers.py b/deerlab/solvers.py index 196f97f48..e85ba229d 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -575,7 +575,7 @@ def Amodel(p): par_prev = [0]*len(par0_red) alpha = None xfit = np.zeros(Nlin) - Ndof_lin = 0 + A_prev = None if verbose>0: print(f'{timestamp()} Preparations completed.') @@ -592,7 +592,7 @@ def linear_problem(y,A,optimize_alpha,alpha): # If all linear parameters are frozen, do not optimize if Nlin_notfrozen==0: - return lin_parfrozen.astype(float), None, 0 + return lin_parfrozen.astype(float), None # Remove columns corresponding to frozen linear parameters Ared = A[:,~lin_frozen] @@ -617,8 +617,6 @@ def linear_problem(y,A,optimize_alpha,alpha): # Components for linear least-squares AtA, Aty = _lsqcomponents((y-yfrozen)[mask], Ared[mask,:], L, alpha, weights=weights[mask]) - Ndof = np.maximum(0,np.trace(Ared@np.linalg.pinv(AtA))) - # Solve the linear least-squares problem result = linSolver(AtA, Aty) result = parseResult(result) @@ -627,8 +625,22 @@ def linear_problem(y,A,optimize_alpha,alpha): # Insert back the frozen linear parameters xfit = _insertfrozen(xfit,lin_parfrozen,lin_frozen) - return xfit, alpha, Ndof + return xfit, alpha + + #=========================================================================== + def linear_dof(A,alpha): + #=========================================================================== + """ + Effective number of linear parameters + ------------------------------------- + Only needed at the solution, for the goodness-of-fit statistics. + """ + if Nlin_notfrozen==0: + return 0 + Ared = A[:,~lin_frozen] + AtA, _ = _lsqcomponents(y[mask], Ared[mask,:], L, alpha, weights=weights[mask]) + return np.maximum(0,np.trace(Ared@np.linalg.pinv(AtA))) #=========================================================================== def ResidualsFcn(p): @@ -640,12 +652,13 @@ def ResidualsFcn(p): non-linear least-squares solver. """ - nonlocal par_prev, check, regparam_prev, xfit, alpha, alpha_stats, Ndof, Ndof_lin - - - + nonlocal par_prev, check, regparam_prev, xfit, alpha, alpha_stats, A_prev + + + # Non-linear model evaluation A = Amodel(p) + A_prev = A # Check whether optimization of the regularization parameter is needed if includeRegularization : @@ -676,7 +689,7 @@ def ResidualsFcn(p): optimize_alpha = False alpha = 0 - xfit,alpha,Ndof_lin = linear_problem(y,A,optimize_alpha,alpha) + xfit,alpha = linear_problem(y,A,optimize_alpha,alpha) regparam_prev = alpha # Compute residual vector @@ -720,7 +733,7 @@ def ResidualsFcn(p): optimize_alpha = False # Solve the linear LSQ problem - linfit, alpha, Ndof_lin = linear_problem(y,Amodel(None),optimize_alpha,alpha) + linfit, alpha = linear_problem(y,Amodel(None),optimize_alpha,alpha) # Compute the residual res = ResidualsFcn(None) @@ -768,7 +781,9 @@ def ResidualsFcn(p): # Compute the fit residual _ResidualsFcn = lambda nonlinfit: ResidualsFcn(_unfrozen_subset_inv(nonlinfit,nonlin_frozen)) res = _ResidualsFcn(nonlinfit) - fvals = np.sum(res**2)/len(res) + fvals = np.sum(res**2)/len(res) + # Effective number of linear parameters at the solution + Ndof_lin = linear_dof(A_prev,alpha) if verbose>0: print(f'{timestamp()} Least-squares routine finished.') From 20d7c3131a97419dfabf5fae0abafab7d4481ea6 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:06:23 +0100 Subject: [PATCH 14/24] Fix the formula for the linear degrees of freedom --- deerlab/solvers.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/deerlab/solvers.py b/deerlab/solvers.py index e85ba229d..e68a33f65 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -634,13 +634,21 @@ def linear_dof(A,alpha): """ Effective number of linear parameters ------------------------------------- + Trace of the hat matrix H = Aw (Aw^T Aw + alpha^2 L^T L)^-1 Aw^T of the (regularized) + linear problem, with Aw the weighted design matrix. Computed as trace((AtAreg)^-1 Aw^T Aw). Only needed at the solution, for the goodness-of-fit statistics. """ if Nlin_notfrozen==0: return 0 Ared = A[:,~lin_frozen] - AtA, _ = _lsqcomponents(y[mask], Ared[mask,:], L, alpha, weights=weights[mask]) - return np.maximum(0,np.trace(Ared@np.linalg.pinv(AtA))) + AtAreg, _ = _lsqcomponents(y[mask], Ared[mask,:], L, alpha, weights=weights[mask]) + Aw = weights[mask,np.newaxis]*Ared[mask,:] + AtA = Aw.T@Aw + try: + Ndof = np.trace(np.linalg.solve(AtAreg,AtA)) + except np.linalg.LinAlgError: + Ndof = np.trace(np.linalg.pinv(AtAreg)@AtA) + return np.maximum(0,Ndof) #=========================================================================== def ResidualsFcn(p): From 7e3778f8862eb33eeb772c192db428224aab0ed7 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:06:23 +0100 Subject: [PATCH 15/24] Fix the information criteria and complex-valued statistics in `goodness_of_fit` --- deerlab/utils.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/deerlab/utils.py b/deerlab/utils.py index 89ff4f68f..78075c6ae 100644 --- a/deerlab/utils.py +++ b/deerlab/utils.py @@ -296,22 +296,25 @@ def goodness_of_fit(x,xfit,Ndof,noiselvl): # Get number of xariables N = len(x) # Extrapolate number of parameters - Q = Ndof - N + Q = N - Ndof + + # Squared magnitudes, such that complex-valued residuals give real-valued statistics + RSS = np.sum(np.abs(residuals)**2) # Reduced Chi-squared test chi2red = 1/Ndof*np.linalg.norm(residuals)**2/sigma**2 # Autocorrelation based on Durbin–Watson statistic - autocorr_DW = abs( 2 - np.sum((residuals[1:-1] - residuals[0:-2])**2)/np.sum(residuals**2) ) + autocorr_DW = abs( 2 - np.sum(np.abs(residuals[1:-1] - residuals[0:-2])**2)/RSS ) # R-squared test - R2 = 1 - np.sum((residuals)**2)/np.sum((xfit-np.mean(xfit))**2) + R2 = 1 - RSS/np.sum(np.abs(xfit-np.mean(xfit))**2) # Root-mean square dexiation - rmsd = np.sqrt(np.sum((residuals)**2)/N) + rmsd = np.sqrt(RSS/N) # Log-likelihood - loglike = N*np.log(np.sum((residuals)**2)) + loglike = N*np.log(RSS) # Akaike information criterion aic = loglike + 2*Q From 55b8d412f4ca5980da1a42f314bb708bdebaef60 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:06:24 +0100 Subject: [PATCH 16/24] Skip the identity product for non-parametric distributions --- deerlab/dipolarmodel.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/deerlab/dipolarmodel.py b/deerlab/dipolarmodel.py index 97becc300..457efcf53 100644 --- a/deerlab/dipolarmodel.py +++ b/deerlab/dipolarmodel.py @@ -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]) From 6f6f4c0278dac11dd865934ecfe1c6154a7925cd Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:20:16 +0100 Subject: [PATCH 17/24] Vectorize `link` and `merge` --- deerlab/model.py | 77 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 10 deletions(-) diff --git a/deerlab/model.py b/deerlab/model.py index 522652d0b..1384d4715 100644 --- a/deerlab/model.py +++ b/deerlab/model.py @@ -4,7 +4,6 @@ # Copyright(c) 2019-2023: Luis Fabregas, Stefan Stoll and other contributors. import numpy as np -from scipy.sparse import block_diag from scipy.optimize import fminbound from deerlab.classes import UQResult from deerlab.bootstrap_analysis import bootstrap_analysis @@ -1350,7 +1349,45 @@ def _aresame(obj1,obj2): # --------------------------------------------------------------------- # --------------------------------------------------------------------- -def _linked_model_with_constants(nonlinfcn,mapping,constantsInfo,linear_reduce_idx,*inputargs): +def _linear_reduction(linear_reduce_idx,Nlin): + """ + (Private function) + + Precomputes how the columns of the design matrix are combined after linking linear parameters. + + Parameters + ---------- + linear_reduce_idx : list + List of lists with the indices of the columns to be summed together, one list per column of the output. + Nlin : int + Number of columns of the design matrix before linking. + + Returns + ------- + reduction : tuple or None + ``None`` if there are no linear parameters, ``('identity',)`` if the columns are unchanged, + ``('permute', order)`` if they are only reordered, and ``('sum', first, rest)`` otherwise. + ``first`` holds the first column of each group, and ``rest`` one ``(groups, columns)`` pair + per further position within the groups, with the columns to add to those groups. + """ + if len(linear_reduce_idx)==0: + return None + order = np.concatenate([np.atleast_1d(idx) for idx in linear_reduce_idx]).astype(int) + sizes = np.array([len(idx) for idx in linear_reduce_idx]) + if np.all(sizes==1): + if len(order)==Nlin and np.array_equal(order,np.arange(Nlin)): + return ('identity',) + return ('permute',order) + first = np.array([idx[0] for idx in linear_reduce_idx],dtype=int) + rest = [] + for k in range(1,np.max(sizes)): + groups = np.where(sizes>k)[0] + columns = np.array([linear_reduce_idx[g][k] for g in groups],dtype=int) + rest.append((groups,columns)) + return ('sum',first,rest) +# --------------------------------------------------------------------- + +def _linked_model_with_constants(nonlinfcn,mapping,constantsInfo,linear_reduction,*inputargs): """ (Private function) @@ -1367,8 +1404,8 @@ def _linked_model_with_constants(nonlinfcn,mapping,constantsInfo,linear_reduce_i constantsInfo : list List of dictionaries with information on the constants in the function. - linear_reduce_idx : list - List of arrays with the indices of the model response to be summed together. + linear_reduction : tuple or None + How the columns of the model response are combined, as returned by ``_linear_reduction``. Returns ------- @@ -1394,10 +1431,21 @@ def _linked_model_with_constants(nonlinfcn,mapping,constantsInfo,linear_reduce_i if isinstance(A,tuple): return A # Make a matrix if model function returns a vector if len(A.shape)<2: A = np.expand_dims(A,1) - # Sum the output matrix along the columns specified in the linear_reduce_idx array - if len(linear_reduce_idx)==0: return A - Amapped = np.vstack([np.sum(np.atleast_2d(A[:,idx]),axis=1) for idx in linear_reduce_idx]).T - return Amapped + # Combine the columns of the output matrix corresponding to linked linear parameters + # Returned as column-major order + if linear_reduction is None: + return A + if linear_reduction[0]=='identity': + return np.asfortranarray(A) + if linear_reduction[0]=='permute': + return np.asfortranarray(A[:,linear_reduction[1]]) + # Sum the columns of each group, adding them in the order they are listed + _,first,rest = linear_reduction + AT = A.T + Amapped = AT[first] + for groups,columns in rest: + Amapped[groups] += AT[columns] + return Amapped.T # --------------------------------------------------------------------- # ============================================================================== @@ -1555,9 +1603,10 @@ def _linkparameter(model,parameters,newname): # Monkey-patch the evaluation function nonlinfcn = model.nonlinmodel linear_reduce_idx = [np.where(mapping_linear==n)[0].tolist() for n in np.unique(mapping_linear) ] + linear_reduction = _linear_reduction(linear_reduce_idx,len(mapping_linear)) # Redefine the non-linear part of the model function - model.nonlinmodel = partial(_linked_model_with_constants,nonlinfcn,mapping,model._constantsInfo,linear_reduce_idx) + model.nonlinmodel = partial(_linked_model_with_constants,nonlinfcn,mapping,model._constantsInfo,linear_reduction) # Return the updated model with the linked parameters return model @@ -1673,7 +1722,15 @@ def _combined_nonlinmodel(mode,nonlinfcns,Nlins,Nconst,arelinear,const_subsets,s # Merge or concatenate the output of the submodels if mode=='merge': - Anonlin_full = block_diag(Amatrices).toarray() + # Block-diagonal matrix, filled into a preallocated dense array + Nrows = [np.shape(A)[0] for A in Amatrices] + Ncols = [np.shape(A)[1] for A in Amatrices] + Anonlin_full = np.zeros((sum(Nrows),sum(Ncols)),dtype=np.result_type(*Amatrices)) + row,col = 0,0 + for Amatrix,Nrow,Ncol in zip(Amatrices,Nrows,Ncols): + Anonlin_full[row:row+Nrow,col:col+Ncol] = Amatrix + row += Nrow + col += Ncol # If all submodels are non-linear, sum the output matrices if not any(arelinear): From ca1d509429cdce21aa4b45270f8ad188b5e96ec6 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:34:45 +0100 Subject: [PATCH 18/24] Reuse the fit at the optimal penalty weight --- deerlab/fit.py | 11 ++++++++--- deerlab/model.py | 20 +++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/deerlab/fit.py b/deerlab/fit.py index 9b7a9fc52..6cc701621 100644 --- a/deerlab/fit.py +++ b/deerlab/fit.py @@ -469,17 +469,22 @@ def fit(model_, y, *constants, par0=None, penalties=None, bootstrap=0, noiselvl= # Prepare the separable non-linear least-squares solver Amodel_fcn = lambda param: model.nonlinmodel(*constants,*param) - fitfcn = lambda y,penweights: snlls(y, Amodel_fcn, par0, lb=lb, ub=ub, lbl=lbl, ubl=ubl, mask=mask, weights=weights, + def fitfcn(y,penweights): + result = snlls(y, Amodel_fcn, par0, lb=lb, ub=ub, lbl=lbl, ubl=ubl, mask=mask, weights=weights, subsets=ysubsets, lin_frozen=linfrozen, nonlin_frozen=nonlinfrozen, regparam=regparam, reg=reg, regparamrange=regparamrange, noiselvl=noiselvl, - extrapenalty=extrapenalties(penweights), modeluq=True, **kwargs) + extrapenalty=extrapenalties(penweights), modeluq=True, **kwargs) + # Keep the penalty weights this fit was run with + result._penweights = penweights + return result # Prepare outer optimization of the penalty weights, if necessary fitfcn = _outerOptimization(fitfcn,penalties,sigmas) # Run the fitting algorithm fitresults = fitfcn(y) - penweights = [penalty._weight_value for penalty in penalties] + # Penalty weights of the returned fit + penweights = list(fitresults._penweights) if len(penalties)>0 else [] # If requested, perform a bootstrap analysis if bootstrap>0: diff --git a/deerlab/model.py b/deerlab/model.py index 1384d4715..381dfb80c 100644 --- a/deerlab/model.py +++ b/deerlab/model.py @@ -1247,27 +1247,37 @@ def optimize(self,fitfcn,y,sigma): weightopt : scalar Optimized penalty weight. """ + # Fits evaluated during the search, by penalty weight + fits = {} + def fitfcn_stored(weight): + fits[weight] = fitfcn(weight) + return fits[weight] + if not self.weight.frozen: # Extract optimization range from model penalty searchrange = np.array([np.log10(self.weight.lb), np.log10(self.weight.ub)]) searchrange[np.isinf(searchrange)] = 20 # Construct the selection functional - selectionFunctional = lambda log10weight: self.selectionfcn(fitfcn,y,sigma,log10weight) + selectionFunctional = lambda log10weight: self.selectionfcn(fitfcn_stored,y,sigma,log10weight) # Minimization of the selection functional log10optweight = fminbound(selectionFunctional,*searchrange, xtol=0.1) # Logscale -> linear-scale optweight = 10**log10optweight - else: + else: optweight = self.weight.value - self._weight_value = optweight + self._weight_value = optweight # Update optimized value to object self.optweight = optweight - # Get the fit result - fitresult = fitfcn(optweight) + # Get the fit result: the search has already evaluated the optimum (fminbound returns + # the best point it evaluated), otherwise run the fit + if optweight in fits: + fitresult = fits[optweight] + else: + fitresult = fitfcn(optweight) return fitresult,optweight #-------------------------------------------------------------------------- From eb9913a3ecc22db68abf22fa5ccb7bcc423736ec Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:34:46 +0100 Subject: [PATCH 19/24] Reproducible bootstrap: draw the samples in the calling process, seed the benchmarks --- benchmarks/conftest.py | 7 ++++++- deerlab/bootstrap_analysis.py | 18 +++++++----------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py index a87de0b52..b91bb1587 100644 --- a/benchmarks/conftest.py +++ b/benchmarks/conftest.py @@ -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): diff --git a/deerlab/bootstrap_analysis.py b/deerlab/bootstrap_analysis.py index d65e3fcf5..ba60aed09 100644 --- a/deerlab/bootstrap_analysis.py +++ b/deerlab/bootstrap_analysis.py @@ -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: From 135bb400ec5a33d7949308f276a0efcda50d0907 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:42:46 +0100 Subject: [PATCH 20/24] =?UTF-8?q?Fix=20the=20test=20that=20decides=20when?= =?UTF-8?q?=20to=20re-optimize=20=CE=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- deerlab/fit.py | 2 +- deerlab/solvers.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/deerlab/fit.py b/deerlab/fit.py index 6cc701621..e0e171e5d 100644 --- a/deerlab/fit.py +++ b/deerlab/fit.py @@ -333,7 +333,7 @@ def fit(model_, y, *constants, par0=None, penalties=None, bootstrap=0, noiselvl= Regularization operator matrix, the default is the second-order differential operator. alphareopt : float scalar, optional - Relative parameter change threshold for reoptimizing the regularization parameter + Parameter change threshold for reoptimizing the regularization parameter (relative for parameters with magnitude above 1, absolute below) when using a selection method, the default is ``1e-3``. nnlsSolver : string, optional diff --git a/deerlab/solvers.py b/deerlab/solvers.py index e68a33f65..9f6e12d7f 100644 --- a/deerlab/solvers.py +++ b/deerlab/solvers.py @@ -360,7 +360,7 @@ def snlls(y, Amodel, par0=None, lb=None, ub=None, lbl=None, ubl=None, nnlsSolver The square of the penalty is computed internally. alphareopt : float scalar, optional - Relative parameter change threshold for reoptimizing the regularization parameter + Parameter change threshold for reoptimizing the regularization parameter (relative for parameters with magnitude above 1, absolute below) when using a selection method, the default is ``1e-3``. nnlsSolver : string, optional @@ -673,7 +673,8 @@ def ResidualsFcn(p): if type(regparam) is str: if Nnonlin_notfrozen>0: # If the parameter vector has not changed by much... - if check and all(abs(par_prev-p)/(p+np.finfo(np.float64).eps) < alphareopt): + # (relative change for |p|>=1, absolute change below, as in the finite-difference steps of least_squares) + if check and np.all(np.abs(p - par_prev) <= alphareopt*np.maximum(np.abs(p),1)): # ...use the alpha optimized in the previous iteration optimize_alpha = False alpha = regparam_prev From 329da7581109f9bb8c9fa3a186dbf4aa1ea65f28 Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:42:46 +0100 Subject: [PATCH 21/24] Add 4pDEER three-pathway benchmark --- benchmarks/bench_fitting.py | 15 +++++++++++++++ benchmarks/conftest.py | 11 +++++++++++ benchmarks/readme.md | 1 + 3 files changed, 27 insertions(+) diff --git a/benchmarks/bench_fitting.py b/benchmarks/bench_fitting.py index c749d49ea..3c76f853a 100644 --- a/benchmarks/bench_fitting.py +++ b/benchmarks/bench_fitting.py @@ -59,6 +59,21 @@ 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" diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py index b91bb1587..ee6e0aad5 100644 --- a/benchmarks/conftest.py +++ b/benchmarks/conftest.py @@ -64,6 +64,17 @@ def data_4pdeer(): 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_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" diff --git a/benchmarks/readme.md b/benchmarks/readme.md index 04a507255..d734d92a4 100644 --- a/benchmarks/readme.md +++ b/benchmarks/readme.md @@ -9,6 +9,7 @@ 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` | From d72f8ce4665bfda4656439a62c599c3f71e3324b Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 11:54:06 +0100 Subject: [PATCH 22/24] Fix benchmark compare --- benchmarks/compare.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/benchmarks/compare.py b/benchmarks/compare.py index 66aa79787..943523386 100644 --- a/benchmarks/compare.py +++ b/benchmarks/compare.py @@ -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(): @@ -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__': From a3b5d532a0d2d1314b8da0ed1e6c49a7e29edaef Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 15:24:43 +0100 Subject: [PATCH 23/24] benchmark profile analysis --- benchmarks/bench_bootstrap.py | 14 ++++++++------ benchmarks/conftest.py | 5 +++-- benchmarks/readme.md | 1 + 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/benchmarks/bench_bootstrap.py b/benchmarks/bench_bootstrap.py index 17c597eae..15a689d75 100644 --- a/benchmarks/bench_bootstrap.py +++ b/benchmarks/bench_bootstrap.py @@ -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): @@ -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() \ No newline at end of file + # 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}' \ No newline at end of file diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py index ee6e0aad5..22b435785 100644 --- a/benchmarks/conftest.py +++ b/benchmarks/conftest.py @@ -61,8 +61,9 @@ 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) - return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2) + 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(): diff --git a/benchmarks/readme.md b/benchmarks/readme.md index d734d92a4..643374c23 100644 --- a/benchmarks/readme.md +++ b/benchmarks/readme.md @@ -18,6 +18,7 @@ This is implemented using [`pytest-benchmark`](https://pytest-benchmark.readthed | `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. From fd115c16f719aba40643579894e1a1825b21162e Mon Sep 17 00:00:00 2001 From: Hugo Karas Date: Thu, 3 Dec 2026 15:25:55 +0100 Subject: [PATCH 24/24] Warm-start the bootstrap and profile fits --- deerlab/classes.py | 9 ++++++--- deerlab/fit.py | 11 ++++++++--- deerlab/profile_analysis.py | 20 ++++++++++++++++++++ test/test_profile_analysis.py | 9 +++++++++ 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/deerlab/classes.py b/deerlab/classes.py index 10ed7e770..02d465c37 100644 --- a/deerlab/classes.py +++ b/deerlab/classes.py @@ -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) @@ -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) diff --git a/deerlab/fit.py b/deerlab/fit.py index e0e171e5d..2f30a5fb9 100644 --- a/deerlab/fit.py +++ b/deerlab/fit.py @@ -469,8 +469,10 @@ def fit(model_, y, *constants, par0=None, penalties=None, bootstrap=0, noiselvl= # Prepare the separable non-linear least-squares solver Amodel_fcn = lambda param: model.nonlinmodel(*constants,*param) + # Start values of the non-linear parameters (replaced by the fitted values for the bootstrap samples) + par0_fit = par0 def fitfcn(y,penweights): - result = snlls(y, Amodel_fcn, par0, lb=lb, ub=ub, lbl=lbl, ubl=ubl, mask=mask, weights=weights, + result = snlls(y, Amodel_fcn, par0_fit, lb=lb, ub=ub, lbl=lbl, ubl=ubl, mask=mask, weights=weights, subsets=ysubsets, lin_frozen=linfrozen, nonlin_frozen=nonlinfrozen, regparam=regparam, reg=reg, regparamrange=regparamrange, noiselvl=noiselvl, extrapenalty=extrapenalties(penweights), modeluq=True, **kwargs) @@ -487,8 +489,11 @@ def fitfcn(y,penweights): penweights = list(fitresults._penweights) if len(penalties)>0 else [] # If requested, perform a bootstrap analysis - if bootstrap>0: - def bootstrap_fcn(ysim): + if bootstrap>0: + # Warm start: the resampled datasets are close to the original one, so start their fits + # at the fitted non-linear parameters, which takes fewer iterations + par0_fit = fitresults.nonlin + def bootstrap_fcn(ysim): fit = fitfcn(np.concatenate(ysim)) if not isinstance(fit.model,list): fit.model = [fit.model] return (fit.param,*fit.model) diff --git a/deerlab/profile_analysis.py b/deerlab/profile_analysis.py index 76bc97d0a..92b604ae8 100644 --- a/deerlab/profile_analysis.py +++ b/deerlab/profile_analysis.py @@ -84,6 +84,26 @@ def profile_analysis(model,y, *args, parameters='all', grids=None, samples=50, n elif not isinstance(parameters,list): parameters = [parameters] + # Warm start: start the fits along the profiles at the fitted values of the free non-linear + # parameters, which takes fewer iterations. The original start values are restored at the end. + par0_original = {} + if 'par0' not in kargs: + for name in model._parameter_list(): + param = getattr(model,name) + if not np.any(param.linear) and not np.all(param.frozen): + par0_original[name] = param.par0 + param.par0 = getattr(fitresult,name) + try: + uqresults = _profile_parameters(model, y, args, kargs, parameters, fitresult, threshold_inputs, noiselvl, samples, grids, verbose, cores) + finally: + for name,value in par0_original.items(): + getattr(model,name).par0 = value + return uqresults +#=============================================================================== + +def _profile_parameters(model, y, args, kargs, parameters, fitresult, threshold_inputs, noiselvl, samples, grids, verbose, cores): + "Profile each of the requested parameters (see ``profile_analysis``)" + # Loop over all parameters in the model uqresults = {} for parameter in parameters: diff --git a/test/test_profile_analysis.py b/test/test_profile_analysis.py index abe54b772..2e8669330 100644 --- a/test/test_profile_analysis.py +++ b/test/test_profile_analysis.py @@ -45,6 +45,15 @@ def test_basics(model, mock_data): assert np.allclose([mean_mean,std_mean],[3,0.2],rtol=1e-2) # ====================================================================== +# ====================================================================== +def test_confidence_intervals(model, mock_data): + "Check that confidence intervals can be computed from the profiles and contain the true values" + profuq = profile_analysis(model,mock_data,samples=10,noiselvl=noiselvl) + for parameter,truth in [('mean',3),('std',0.2)]: + ci = profuq[parameter].ci(95) + assert np.shape(ci)==(2,) and ci[0] <= truth <= ci[1] +# ====================================================================== + # ====================================================================== def test_globalmodel(model, mock_data): "Check the profiling works with multiple datasets"