Example #1
0
    def checkpoint(self):
        """Checkpoint function for dynesty sampler
        """
        with loadfile(self.checkpoint_file, 'a') as fp:
            fp.write_random_state()

            # Dynesty has its own __getstate__ which deletes
            # random state information and the pool
            saved = {}
            for key in self.no_pickle:
                if hasattr(self._sampler, key):
                    saved[key] = getattr(self._sampler, key)
                    setattr(self._sampler, key, None)

            # For the dynamic sampler, we must also handle the internal
            # sampler object
            #saved_internal = {}
            #if self.nlive < 0:
            #    for key in self.no_pickle:
            #        if hasattr(self._sampler.sampler, key):
            #            saved[key] = getattr(self._sampler.sampler, key)
            #            setattr(self._sampler.sampler, key, None)

            #for key in self._sampler.__dict__:
            #    print(key, type(self._sampler.__dict__[key]))

            #for key in self._sampler.sampler.__dict__:
            #    print(key, type(self._sampler.sampler.__dict__[key]))

            fp.write_pickled_data_into_checkpoint_file(self._sampler)

        # Restore properties that couldn't be pickled if we are continuing
        for key in saved:
            setattr(self._sampler, key, saved[key])
Example #2
0
def ensemble_compute_acl(filename,
                         start_index=None,
                         end_index=None,
                         min_nsamples=10):
    """Computes the autocorrleation length for a parallel tempered, ensemble
    MCMC.

    Parameter values are averaged over all walkers at each iteration and
    temperature.  The ACL is then calculated over the averaged chain.

    Parameters
    -----------
    filename : str
        Name of a samples file to compute ACLs for.
    start_index : int, optional
        The start index to compute the acl from. If None (the default), will
        try to use the number of burn-in iterations in the file; otherwise,
        will start at the first sample.
    end_index : int, optional
        The end index to compute the acl to. If None, will go to the end
        of the current iteration.
    min_nsamples : int, optional
        Require a minimum number of samples to compute an ACL. If the
        number of samples per walker is less than this, will just set to
        ``inf``. Default is 10.

    Returns
    -------
    dict
        A dictionary of ntemps-long arrays of the ACLs of each parameter.
    """
    acls = {}
    with loadfile(filename, 'r') as fp:
        if end_index is None:
            end_index = fp.niterations
        tidx = numpy.arange(fp.ntemps)
        for param in fp.variable_params:
            these_acls = numpy.zeros(fp.ntemps)
            for tk in tidx:
                samples = fp.read_raw_samples(param,
                                              thin_start=start_index,
                                              thin_interval=1,
                                              thin_end=end_index,
                                              temps=tk,
                                              flatten=False)[param]
                # contract the walker dimension using the mean, and flatten
                # the (length 1) temp dimension
                samples = samples.mean(axis=1)[0, :]
                if samples.size < min_nsamples:
                    acl = numpy.inf
                else:
                    acl = autocorrelation.calculate_acl(samples)
                if acl <= 0:
                    acl = numpy.inf
                these_acls[tk] = acl
            acls[param] = these_acls
        maxacl = numpy.array(list(acls.values())).max()
        logging.info("ACT: %s", str(maxacl * fp.thinned_by))
    return acls
def compute_acf(filename, start_index=None, end_index=None,
                chains=None, parameters=None, temps=None):
    """Computes the autocorrleation function for independent MCMC chains with
    parallel tempering.

    Parameters
    -----------
    filename : str
        Name of a samples file to compute ACFs for.
    start_index : int, optional
        The start index to compute the acl from. If None (the default),
        will try to use the burn in iteration for each chain;
        otherwise, will start at the first sample.
    end_index : {None, int}
        The end index to compute the acl to. If None, will go to the end
        of the current iteration.
    chains : optional, int or array
        Calculate the ACF for only the given chains. If None (the
        default) ACFs for all chains will be estimated.
    parameters : optional, str or array
        Calculate the ACF for only the given parameters. If None (the
        default) will calculate the ACF for all of the model params.
    temps : optional, (list of) int or 'all'
        The temperature index (or list of indices) to retrieve. If None
        (the default), the ACF will only be computed for the coldest (= 0)
        temperature chain. To compute an ACF for all temperates pass 'all',
        or a list of all of the temperatures.

    Returns
    -------
    dict :
        Dictionary parameter name -> ACF arrays. The arrays have shape
        ``ntemps x nchains x niterations``.
    """
    acfs = {}
    with loadfile(filename, 'r') as fp:
        if parameters is None:
            parameters = fp.variable_params
        if isinstance(parameters, string_types):
            parameters = [parameters]
        temps = _get_temps_idx(fp, temps)
        if chains is None:
            chains = numpy.arange(fp.nchains)
        for param in parameters:
            subacfs = []
            for tk in temps:
                subsubacfs = []
                for ci in chains:
                    samples = fp.read_raw_samples(
                        param, thin_start=start_index, thin_interval=1,
                        thin_end=end_index, chains=ci, temps=tk)[param]
                    thisacf = autocorrelation.calculate_acf(samples).numpy()
                    subsubacfs.append(thisacf)
                # stack the chains
                subacfs.append(subsubacfs)
            # stack the temperatures
            acfs[param] = numpy.stack(subacfs)
    return acfs
Example #4
0
def ensemble_compute_acl(filename,
                         start_index=None,
                         end_index=None,
                         min_nsamples=10):
    """Computes the autocorrleation length for an ensemble MCMC.

    Parameter values are averaged over all walkers at each iteration.
    The ACL is then calculated over the averaged chain. If an ACL cannot
    be calculated because there are not enough samples, it will be set
    to ``inf``.

    Parameters
    -----------
    filename : str
        Name of a samples file to compute ACLs for.
    start_index : int, optional
        The start index to compute the acl from. If None, will try to use
        the number of burn-in iterations in the file; otherwise, will start
        at the first sample.
    end_index : int, optional
        The end index to compute the acl to. If None, will go to the end
        of the current iteration.
    min_nsamples : int, optional
        Require a minimum number of samples to compute an ACL. If the
        number of samples per walker is less than this, will just set to
        ``inf``. Default is 10.

    Returns
    -------
    dict
        A dictionary giving the ACL for each parameter.
    """
    acls = {}
    with loadfile(filename, 'r') as fp:
        for param in fp.variable_params:
            samples = fp.read_raw_samples(param,
                                          thin_start=start_index,
                                          thin_interval=1,
                                          thin_end=end_index,
                                          flatten=False)[param]
            samples = samples.mean(axis=0)
            # if < min number of samples, just set to inf
            if samples.size < min_nsamples:
                acl = numpy.inf
            else:
                acl = autocorrelation.calculate_acl(samples)
            if acl <= 0:
                acl = numpy.inf
            acls[param] = acl
        maxacl = numpy.array(list(acls.values())).max()
        logging.info("ACT: %s", str(maxacl * fp.thin_interval))
    return acls
Example #5
0
    def resume_from_checkpoint(self):
        try:
            with loadfile(self.checkpoint_file, 'r') as fp:
                sampler = fp.read_pickled_data_from_checkpoint_file()

                for key in sampler.__dict__:
                    if key not in self.no_pickle:
                        value = getattr(sampler, key)
                        setattr(self._sampler, key, value)

            self.set_state_from_file(self.checkpoint_file)
            logging.info("Found valid checkpoint file: %s",
                         self.checkpoint_file)
        except Exception as e:
            print(e)
            logging.info("Failed to load checkpoint file")
Example #6
0
    def __init__(self, variable_params, posterior_file, nsamples, **kwargs):
        super(TestPosterior, self).__init__(variable_params, **kwargs)

        from pycbc.inference.io import loadfile  # avoid cyclic import
        logging.info('loading test posterior model')
        inf_file = loadfile(posterior_file)
        logging.info('reading samples')
        samples = inf_file.read_samples(variable_params)
        samples = numpy.array([samples[v] for v in variable_params])

        # choose only the requested amount of samples
        idx = numpy.arange(0, samples.shape[-1])
        idx = numpy.random.choice(idx, size=int(nsamples), replace=False)
        samples = samples[:, idx]

        logging.info('making kde with %s samples', samples.shape[-1])
        self.kde = stats.gaussian_kde(samples)
        logging.info('done initializing test posterior model')
Example #7
0
def ensemble_compute_acf(filename,
                         start_index=None,
                         end_index=None,
                         per_walker=False,
                         walkers=None,
                         parameters=None):
    """Computes the autocorrleation function for an ensemble MCMC.

    By default, parameter values are averaged over all walkers at each
    iteration. The ACF is then calculated over the averaged chain. An
    ACF per-walker will be returned instead if ``per_walker=True``.

    Parameters
    -----------
    filename : str
        Name of a samples file to compute ACFs for.
    start_index : int, optional
        The start index to compute the acl from. If None (the default), will
        try to use the number of burn-in iterations in the file; otherwise,
        will start at the first sample.
    end_index : int, optional
        The end index to compute the acl to. If None (the default), will go to
        the end of the current iteration.
    per_walker : bool, optional
        Return the ACF for each walker separately. Default is False.
    walkers : int or array, optional
        Calculate the ACF using only the given walkers. If None (the
        default) all walkers will be used.
    parameters : str or array, optional
        Calculate the ACF for only the given parameters. If None (the
        default) will calculate the ACF for all of the model params.

    Returns
    -------
    dict :
        Dictionary of arrays giving the ACFs for each parameter. If
        ``per-walker`` is True, the arrays will have shape
        ``nwalkers x niterations``.
    """
    acfs = {}
    with loadfile(filename, 'r') as fp:
        if parameters is None:
            parameters = fp.variable_params
        if isinstance(parameters, string_types):
            parameters = [parameters]
        for param in parameters:
            if per_walker:
                # just call myself with a single walker
                if walkers is None:
                    walkers = numpy.arange(fp.nwalkers)
                arrays = [
                    ensemble_compute_acf(filename,
                                         start_index=start_index,
                                         end_index=end_index,
                                         per_walker=False,
                                         walkers=ii,
                                         parameters=param)[param]
                    for ii in walkers
                ]
                acfs[param] = numpy.vstack(arrays)
            else:
                samples = fp.read_raw_samples(param,
                                              thin_start=start_index,
                                              thin_interval=1,
                                              thin_end=end_index,
                                              walkers=walkers,
                                              flatten=False)[param]
                samples = samples.mean(axis=0)
                acfs[param] = autocorrelation.calculate_acf(samples).numpy()
    return acfs
Example #8
0
def ensemble_compute_acf(filename,
                         start_index=None,
                         end_index=None,
                         per_walker=False,
                         walkers=None,
                         parameters=None,
                         temps=None):
    """Computes the autocorrleation function for a parallel tempered, ensemble
    MCMC.

    By default, parameter values are averaged over all walkers at each
    iteration. The ACF is then calculated over the averaged chain for each
    temperature. An ACF per-walker will be returned instead if
    ``per_walker=True``.

    Parameters
    ----------
    filename : str
        Name of a samples file to compute ACFs for.
    start_index : int, optional
        The start index to compute the acl from. If None (the default), will
        try to use the number of burn-in iterations in the file; otherwise,
        will start at the first sample.
    end_index : int, optional
        The end index to compute the acl to. If None (the default), will go to
        the end of the current iteration.
    per_walker : bool, optional
        Return the ACF for each walker separately. Default is False.
    walkers : int or array, optional
        Calculate the ACF using only the given walkers. If None (the
        default) all walkers will be used.
    parameters : str or array, optional
        Calculate the ACF for only the given parameters. If None (the
        default) will calculate the ACF for all of the model params.
    temps : (list of) int or 'all', optional
        The temperature index (or list of indices) to retrieve. If None
        (the default), the ACF will only be computed for the coldest (= 0)
        temperature chain. To compute an ACF for all temperates pass 'all',
        or a list of all of the temperatures.

    Returns
    -------
    dict :
        Dictionary of arrays giving the ACFs for each parameter. If
        ``per-walker`` is True, the arrays will have shape
        ``ntemps x nwalkers x niterations``. Otherwise, the returned array
        will have shape ``ntemps x niterations``.
    """
    acfs = {}
    with loadfile(filename, 'r') as fp:
        if parameters is None:
            parameters = fp.variable_params
        if isinstance(parameters, str):
            parameters = [parameters]
        temps = _get_temps_idx(fp, temps)
        for param in parameters:
            subacfs = []
            for tk in temps:
                if per_walker:
                    # just call myself with a single walker
                    if walkers is None:
                        walkers = numpy.arange(fp.nwalkers)
                    arrays = [
                        ensemble_compute_acf(filename,
                                             start_index=start_index,
                                             end_index=end_index,
                                             per_walker=False,
                                             walkers=ii,
                                             parameters=param,
                                             temps=tk)[param][0, :]
                        for ii in walkers
                    ]
                    # we'll stack all of the walker arrays to make a single
                    # nwalkers x niterations array; when these are stacked
                    # below, we'll get a ntemps x nwalkers x niterations
                    # array
                    subacfs.append(numpy.vstack(arrays))
                else:
                    samples = fp.read_raw_samples(param,
                                                  thin_start=start_index,
                                                  thin_interval=1,
                                                  thin_end=end_index,
                                                  walkers=walkers,
                                                  temps=tk,
                                                  flatten=False)[param]
                    # contract the walker dimension using the mean, and
                    # flatten the (length 1) temp dimension
                    samples = samples.mean(axis=1)[0, :]
                    thisacf = autocorrelation.calculate_acf(samples).numpy()
                    subacfs.append(thisacf)
            # stack the temperatures
            acfs[param] = numpy.stack(subacfs)
    return acfs
Example #9
0
def compute_acl(filename, start_index=None, end_index=None, min_nsamples=10):
    """Computes the autocorrleation length for independent MCMC chains with
    parallel tempering.

    ACLs are calculated separately for each chain.

    Parameters
    -----------
    filename : str
        Name of a samples file to compute ACLs for.
    start_index : {None, int}
        The start index to compute the acl from. If None, will try to use
        the number of burn-in iterations in the file; otherwise, will start
        at the first sample.
    end_index : {None, int}
        The end index to compute the acl to. If None, will go to the end
        of the current iteration.
    min_nsamples : int, optional
        Require a minimum number of samples to compute an ACL. If the
        number of samples per walker is less than this, will just set to
        ``inf``. Default is 10.

    Returns
    -------
    dict
        A dictionary of ntemps x nchains arrays of the ACLs of each
        parameter.
    """

    # following is a convenience function to calculate the acl for each chain
    # defined here so that we can use map for this below
    def _getacl(si):
        # si: the samples loaded for a specific chain; may have nans in it
        si = si[~numpy.isnan(si)]
        if len(si) < min_nsamples:
            acl = numpy.inf
        else:
            acl = autocorrelation.calculate_acl(si)
        if acl <= 0:
            acl = numpy.inf
        return acl

    acls = {}
    with loadfile(filename, 'r') as fp:
        tidx = numpy.arange(fp.ntemps)
        for param in fp.variable_params:
            these_acls = numpy.zeros((fp.ntemps, fp.nchains))
            for tk in tidx:
                samples = fp.read_raw_samples(param,
                                              thin_start=start_index,
                                              thin_interval=1,
                                              thin_end=end_index,
                                              temps=tk,
                                              flatten=False)[param]
                # flatten out the temperature
                samples = samples[0, ...]
                # samples now has shape nchains x maxiters
                if samples.shape[-1] < min_nsamples:
                    these_acls[tk, :] = numpy.inf
                else:
                    these_acls[tk, :] = list(map(_getacl, samples))
            acls[param] = these_acls
        # report the mean ACL: take the max over the temps and parameters
        act = acl_from_raw_acls(acls) * fp.thinned_by
        finite = act[numpy.isfinite(act)]
        logging.info("ACTs: min %s, mean (of finite) %s, max %s",
                     str(act.min()),
                     str(finite.mean() if finite.size > 0 else numpy.inf),
                     str(act.max()))
    return acls