diff --git a/curepy/container/measurement.py b/curepy/container/measurement.py index 3a9a12d..8d55f60 100644 --- a/curepy/container/measurement.py +++ b/curepy/container/measurement.py @@ -32,12 +32,16 @@ def __init__( length of ``y``. :param skip_invcov: If ``True``, skip the computation of the inverse covariance matrix (which is only needed for certain retrieval methods like optimal estimation). """ - + self.u_y_syst = u_y_syst + self.u_y_rand = u_y_rand + u_y_syst = None + u_y_rand = None u_y_total, corr_y = self._format_uncertainty( u_y_total, u_y_rand, u_y_syst, corr_y ) self.y = y + self.N_eff = len(y) self.u_y = u_y_total self.y_flat, self.u_y_flat, self.y_shape = self._flatten_inputs( self.y, self.u_y diff --git a/curepy/container/retrieval_input.py b/curepy/container/retrieval_input.py index 63714af..a9ae6fe 100644 --- a/curepy/container/retrieval_input.py +++ b/curepy/container/retrieval_input.py @@ -1,5 +1,7 @@ """Container for all retrieval inputs""" +from matplotlib.pylab import gamma + from curepy.container.measurement_function import MeasurementFunction from curepy.container.ancillary_parameter import AncillaryParameter from curepy.container.prior import Prior @@ -7,6 +9,9 @@ from typing import Union, List, Optional, Callable, Any +import scipy.linalg +import numpy as np +import comet_maths as cm class RetrievalInput: @@ -259,3 +264,42 @@ def build_from_obsarray( b, u_b, corr_b, corr_between_b, b_samples, b_MC_steps ) self.prior_obj = Prior(prior_shape, prior_params, prior_correlation) + + def return_mismatch_covariance(self, samples: np.ndarray, autocorrelation_time) -> np.ndarray: + """ + Return the mismatch covariance matrix. + + :param samples: Retrieval samples. + :returns: Mismatch covariance matrix. + """ + r_w = self.calculate_whitened_residuals(samples) + R = (r_w @ r_w.T)/len(r_w.T) + evals, evecs = np.linalg.eigh(R) + + N_eff = len(samples)/autocorrelation_time + gamma = len(r_w) / N_eff + lambda_mp = (1 + np.sqrt(gamma))**2 + + evecs_dominant = evecs[:, evals > lambda_mp] + evals_dominant = evals[evals > lambda_mp] + + C_fit_half = scipy.linalg.sqrtm(cm.convert_corr_to_cov(self.measurement_obj.corr_y, self.measurement_obj.u_y_flat)) + Delta = np.diag(evals_dominant - lambda_mp) + C_model = C_fit_half @ evecs_dominant @ Delta @ evecs_dominant.T @ C_fit_half + + C_model = 0.5 * (C_model + C_model.T) + + return C_model, N_eff + + def calculate_whitened_residuals(self, samples: np.ndarray) -> np.ndarray: + """ + Calculate the whitened residuals of the retrieval. + + :param samples: Retrieval samples. + :returns: Whitened residuals. + """ + samples_sim = np.vstack([self.measurement_function_obj.measurement_function_x(samples[i], self.ancillary_obj.b) for i in range(len(samples))]) if len(samples.shape) > 1 else self.measurement_function_obj.measurement_function_x(samples, self.ancillary_obj.b) + r = samples_sim - self.measurement_obj.y_flat + C_fit = cm.convert_corr_to_cov(self.measurement_obj.corr_y, self.measurement_obj.u_y_flat) + r_w = scipy.linalg.sqrtm(np.linalg.inv(C_fit)) @ r.T + return r_w diff --git a/curepy/container/retrieval_result.py b/curepy/container/retrieval_result.py index 11a89dc..96cb4be 100644 --- a/curepy/container/retrieval_result.py +++ b/curepy/container/retrieval_result.py @@ -4,6 +4,7 @@ import obsarray from typing import Optional import numpy as np +from scipy.stats import kstest from curepy.retrieval_methods.base import BaseRetrieval @@ -18,6 +19,7 @@ def __init__( b_samples: Optional[np.ndarray] = None, x_names: Optional[list] = None, retrieval_object: Optional[BaseRetrieval] = None, + N_eff: int = None, ) -> None: """ Container for retrieval output quantities. @@ -37,6 +39,7 @@ def __init__( self.b_samples = b_samples self.x_names = x_names self._retrieval_object = retrieval_object + self.N_eff = N_eff def build_obsarray(self) -> None: """ @@ -47,11 +50,18 @@ def build_obsarray(self) -> None: """ raise NotImplementedError - def get_chisq(self) -> float: + def get_chisq(self, + reduced: bool = False, + ) -> float: """ Get the chi-squared value of the retrieval. - - .. note:: - Not yet implemented. """ - return self._retrieval_object.find_chisum(self.values) + return self._retrieval_object.find_chisum(self.values, reduced=reduced, N_eff=self.N_eff) + + def get_ks_p_value(self) -> float: + """ + Get the p-value from the Kolmogorov-Smirnov test of the whitened residuals. + """ + r_w = self._retrieval_object.retrieval_input.calculate_whitened_residuals(self.values) + _, pvalue = kstest(r_w, 'norm') + return pvalue diff --git a/curepy/retrieval_methods/base.py b/curepy/retrieval_methods/base.py index 7a30a75..9154cba 100644 --- a/curepy/retrieval_methods/base.py +++ b/curepy/retrieval_methods/base.py @@ -105,6 +105,8 @@ def find_chisum( self, theta: np.ndarray, repeat_dims: List[int] = [], + reduced: bool = False, + N_eff: int = None, ) -> float: """ Compute the chi-squared cost between the forward model and observations. @@ -127,8 +129,15 @@ def find_chisum( ).flatten() ) diff = modelled_data - self.retrieval_input.measurement_obj.y_flat - - # Only normalize by u_y_flat if it's available + + #import comet_maths as cm + #u_syst_rel = self.retrieval_input.measurement_obj.u_y_syst/self.retrieval_input.measurement_obj.y_flat + #u_syst = modelled_data * u_syst_rel + #u_rand = self.retrieval_input.measurement_obj.u_y_rand + #C_tot = cm.convert_corr_to_cov(np.eye(len(u_rand)), u_rand) + cm.convert_corr_to_cov(np.ones((len(u_syst), len(u_syst))), u_syst) + #s, d = np.linalg.slogdet(C_tot) + #return diff.T @ np.linalg.inv(C_tot) @ diff - (s * d) + #Only normalize by u_y_flat if it's available if self.retrieval_input.measurement_obj.u_y_flat is not None: diff_norm = diff / self.retrieval_input.measurement_obj.u_y_flat else: @@ -142,8 +151,10 @@ def find_chisum( else: if len(repeat_dims) == 0: - y = self.retrieval_input.measurement_obj.W @ diff_norm + W = self.retrieval_input.measurement_obj.W + y = W @ diff_norm chisq = y.T @ y + elif len(repeat_dims) == 1: sum = 0 for i in range(diff.shape[repeat_dims[0]]): @@ -163,7 +174,10 @@ def find_chisum( raise ValueError( "The chi-squared cost is negative, which should not be possible. Check the inputs and the measurement function for errors." ) - + + if reduced and N_eff: + return chisq/N_eff + return chisq def lnprob(self, theta: np.ndarray) -> float: diff --git a/curepy/retrieval_methods/mcmc.py b/curepy/retrieval_methods/mcmc.py index 222fa8c..a499c35 100644 --- a/curepy/retrieval_methods/mcmc.py +++ b/curepy/retrieval_methods/mcmc.py @@ -12,6 +12,8 @@ import comet_maths as cm + + class MCMC(BaseRetrieval): """MCMC retrieval object.""" @@ -50,6 +52,8 @@ def _run_retrieval( return_b_samples: bool = False, reshape_results: bool = True, corr_dims: Optional[Union[int, Sequence[int]]] = -99, + iterative_mismatch_covariance: bool = False, + modelled_covariance: bool = False, ) -> RetrievalResult: """ Run the MCMC retrieval and return the results. @@ -83,7 +87,9 @@ def _run_retrieval( # generate samples with MCMC if b_samples is None or self.retrieval_input.ancillary_obj.b_MC_steps == 1: - samples = self.run_MCMC(theta_0, self.nwalkers, self.steps, self.burn_in) + samples = self.run_MCMC(theta_0, self.nwalkers, self.steps, self.burn_in, + iterative_mismatch_covariance, + modelled_covariance) else: samples = np.zeros( ( @@ -114,7 +120,9 @@ def _run_retrieval( * (self.nwalkers * self.steps - self.burn_in) : (i + 1) * (self.nwalkers * self.steps - self.burn_in), :, - ] = self.run_MCMC(theta_0, self.nwalkers, self.steps, self.burn_in) + ] = self.run_MCMC(theta_0, self.nwalkers, self.steps, self.burn_in, + iterative_mismatch_covariance, + modelled_covariance) self.retrieval_input.ancillary_obj.b = b[:] @@ -134,6 +142,8 @@ def run_MCMC( nwalkers: int, steps: int, burn_in: int, + iterative_mismatch_covariance: bool = False, + modelled_covariance: bool = False, ) -> np.ndarray: """ Run :class:`emcee.EnsembleSampler` and return the post-burn-in chain. @@ -143,6 +153,7 @@ def run_MCMC( :param nwalkers: Number of ensemble walkers. :param steps: Total number of sampling steps. :param burn_in: Number of initial samples to discard. + :param iterative_mismatch_covariance: If ``True``, the mismatch covariance method is used. :returns: Array of post-burn-in samples with shape ``(nwalkers * steps - burn_in, ndim)``. """ @@ -154,8 +165,74 @@ def run_MCMC( sampler = emcee.EnsembleSampler(nwalkers, ndimw, self.lnprob, pool=p) else: sampler = emcee.EnsembleSampler(nwalkers, ndimw, self.lnprob) - sampler.run_mcmc(pos, steps, progress=self.progress) - + if not (iterative_mismatch_covariance or modelled_covariance): + sampler.run_mcmc(pos, steps, progress=self.progress) + if iterative_mismatch_covariance: + keep_running = True + #set random correlation for inital retrieval + store_corr, store_cholesky, store_W = self.retrieval_input.measurement_obj.corr_y, self.retrieval_input.measurement_obj.cholesky, self.retrieval_input.measurement_obj.W + self.retrieval_input.measurement_obj.corr_y, self.retrieval_input.measurement_obj.cholesky, self.retrieval_input.measurement_obj.W = self.retrieval_input.measurement_obj.return_corr_cholesky_whitening( + np.diag(np.diag(self.retrieval_input.measurement_obj.corr_y)) + ) + while keep_running: + #run MCMC with random correlation + sampler.run_mcmc(pos, steps, progress=self.progress) + #calculate the mismatch covariance matrix + C_model, N_eff = self.retrieval_input.return_mismatch_covariance(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], np.max(sampler.get_autocorr_time(quiet=True))) + C_model, N_eff = self.retrieval_input.return_mismatch_covariance(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], np.max(sampler.get_autocorr_time(quiet=True))) + if not np.allclose(np.zeros_like(C_model), C_model, rtol=0.01): + C_meas = cm.convert_corr_to_cov(store_corr, + self.retrieval_input.measurement_obj.u_y_flat + ) + C_total = C_model + C_meas + #rebuild the measurement object with the updated covariance matrix + self.retrieval_input.build_measurement( + self.retrieval_input.measurement_obj.y_flat, + cm.uncertainty_from_covariance(C_total), + corr_y = cm.correlation_from_covariance(C_total), + ) + theta_0 = self.generate_theta_0( + list(np.mean(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], axis = 0)) + ) + pos = [self.generate_theta_i(theta_0) for i in range(nwalkers)] + sampler.reset() + else: + theta_0 = self.generate_theta_0( + list(np.mean(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], axis = 0)) + ) + sampler.reset() + keep_running = False + + pos = [self.generate_theta_i(theta_0) for i in range(nwalkers)] + sampler.run_mcmc(pos, steps, progress=self.progress) + + if modelled_covariance: + #random for initial retrieval + store_corr, store_cholesky, store_W = self.retrieval_input.measurement_obj.corr_y, self.retrieval_input.measurement_obj.cholesky, self.retrieval_input.measurement_obj.W + self.retrieval_input.measurement_obj.corr_y, self.retrieval_input.measurement_obj.cholesky, self.retrieval_input.measurement_obj.W = self.retrieval_input.measurement_obj.return_corr_cholesky_whitening( + np.diag(np.diag(self.retrieval_input.measurement_obj.corr_y)) + ) + #run MCMC with random correlation + sampler.run_mcmc(pos, steps, progress=self.progress) + #model values + modelled_values = self.retrieval_input.measurement_function_obj.measurement_function_x(np.median(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], axis = 0), + self.retrieval_input.ancillary_obj.b) + #construct covariance + relative_unc = self.retrieval_input.measurement_obj.u_y_flat / self.retrieval_input.measurement_obj.y_flat + modelled_unc = relative_unc * modelled_values + #IMPORTANT: WHAT CORRELATION TO ASSUME + self.retrieval_input.build_measurement( + self.retrieval_input.measurement_obj.y_flat, + modelled_unc, + corr_y = store_corr, + ) + theta_0 = self.generate_theta_0( + list(np.mean(sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::], axis = 0)) + ) + sampler.reset() + pos = [self.generate_theta_i(theta_0) for i in range(nwalkers)] + sampler.run_mcmc(pos, steps, progress=self.progress) + samples = sampler.get_chain()[:, :, :].reshape((-1, ndimw))[burn_in::] return samples @@ -248,6 +325,7 @@ def analyse_samples( b_samples=b_samples if return_b_samples else None, x_names=self.retrieval_input.measurement_function_obj._input_quantities_names, retrieval_object=self, + N_eff=self.retrieval_input.measurement_obj.N_eff - len(medians) ) return outs diff --git a/examples/simple_quadratic_MCMC_example.py b/examples/simple_quadratic_MCMC_example.py index ddeb422..d258bf2 100644 --- a/examples/simple_quadratic_MCMC_example.py +++ b/examples/simple_quadratic_MCMC_example.py @@ -28,7 +28,7 @@ def quadratic(a, b, c, x, d): y = data + noise meas_func = MeasurementFunction(quadratic, [0.5, 0.2, -10]) -meas = Measurement(y, noise, corr_y=np.eye(len(x))) +meas = Measurement(y, noise, corr_y= 0.9*np.eye(len(x)) + 0.1 * np.ones((len(x), len(x)))) ancill = AncillaryParameter([x, d], [None, 1], [np.eye(len(x)), None], b_MC_steps=3) prior = Prior( ["normal"] * 3, @@ -38,9 +38,9 @@ def quadratic(a, b, c, x, d): inputs = RetrievalInput(meas_func, meas, ancill, prior) -ret = MCMC(100, 1000, 100) +ret = MCMC(100, 1000, 40000) -results = ret.run_retrieval(inputs, return_samples=True) +results = ret.run_retrieval(inputs, return_samples=True, iterative_mismatch_covariance=True) print(results.values) print(results.uncertainties) diff --git a/examples/test.png b/examples/test.png index 99fbbe7..ad9d821 100644 Binary files a/examples/test.png and b/examples/test.png differ