Repository navigation
Conversation
* Increase version number and update changelog (JeschkeLab#455) * Bugfixes 4th sep (JeschkeLab#460) * Fix normalisation in rice model Closes JeschkeLab#459 * Remove three spin anaysis Closes JeschkeLab#427 * Improved installation instructions * Caution about difference in definition of cost function Closes JeschkeLab#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 (JeschkeLab#464) * Fixing Sophgrid bug * Add unit test for sophgrid * Update changelog.rst for new release (JeschkeLab#466)
* Fixing Sophgrid bug * Add unit test for sophgrid * Minor doc update * Bump version Number * Remove unnecessary doc files * Update changelog
* 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
* Update for 3.12 * Updated workflows and changelog * Upload to 3.12
* Update for 3.12 * Updated workflows and changelog * Upload to 3.12 * Numpy 2.0 compatibility updates * Update Changelog
* 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
- ~25% speed-up on fitting - Fixes issues due to arrays > 1000 elements being cut or small difference being rounded
Speedup: 5 to 30%
stestoll
approved these changes
Dec 3, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Speed up fitting
Summary
This PR removes overhead from
fit, followingFITTING_SPEEDUPS.md. Every benchmark is now 1.8× to 4.8× faster thanmain. Most changes leave results bit-identical; the ones that change output are listed below.Speed-up on the benchmarks
mainvs this branch, measured in one session withpython benchmarks/compare.py main(mean of 3–5 cold-cache rounds).main(s)merge+link)mainThe complex-valued and three-pathway benchmarks are new in this PR. Saved runs:
0019_base-main.json,0020_head.json.Largest gains
link/merge(section 7): −24% on the global fit.Changes that affect output
stats) change (sections 4b and 5): these are bug fixes, so reported values move.selregparam.aic,aiccandbicsubtracted the parameter penalty instead of adding it.rmsd,R2,autocorrand the information criteria were complex numbers; they are now real.aic,aiccorbiccan therefore choose a different weight. The default (icc) is unaffected.np.random.seed. Before, they could not be reproduced. 1-core results are unchanged.penweightsnow reports the weights the returned fit was run with. Before, this could be the last weight evaluated rather than the optimum.Other changes
jacobian=argument ofUQResult.propagate.memoizationdependency.benchmarks/compare.py: fixed two bugs. The base revision was benchmarked with the working tree'sdeerlab, becausepython -m pytestputs the working directory ahead ofPYTHONPATH. Also, the--failthreshold was passed in a format that pytest-benchmark rejects.Details
Each change below lists its benchmark effect (
pytest benchmarks, mean of 3–5 cold-cache rounds, same machine; macOS, Python 3.14, NumPy 2.4, SciPy 1.17).Changes
1. Exact byte-based cache keys for the dipolar kernel
memoization.cachedonelementarykernel_twospinand_elementarykernel_twospin_interpwith a small LRU cache,_arraycacheindipolarkernel.py. It keeps the size limit of 100 entries and thecache_clear()method.(shape, dtype, tobytes())instead ofstr(args).str()rounds to 8 significant digits and abbreviates arrays with more than 1000 elements, so different inputs could share a key and get the wrong kernel back. Verified: two 2000-point time axes that differ in one element had equalstr()keys before this change; they now get separate entries.dipolarkernel(..., clearcache=True)now also clears the interpolator cache.memoizationdependency (setup.py, installation docs).2. Evaluate the model once per residual
snllsresidual (solvers.py): the residual reuses the design matrixAcomputed earlier in the same call, instead of evaluatingAmodel(p)a second time.snlls(solvers.py) andUQResult.propagate(classes.py): the inner model is evaluated once and split into.real/.imag, instead of once for each part.snllswith a complex design matrix: removed a redundantA0 = Amodel(par0)that recomputed the value set on the line before.snllsfit now calls the model 26 times instead of 97, with identical fitted parameters. The newtest_4pdeer_complexbenchmark (see "Benchmarks added") covers this case.3. Exact Jacobian for the linear parameters in uncertainty propagation
UQResult.propagatetakes a new optionaljacobian=argument. If it is given, the finite-difference Jacobian (one model evaluation per parameter) is skipped.snlls): the response is y = A(θ)·x, so its Jacobian with respect to x is exactly A(θ). Only the non-linear parameters θ use finite differences. Before, there were finite differences over all parameters: 3 + 151 model evaluations for non-parametric 4pDEER.uq_subsetinsnlls,Model._getparamuq): the Jacobian of the selectionx[idx]is passed as the selection matrix, instead of being computed by finite differences.FitResult.propagate(e.g. background uncertainty infit): for moment-based uncertainties, the finite differences only run over the parameters that the propagated model uses. Columns of the other parameters are zero, as before. For the background this replaces about 150Model.__call__evaluations by the few for its own parameters.4a. Compute the linear degrees of freedom once
snllscomputedNdof = trace(Ared@pinv(AtA))insidelinear_problem, i.e. one SVD on every residual call. Only the value from the last residual call was used, in the goodness-of-fit statistics. That last call could even be a finite-difference column of the uncertainty Jacobian.linear_dof(A, alpha)helper, at the solution after the least-squares run. The formula is unchanged in this step.stats, on the 4pDEER, complex 4pDEER and 5pDEER benchmark fits. Tests: the full suite passes (617 tests).Saved runs:
0007_after_1_3.json(before),0008_after_1_4a.json(after).4b. Fix the formula for the linear degrees of freedom
Old formula:
trace(Ared@pinv(AtA)).Aredis N×n, so the product is N×n andnp.tracesummed its first n diagonal elements, which mixes time and distance indices. It also used the unweighted, unmasked design matrix.New formula: the effective number of linear parameters is the trace of the hat matrix, H = Aw·(AwᵀAw + α²LᵀL)⁻¹·Awᵀ, with Aw the weighted and masked design matrix. It is computed as
trace(solve(AtAreg, AwᵀAw)), with apinvfallback ifAtAregis singular. This is the same trace of H thatselregparamuses for its criteria. Like there, the non-negativity constraints are not taken into account.Effect on
stats(fitted parameters and uncertainties unchanged):Penalty weights:
Penalty.optimizeselects the weight withstats['aic'],['aicc']or['bic']when the user picks one of these criteria, so the chosen weight can change for them. The default fordipolarpenaltyisicc, which does not usestats: the compactness benchmark result is identical (same weight, α and P).Tests: the full suite passes (617 tests).
Timing: no measurable change. It adds one n×n solve per fit; all benchmarks are within run-to-run noise. A first run showed single-pathway 4pDEER at 0.298 s; two re-runs gave 0.276 and 0.273 s (vs 0.275 s before).
Note: in this step
aic/aicc/bicdecrease with the larger number of parameters, because of the sign error fixed in section 5.5. Fix the information criteria and complex-valued statistics in
goodness_of_fit(bug fix; changesstats)Not a speedup but related bugfix
Sign of the parameter penalty: the number of parameters was computed as
Q = Ndof - N. WithNdof = N - nParamthis is −nParam, soaic = loglike + 2Q,aiccandbicsubtracted the parameter penalty instead of adding it. NowQ = N - Ndof.Complex-valued data:
rmsd,R2,autocorrand the log-likelihood usedresiduals**2, which is complex for complex residuals, so these statistics came out complex. They now useabs(residuals)**2(chi2redalready used the norm).Nremains the number of complex data points.Effect on
stats(fitted parameters and uncertainties unchanged):Penalty weights: as in 4b, penalties with
selection='aic','aicc'or'bic'can now select a different weight; the defaulticcis unaffected.Tests: the full suite passes (617 tests). Timing: unchanged, all benchmarks within run-to-run noise.
6. Skip the identity product for non-parametric distributions
freedistreturnsnp.eye(len(r))andVtwospin_nonlinear_fcn(dipolarmodel.py) computedKdipolar@eyeon every model evaluation. Whendipolarmodelwas built withPmodel=None, it now returnsKdipolardirectly.Kdipolaris a new array on every call (not the cached kernel), so returning it is safe.stats, on the 4pDEER, complex 4pDEER and 5pDEER benchmark fits. Tests: the full suite passes (617 tests).7. Vectorize
linkandmergelink(_linked_model_with_constants,model.py): after linking, the design-matrix columns of linked linear parameters were summed with a Python loop over all columns (np.vstack([np.sum(A[:,idx],axis=1) for idx in linear_reduce_idx])), on every model call and at every linking level. The column reduction is now precomputed once at link time by a new_linear_reductionhelper:conc): no reduction.P_1+P_2): start from the first column of each group and add the remaining columns with one vectorized add per position within the groups. This adds the columns in the same order as before. (np.add.reduceatwas tried first and was no faster than the loop.)vstack(...).Treturned it. With C order, the downstream matrix products take a different BLAS path, and the global fit changed by up to 8×10⁻⁷ relative.merge(_combined_nonlinmodel,model.py): the block-diagonal design matrix is filled into a preallocated dense array instead ofscipy.sparse.block_diag(...).toarray(). Thescipy.sparseimport is no longer needed.Per model call (2-dataset global fit, 725×302 merged matrix):
link, identity levellink, summing level (150 pairs)mergeblock diagonalResults: bit-identical on the global fit (parameters, covariance, confidence intervals,
stats) and on the 4pDEER, complex 4pDEER and 5pDEER fits. The summing path is also bit-identical to the old loop for groups of 3 and 4 columns (checked separately). Tests: the full suite passes (617 tests).link/merge)8. Reuse the fit at the optimal penalty weight
Penalty.optimize(model.py) ran the full fit again at the optimal weight afterfminbound.fminboundreturns the best point it has evaluated, so this fit had already been computed. The fits from the search are now kept, by weight, and the one at the optimum is returned; if the optimum was not evaluated (or the weight is frozen), the fit is run as before.fitread the reportedpenweightsfrom the penalty objects' state (_weight_value) afterwards. Without the repeat, that state could belong to another outer weight.fit(fit.py) therefore now stores on eachsnllsresult the penalty weights it was run with, and reports those.Penalty.optimizealso sets_weight_valueto the optimal weight. Before, it held the last weight evaluated, which is not necessarily the optimum.snllsfits: 11 → 10 with one penalty (compactness), 143 → 120 with two (compactness + smoothness).stats) for one and two penalties. Tests: the full suite passes (617 tests).9. Reproducible bootstrap: draw the samples in the calling process, seed the benchmarks
bootstrap_analysis(bootstrap_analysis.py): the resampled datasets were drawn inside each parallel job, i.e. in the worker processes whencores>1. Their random state cannot be seeded from the calling script, so results with several cores were not reproducible and differed from the 1-core result. All samples are now drawn in the calling process before the fits are dispatched.cores=1the random numbers are drawn in the same order as before: results are bit-identical to the previous version for the same seed.np.random.seed(...)now reproduces the result, and it is identical to the 1-core result (checked with 1 and 4 cores, two runs each).benchmarks/conftest.py):clear_caches, which runs before every round, now also seedsnp.randomwith the dataset seed. The bootstrap benchmarks (and the random draws inUQResult.propagatefor bootstrap uncertainties) are therefore the same in every round and every run, and their accuracy checks can no longer fail by chance.10. Fix the test that decides when to re-optimize α
snllsre-optimizes the regularization parameter α unless all non-linear parameters changed by less thanalphareopt(1e-3) since the previous residual call. The test wasall(abs(par_prev-p)/(p+eps) < alphareopt):least_squaresgives a relative change of ~1, so a full α search ran inside that Jacobian column.New test:
np.all(np.abs(p - par_prev) <= alphareopt*np.maximum(np.abs(p),1)), i.e. relative change for |p| ≥ 1 and absolute change below. The floor of 1 is the scaleleast_squaresuses for its own finite-difference steps (max(1,|x|)), so those steps (~1.5×10⁻⁸) can no longer trigger an α search. Thealphareoptdocstrings insnllsandfitare updated accordingly.Operation counts and results (
fitwithout bootstrap; σ = standard error of the parameter before the change):pathways=[1,3](refocusing time of pathway 3 at 0)Overlap with the ground truth: 4pDEER
[1,3]0.914 → 0.919, complex 0.934 → 0.933, others unchanged.Tests: the full suite passes (617 tests).
The benchmarks existing at this point had no parameter at or near 0. The new
test_4pdeer_3pathwaysbenchmark (pathway 3 refocuses at 0) covers this case.11. Fix the profile-analysis benchmark and profile confidence intervals
benchmarks/bench_bootstrap.py):test_4pdeer_profile_analysiscould never pass.alpha=0.05toprofile_analysis, which forwards unknown keywords tofitand on tosnlls:TypeError.results.Pandresults.PUncert, butprofile_analysisreturns a dict with oneUQResultper non-linear parameter.nprofile) and checks that each 95% profile confidence interval contains the true value of the simulation. The true values are now stored in thedata_4pdeerfixture astruth.bootstrapgroup and listed inbenchmarks/readme.md.UQResult.cifor profile results (classes.py):ci()failed for every result returned byprofile_analysis(TypeError: string indices must be integers).profile_analysisstores a single profile as a dict and the fitted value as a scalar, whileci()iterated over the profiles as a list and indexed the fitted value. Both cases are now handled, aspardistalready did. New testtest_confidence_intervalsintest/test_profile_analysis.py(fails before the fix, passes after).mod[0.224, 0.469] (true 0.35),reftime[0.297, 0.305] (0.3),conc[19.6, 34.1] (30).12. Warm-start the bootstrap and profile fits
Bootstrap (
fit.py): the fits of the resampled datasets started from the model'spar0, like the original fit. The resampled data are close to the original data, so they now start from the fitted non-linear parameters of the original fit. α is still optimized in every sample, so the bootstrap still includes the variability of α (fixing α would be 3× faster but narrowed the bootstrap spread by 14% on 4pDEER, so it is not done).Profile analysis (
profile_analysis.py): the fits along each profile now start from the fitted values of the free non-linear parameters. This is done by setting the model parameters'par0for the duration of the analysis and restoring them afterwards (also on error), unless the user passespar0. The profiling loop moved into a private helper_profile_parametersfor that.Effect (4pDEER, 20 bootstrap samples, seeded; profile with 10 grid points per parameter):
least_squaresevaluationsResults: the warm-started fits converge to the same optima within the optimizer's tolerance.
conc(25.2 → 27.1); this is the flat direction between concentration and distribution tail. Confidence intervals:mod[0.338, 0.358] → [0.338, 0.357],reftimeunchanged to 10⁻⁴,conc[17.7, 45.0] → [18.5, 44.3]; P and its CI change by at most 0.5% of max(P).modunchanged,reftime[0.2972, 0.3052] → [0.2968, 0.3052],conc[19.64, 34.15] → [19.59, 34.07].Tests: the full suite passes (618 tests).
Benchmarks added
test_4pdeer_complex(bench_fitting.py, fixturedata_4pdeer_complex): 4pDEER with complex-valued data, as acquired in quadrature. The signal has a receiver phase of π/5 and independent noise on the real and imaginary channels. The model isdipolarmodelmultiplied by exp(−i·phase), with the phase fitted as an extra non-linear parameter. Besides the distribution overlap, the benchmark checks that the fitted phase is within 0.05 rad of the true phase. It covers the complex-valued code paths insnllsandUQResult.propagate.test_4pdeer_3pathways(bench_fitting.py, fixturedata_4pdeer_3pathways): 4pDEER with three dipolar pathways, simulated and fitted withex_4pdeer(..., pathways=[1,2,3])(amplitudes 0.35, 0.05, 0.05; refocusing times τ1, τ1+τ2, 0). Pathway 3 refocuses at t=0, so its refocusing time is a parameter at 0, the case of section 10. Checks the distribution overlap (> 0.9; 0.92 obtained).