diff --git a/benchmarks/bench_bootstrap.py b/benchmarks/bench_bootstrap.py index 17c597ea..b9afb436 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}' diff --git a/benchmarks/bench_fitting.py b/benchmarks/bench_fitting.py index b2ef2d34..3c76f853 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,37 @@ def analysis(): assert overlap(d['r'], results.P) > 0.9 # ====================================================================== +@pytest.mark.benchmark(group='fit') +def test_4pdeer_3pathways(benchmark, data_4pdeer_3pathways): + "4-pulse DEER, three dipolar pathways (pathway 3 refocuses at t=0), Tikhonov regularization" + d = data_4pdeer_3pathways + + def analysis(): + experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1, 2, 3]) + Vmodel = dl.dipolarmodel(d['t'], d['r'], experiment=experiment) + return dl.fit(Vmodel, d['V']) + + results = run_cold(benchmark, analysis) + + assert overlap(d['r'], results.P) > 0.9 +# ====================================================================== + +@pytest.mark.benchmark(group='fit') +def test_4pdeer_complex(benchmark, data_4pdeer_complex): + "4-pulse DEER, single pathway, complex-valued data with the receiver phase fitted, Tikhonov regularization" + d = data_4pdeer_complex + + def analysis(): + experiment = dl.ex_4pdeer(d['tau1'], d['tau2'], pathways=[1]) + Vmodel = phased_dipolarmodel(d['t'], d['r'], experiment) + return dl.fit(Vmodel, d['V']) + + results = run_cold(benchmark, analysis) + + assert overlap(d['r'], results.P) > 0.9 + assert abs(results.phase - d['phase']) < 0.05 +# ====================================================================== + @pytest.mark.benchmark(group='fit') def test_4pdeer_single_pathway_long(benchmark, data_4pdeer_long): "4-pulse DEER, single pathway, Tikhonov regularization, long evolution time" diff --git a/benchmarks/compare.py b/benchmarks/compare.py index 66aa7978..94352338 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__': diff --git a/benchmarks/conftest.py b/benchmarks/conftest.py index c41bd917..22b43578 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): @@ -56,9 +61,36 @@ def data_4pdeer(): t = np.linspace(0.1, 3.8, 250) # μs r = np.linspace(2, 6, 150) # nm experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1]) - V = _simulate(t, r, experiment, mod=0.35, reftime=tau1, conc=30) + truth = dict(mod=0.35, reftime=tau1, conc=30) + V = _simulate(t, r, experiment, **truth) + return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2, truth=truth) + +@pytest.fixture(scope='session') +def data_4pdeer_3pathways(): + "4-pulse DEER dataset with three dipolar pathways (refocusing at tau1, tau1+tau2 and 0)" + tau1, tau2 = 0.3, 4.0 # μs + t = np.linspace(0.1, 3.8, 250) # μs + r = np.linspace(2, 6, 150) # nm + experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1, 2, 3]) + V = _simulate(t, r, experiment, lam1=0.35, reftime1=tau1, lam2=0.05, reftime2=tau1 + tau2, + lam3=0.05, reftime3=0, conc=30) return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2) +@pytest.fixture(scope='session') +def data_4pdeer_complex(): + "Single-pathway 4-pulse DEER dataset, complex-valued with a receiver phase offset, as acquired in quadrature" + tau1, tau2 = 0.3, 4.0 # μs + t = np.linspace(0.1, 3.8, 250) # μs + r = np.linspace(2, 6, 150) # nm + phase = np.pi/5 # rad + experiment = dl.ex_4pdeer(tau1, tau2, pathways=[1]) + model = dl.dipolarmodel(t, r, experiment=experiment) + V = model(mod=0.35, reftime=tau1, conc=30, P=np.interp(r, r_true, P_true)) + V = V/np.max(V)*np.exp(-1j*phase) + # Independent noise on the real and imaginary channels + V = V + dl.whitegaussnoise(t, noiselvl, seed=seed) + 1j*dl.whitegaussnoise(t, noiselvl, seed=seed + 1) + return dict(t=t, r=r, V=V, tau1=tau1, tau2=tau2, phase=phase) + @pytest.fixture(scope='session') def data_4pdeer_long(): "Single-pathway 4-pulse DEER dataset with a long evolution time" diff --git a/benchmarks/readme.md b/benchmarks/readme.md index 7c3750dc..643374c2 100644 --- a/benchmarks/readme.md +++ b/benchmarks/readme.md @@ -9,6 +9,8 @@ This is implemented using [`pytest-benchmark`](https://pytest-benchmark.readthed | Group | Benchmark | File | |---|---|---| | `fit` | Single pathway 4pDEER | `bench_fitting.py` | +| `fit` | 4pDEER with three pathways (1, 2, 3) | `bench_fitting.py` | +| `fit` | Single pathway 4pDEER, complex-valued data with receiver phase | `bench_fitting.py` | | `fit` | Single pathway 4pDEER, long trace | `bench_fitting.py` | | `fit` | Single pathway 4pDEER, long trace, parametric (`dd_gauss2`) | `bench_fitting.py` | | `fit` | Global fit of two 4pDEER traces | `bench_fitting.py` | @@ -16,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. diff --git a/deerlab/bootstrap_analysis.py b/deerlab/bootstrap_analysis.py index d65e3fcf..ba60aed0 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: diff --git a/deerlab/classes.py b/deerlab/classes.py index 4dd1e3be..02d465c3 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) @@ -526,7 +529,7 @@ def getprofile_at(value): #-------------------------------------------------------------------------------- - def propagate(self,model,lb=None,ub=None,samples=None): + def propagate(self,model,lb=None,ub=None,samples=None,jacobian=None): """ Uncertainty propagation. @@ -548,7 +551,11 @@ def propagate(self,model,lb=None,ub=None,samples=None): Upper bounds of the values returned by ``model``, by default assumed unconstrained. samples : int, optional Number of samples to use when propagating a bootstraped uncertainty. If not provided, default value is 1000. - + jacobian : ndarray, optional + Jacobian of ``model`` with respect to the parameters at the mean, with shape (number of model outputs, number of parameters). + Complex-valued if ``model`` is complex-valued. Only used for ``'moment'`` uncertainties. If not provided, it is + estimated by finite differences, which costs one evaluation of ``model`` per parameter. + Returns ------- modeluq : :ref:`UQResult` @@ -578,12 +585,19 @@ def propagate(self,model,lb=None,ub=None,samples=None): if self.type=='moment': - if iscomplex: - model_ = model - model = lambda p: np.concatenate([model_(p).real,model_(p).imag]) - - # Get jacobian of model to be propagated with respect to parameters - J = Jacobian(model,parfit,self.lb,self.ub) + if jacobian is not None: + J = np.atleast_2d(jacobian) + if iscomplex: + J = np.concatenate([J.real,J.imag]) + else: + if iscomplex: + model_ = model + def model(p): + y = model_(p) + return np.concatenate([y.real,y.imag]) + + # Get jacobian of model to be propagated with respect to parameters + J = Jacobian(model,parfit,self.lb,self.ub) # Clip at boundaries modelfit = np.maximum(modelfit,lb) diff --git a/deerlab/dipolarkernel.py b/deerlab/dipolarkernel.py index ae59cf63..64ef6a86 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/deerlab/dipolarmodel.py b/deerlab/dipolarmodel.py index 97becc30..457efcf5 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]) diff --git a/deerlab/fit.py b/deerlab/fit.py index 9b7a9fc5..2f30a5fb 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 @@ -469,21 +469,31 @@ 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, + # 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_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) + 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: - 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/fitresult.py b/deerlab/fitresult.py index 4d1ee66a..c66a8ede 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 0518a7e1..381dfb80 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 @@ -658,7 +657,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: @@ -1246,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 #-------------------------------------------------------------------------- @@ -1348,7 +1359,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) @@ -1365,8 +1414,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 ------- @@ -1392,10 +1441,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 # --------------------------------------------------------------------- # ============================================================================== @@ -1553,9 +1613,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 @@ -1671,7 +1732,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): diff --git a/deerlab/profile_analysis.py b/deerlab/profile_analysis.py index 76bc97d0..92b604ae 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/deerlab/solvers.py b/deerlab/solvers.py index da46fd0c..9f6e12d7 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 @@ -358,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 @@ -512,9 +514,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)]) @@ -572,7 +575,7 @@ def snlls(y, Amodel, par0=None, lb=None, ub=None, lbl=None, ubl=None, nnlsSolver 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.') @@ -589,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] @@ -614,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) @@ -624,10 +625,32 @@ 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 + ------------------------------------- + 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] + 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): #=========================================================================== """ @@ -637,19 +660,21 @@ 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 : 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 @@ -673,11 +698,11 @@ 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 - res = weights*(Amodel(p)@xfit - y) + res = weights*(A@xfit - y) # Apply mask to residual res = res[mask] @@ -717,7 +742,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) @@ -765,7 +790,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.') @@ -786,7 +813,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 #----------------------------------------------------------------------------- @@ -842,14 +871,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] diff --git a/deerlab/utils.py b/deerlab/utils.py index 89ff4f68..78075c6a 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 diff --git a/docsrc/source/installation.rst b/docsrc/source/installation.rst index 95257bc3..9902c444 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 46872106..5f596b44 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', diff --git a/test/test_profile_analysis.py b/test/test_profile_analysis.py index abe54b77..2e866933 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"