From a140b2ab39d1914a2dd0fcc0b69bbef3d8361fe5 Mon Sep 17 00:00:00 2001 From: Fabian Joswig Date: Wed, 1 Mar 2023 16:26:37 +0000 Subject: [PATCH] refactor: removed redundant formulations of the chisquare function in least_squares. --- pyerrors/fits.py | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/pyerrors/fits.py b/pyerrors/fits.py index 2f635b4a..9aa9e8bf 100644 --- a/pyerrors/fits.py +++ b/pyerrors/fits.py @@ -580,17 +580,6 @@ def _combined_fit(x, y, func, silent=False, **kwargs): else: x0 = [0.1] * n_parms - if kwargs.get('correlated_fit') is True: - def chisqfunc_residuals_corr(p): - model = np.concatenate([np.array(funcd[key](p, np.asarray(xd[key]))).reshape(-1) for key in key_ls]) - chisq = anp.dot(chol_inv, (y_f - model)) - return chisq - - def chisqfunc_residuals(p): - model = np.concatenate([np.array(funcd[key](p, np.asarray(xd[key]))).reshape(-1) for key in key_ls]) - chisq = ((y_f - model) / dy_f) - return chisq - if kwargs.get('correlated_fit') is True: corr = covariance(y_all, correlation=True, **kwargs) covdiag = np.diag(1 / np.asarray(dy_f)) @@ -602,9 +591,24 @@ def _combined_fit(x, y, func, silent=False, **kwargs): chol = np.linalg.cholesky(corr) chol_inv = scipy.linalg.solve_triangular(chol, covdiag, lower=True) + def general_chisqfunc_corr(p, ivars): + model = anp.concatenate([anp.array(funcd[key](p, anp.asarray(xd[key]))).reshape(-1) for key in key_ls]) + return anp.dot(chol_inv, (ivars - model)) + + def general_chisqfunc(p, ivars): + model = anp.concatenate([anp.array(funcd[key](p, anp.asarray(xd[key]))).reshape(-1) for key in key_ls]) + return ((ivars - model) / dy_f) + + if kwargs.get('correlated_fit') is True: + def chisqfunc_residuals_corr(p): + return general_chisqfunc_corr(p, y_f) + def chisqfunc_corr(p): return anp.sum(chisqfunc_residuals_corr(p) ** 2) + def chisqfunc_residuals(p): + return general_chisqfunc(p, y_f) + def chisqfunc(p): return anp.sum(chisqfunc_residuals(p) ** 2) @@ -700,16 +704,10 @@ def _combined_fit(x, y, func, silent=False, **kwargs): if kwargs.get('correlated_fit') is True: def chisqfunc_compact(d): - func_list = np.concatenate([[funcd[k]] * len(xd[k]) for k in key_ls]) - model = anp.array([func_list[i](d[:n_parms], x_all[i]) for i in range(len(x_all))]) - chisq = anp.sum(anp.dot(chol_inv, (d[n_parms:] - model)) ** 2) - return chisq + return anp.sum(general_chisqfunc_corr(d[:n_parms], d[n_parms:]) ** 2) else: def chisqfunc_compact(d): - func_list = np.concatenate([[funcd[k]] * len(xd[k]) for k in key_ls]) - model = anp.array([func_list[i](d[:n_parms], x_all[i]) for i in range(len(x_all))]) - chisq = anp.sum(((d[n_parms:] - model) / dy_f) ** 2) - return chisq + return anp.sum(general_chisqfunc(d[:n_parms], d[n_parms:]) ** 2) jac_jac_y = hessian(chisqfunc_compact)(np.concatenate((fitp, y_f)))