How to use the getdist.chains.WeightedSampleError function in getdist

To help you get started, we’ve selected a few getdist examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cmbant / getdist / getdist / chains.py View on Github external
def thin_indices(self, factor, weights=None):
        """
        Indices to make single weight 1 samples. Assumes integer weights.

        :param factor: The factor to thin by, should be int.
        :param weights: The weights to thin, None if this should use the weights stored in the object.
        :return: array of indices of samples to keep
        """
        if weights is None:  weights = self.weights
        numrows = len(weights)
        norm1 = np.sum(weights)
        weights = weights.astype(np.int)
        norm = np.sum(weights)

        if abs(norm - norm1) > 1e-4:
            raise WeightedSampleError('Can only thin with integer weights')
        if factor != int(factor):
            raise WeightedSampleError('Thin factor must be integer')
        factor = int(factor)
        if factor >= np.max(weights):
            cumsum = np.cumsum(weights) // factor
            # noinspection PyTupleAssignmentBalance
            _, thin_ix = np.unique(cumsum, return_index=True)
        else:
            tot = 0
            i = 0
            thin_ix = np.empty(norm // factor, dtype=np.int)
            ix = 0
            mult = weights[i]
            while i < numrows:
                if mult + tot < factor:
                    tot += mult
github cmbant / getdist / getdist / chains.py View on Github external
def _getParamIndices(self):
        """
        Gets the indices of the params.

        :return: A dict mapping the param name to the parameter index.
        """
        if self.samples is not None and len(self.paramNames.names) != self.n:
            raise WeightedSampleError("paramNames size does not match number of parameters in samples")
        index = dict()
        for i, name in enumerate(self.paramNames.names):
            index[name.name] = i
        self.index = index
        return self.index
github cmbant / getdist / getdist / chains.py View on Github external
"min_weight_ratio": self.min_weight_ratio}
        if hasattr(files_or_samples, '__len__') and not len(files_or_samples) or files_or_samples is None:
            raise ValueError('files_or_samples empty in loadChains')
        if isinstance(files_or_samples, six.string_types) or isinstance(files_or_samples[0], six.string_types):
            # From files
            if weights is not None or loglikes is not None:
                raise ValueError('weights and loglikes not needed reading from file')
            if isinstance(files_or_samples, six.string_types):
                files_or_samples = [files_or_samples]
            self.name_tag = self.name_tag or os.path.basename(root)
            for fname in files_or_samples:
                if print_load_details:
                    print(fname)
                try:
                    self.chains.append(WeightedSamples(fname, **WSkwargs))
                except WeightedSampleError:
                    if print_load_details:
                        print('Ignored file %s (likely empty)' % fname)
            nchains = len(self.chains)
            if not nchains:
                raise WeightedSampleError('loadChains - no chains found for ' + root)
        else:
            # From arrays
            def array_dimension(a):
                # Dimension for numpy or list/tuple arrays, not very safe (does not work if string elements)
                d = 0
                while True:
                    try:
                        a = a[0]
                        d += 1
                    except:
                        return d
github cmbant / getdist / getdist / chains.py View on Github external
def _makeParamvec(self, par):
        if isinstance(par, _int_types):
            if 0 <= par < self.n:
                return self.samples[:, par]
            elif par == -1:
                if self.loglikes is None:
                    raise WeightedSampleError('Samples do not have logLikes (par=-1)' % par)
                return self.loglikes
            elif par == -2:
                return self.weights
            else:
                raise WeightedSampleError('Parameter %i does not exist' % par)
        return par
github cmbant / getdist / getdist / mcsamples.py View on Github external
import six
from scipy.stats import norm
import getdist
from getdist import chains, types, covmat, ParamInfo, IniFile, ParamNames, cobaya_interface
from getdist.densities import Density1D, Density2D, DensityND
from getdist.densities import getContourLevels as getOtherContourLevels
from getdist.chains import Chains, chainFiles, lastModified, WeightedSampleError, ParamError
from getdist.convolve import convolve1D, convolve2D
from getdist.cobaya_interface import MCSamplesFromCobaya
import getdist.kde_bandwidth as kde
from getdist.parampriors import ParamBounds

pickle_version = 22


class MCSamplesError(WeightedSampleError):
    """
    An Exception that is raised when there is an error inside the MCSamples class.
    """
    pass


class SettingError(MCSamplesError):
    """
    An Exception that indicates bad settings.
    """
    pass


class BandwidthError(MCSamplesError):
    """
    An Exception that indicate KDE bandwidth failure.
github cmbant / getdist / getdist / chains.py View on Github external
:param samples: array of parameter values for each sample, passed to :func:`setSamples`
        :param weights: array of weights
        :param loglikes: array of -log(Likelihood)
        :param name_tag: The name of this instance.
        :param label: latex label for these samples
        :param files_are_chains: use False if the samples file (filename) does not start with two columns giving
                                 weights and -log(Likelihoods)
        :param min_weight_ratio: remove samples with weight less than min_weight_ratio times the maximum weight
        """

        self.precision = '%.8e'
        self.min_weight_ratio = min_weight_ratio
        if filename:
            cols = loadNumpyTxt(filename, skiprows=ignore_rows)
            if not len(cols):
                raise WeightedSampleError('Empty chain: %s' % filename)
            self.setColData(cols, are_chains=files_are_chains)
            self.name_tag = name_tag or os.path.basename(filename)
        else:
            self.setSamples(slice_or_none(samples, ignore_rows),
                            slice_or_none(weights, ignore_rows),
                            slice_or_none(loglikes, ignore_rows))
            self.name_tag = name_tag
            if samples is not None and int(ignore_rows):
                if print_load_details:
                    print('Removed %s lines as burn in' % ignore_rows)
        self.label = label
        self.needs_update = True
github cmbant / getdist / getdist / chains.py View on Github external
def _makeParamvec(self, par):
        if isinstance(par, _int_types):
            if 0 <= par < self.n:
                return self.samples[:, par]
            elif par == -1:
                if self.loglikes is None:
                    raise WeightedSampleError('Samples do not have logLikes (par=-1)' % par)
                return self.loglikes
            elif par == -2:
                return self.weights
            else:
                raise WeightedSampleError('Parameter %i does not exist' % par)
        return par