Exemplo n.º 1
0
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
Exemplo n.º 2
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
Exemplo n.º 3
0
Arquivo: base.py Projeto: vivienr/gwin
    def compute_acfs(cls,
                     fp,
                     start_index=None,
                     end_index=None,
                     per_walker=False,
                     walkers=None,
                     parameters=None):
        """Computes the autocorrleation function of the model params in the
        given file.

        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
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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.

        Returns
        -------
        FieldArray
            A ``FieldArray`` of the ACF vs iteration for each parameter. If
            `per-walker` is True, the FieldArray will have shape
            ``nwalkers x niterations``.
        """
        acfs = {}
        if parameters is None:
            parameters = fp.variable_params
        if isinstance(parameters, str) or isinstance(parameters, unicode):
            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 = [
                    cls.compute_acfs(fp,
                                     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 = cls.read_samples(fp,
                                           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 FieldArray.from_kwargs(**acfs)
Exemplo n.º 4
0
    def compute_acf(cls, filename, start_index=None, end_index=None,
                    per_walker=False, walkers=None, parameters=None):
        """Computes the autocorrleation function of the model params in the
        given file.

        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 : {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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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.

        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 cls._io(filename, 'r') as fp:
            if parameters is None:
                parameters = fp.variable_params
            if isinstance(parameters, str) or isinstance(parameters, unicode):
                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 = [
                        cls.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
Exemplo n.º 5
0
    def compute_acfs(cls, fp, start_index=None, end_index=None,
                     per_walker=False, walkers=None, parameters=None):
        """Computes the autocorrleation function of the variable args in the
        given file.

        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
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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 variable args.

        Returns
        -------
        FieldArray
            A ``FieldArray`` of the ACF vs iteration for each parameter. If
            `per-walker` is True, the FieldArray will have shape
            ``nwalkers x niterations``.
        """
        acfs = {}
        if parameters is None:
            parameters = fp.variable_args
        if isinstance(parameters, str) or isinstance(parameters, unicode):
            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 = [cls.compute_acfs(fp, 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 = cls.read_samples(fp, 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 FieldArray.from_kwargs(**acfs)
Exemplo n.º 6
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
Exemplo n.º 7
0
    def compute_acfs(cls,
                     fp,
                     start_index=None,
                     end_index=None,
                     per_walker=False,
                     walkers=None,
                     parameters=None,
                     temps=None):
        """Computes the autocorrleation function of the variable args in the
        given file.

        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
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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 variable args.
        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
        -------
        FieldArray
            A ``FieldArray`` of the ACF vs iteration for each parameter. If
            `per-walker` is True, the FieldArray will have shape
            ``ntemps x nwalkers x niterations``. Otherwise, the returned
            array will have shape ``ntemps x niterations``.
        """
        acfs = {}
        if parameters is None:
            parameters = fp.variable_args
        if isinstance(parameters, str) or isinstance(parameters, unicode):
            parameters = [parameters]
        if isinstance(temps, int):
            temps = [temps]
        elif temps == 'all':
            temps = numpy.arange(fp.ntemps)
        elif temps is None:
            temps = [0]
        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 = [
                        cls.compute_acfs(fp,
                                         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 = cls.read_samples(fp,
                                               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
            # FIXME: the following if/else can be condensed to a single line
            # using numpy.stack, once the version requirements are bumped to
            # numpy >= 1.10
            if per_walker:
                nw, ni = subacfs[0].shape
                acfs[param] = numpy.zeros((len(temps), nw, ni), dtype=float)
                for tk in range(len(temps)):
                    acfs[param][tk, ...] = subacfs[tk]
            else:
                acfs[param] = numpy.vstack(subacfs)
        return FieldArray.from_kwargs(**acfs)
Exemplo n.º 8
0
    def compute_acfs(cls, fp, start_index=None, end_index=None,
                     per_walker=False, walkers=None, parameters=None,
                     temps=None):
        """Computes the autocorrleation function of the variable args in the
        given file.

        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
        -----------
        fp : InferenceFile
            An open file handler to read the samples from.
        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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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 variable args.
        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
        -------
        FieldArray
            A ``FieldArray`` of the ACF vs iteration for each parameter. If
            `per-walker` is True, the FieldArray will have shape
            ``ntemps x nwalkers x niterations``. Otherwise, the returned
            array will have shape ``ntemps x niterations``.
        """
        acfs = {}
        if parameters is None:
            parameters = fp.variable_args
        if isinstance(parameters, str) or isinstance(parameters, unicode):
            parameters = [parameters]
        if isinstance(temps, int):
            temps = [temps]
        elif temps == 'all':
            temps = numpy.arange(fp.ntemps)
        elif temps is None:
            temps = [0]
        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 = [cls.compute_acfs(fp, 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 = cls.read_samples(fp, 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
            # FIXME: the following if/else can be condensed to a single line
            # using numpy.stack, once the version requirements are bumped to
            # numpy >= 1.10
            if per_walker:
                nw, ni = subacfs[0].shape
                acfs[param] = numpy.zeros((len(temps), nw, ni), dtype=float)
                for tk in range(len(temps)):
                    acfs[param][tk,...] = subacfs[tk]
            else:
                acfs[param] = numpy.vstack(subacfs)
        return FieldArray.from_kwargs(**acfs)
Exemplo n.º 9
0
    def compute_acf(cls, filename, start_index=None, end_index=None,
                    per_walker=False, walkers=None, parameters=None,
                    temps=None):
        """Computes the autocorrleation function of the model params in the
        given file.

        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 : {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.
        per_walker : optional, bool
            Return the ACF for each walker separately. Default is False.
        walkers : optional, int or array
            Calculate the ACF using only the given walkers. If None (the
            default) all walkers will be used.
        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 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 cls._io(filename, 'r') as fp:
            if parameters is None:
                parameters = fp.variable_params
            if isinstance(parameters, str) or isinstance(parameters, unicode):
                parameters = [parameters]
            if isinstance(temps, int):
                temps = [temps]
            elif temps == 'all':
                temps = numpy.arange(fp.ntemps)
            elif temps is None:
                temps = [0]
            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 = [cls.compute_acfs(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