How to use the emcee.autocorr.AutocorrError function in emcee

To help you get started, we’ve selected a few emcee 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 dfm / emcee / tests / unit / test_autocorr.py View on Github external
def test_too_short(seed=1234, ndim=3, N=100):
    x = get_chain(seed=seed, ndim=ndim, N=N)
    with pytest.raises(AutocorrError):
        integrated_time(x)
    tau = integrated_time(x, quiet=True)  # NOQA
github manoharan-lab / holopy / holopy / inference / mcmc.py View on Github external
def _repr_html_(self):
        results = "{}".format(", ".join(["{}:{}".format(n, v._repr_latex_()) for n, v in zip(self._names, list(self.values()))]))
        try:
            indep_steps = self.approx_independent_steps
            indep_steps_str = "\n~ {} of which are independent".format(indep_steps)
        except emcee.autocorr.AutocorrError:
            indep_steps_str = ""
        block = """<h4>{s.__class__.__name__}</h4> {results}
{s.sampler.chain.shape[0]} walkers
{s.n_steps} Steps{indep_steps}
Acceptance Fraction: {s.acceptance_fraction}
        """.format(s=self, results=results, indep_steps=indep_steps_str)
        return "<br>".join(block.split('\n'))
github lmfit / lmfit-py / lmfit / minimizer.py View on Github external
# work out correlation coefficients
            corrcoefs = np.corrcoef(flatchain.T)

            for i, var_name in enumerate(result.var_names):
                for j, var_name2 in enumerate(result.var_names):
                    if i != j:
                        result.params[var_name].correl[var_name2] = corrcoefs[i, j]

        result.chain = np.copy(chain)
        result.lnprob = np.copy(lnprobability)
        result.errorbars = True
        result.nvarys = len(result.var_names)
        result.nfev = nwalkers*steps
        try:
            result.acor = self.sampler.get_autocorr_time()
        except AutocorrError as e:
            print(str(e))
            pass
        result.acceptance_fraction = self.sampler.acceptance_fraction

        # Calculate the residual with the "best fit" parameters
        out = self.userfcn(params, *self.userargs, **self.userkws)
        result.residual = _nan_policy(out, nan_policy=self.nan_policy,
                                      handle_inf=False)

        # If uncertainty was automatically estimated, weight the residual properly
        if (not is_weighted) and (result.residual.size > 1):
            if '__lnsigma' in params:
                result.residual = result.residual/np.exp(params['__lnsigma'].value)

        # Calculate statistics for the two standard cases:
        if isinstance(result.residual, ndarray) or (float_behavior == 'chi2'):
github guillochon / MOSFiT / mosfit / samplers / ensembler.py View on Github external
axis=2) if len(self._all_chain) else
                            sampler.chain[:, :, :li + 1:slr, :])
                        for a in range(acorc, 1, -1):
                            ms = self._burn_in
                            if ms >= self._emi - low:
                                break
                            try:
                                acorts = sampler.get_autocorr_time(
                                    chain=cur_chain, low=low, c=a,
                                    min_step=int(np.round(float(ms) / sli)),
                                    max_walkers=5, fast=True)
                                acort = max([
                                    max(x)
                                    for x in acorts
                                ])
                            except AutocorrError:
                                continue
                            else:
                                self._aa = a
                                self._aacort = acort * sli
                                self._ams = ms
                                break
                        self._acor = [self._aacort, self._aa, self._ams]

                        self._actc = int(np.ceil(self._aacort / sli))
                        actn = np.int(
                            float(self._emi - self._ams) / self._actc)

                        if (self._cc is not None and
                            actn >= self._cc and
                                self._emi > self._iterations):
                            prt.message('converged')
github guillochon / MOSFiT / mosfit / mossampler.py View on Github external
# N-dimensional case.
                m[axis] = slice(1, M)
                tau = 1 + 2 * np.sum(f[m], axis=axis)

            # Accept the window size if it satisfies the convergence criterion.
            if np.all(tau > 1.0) and M > c * tau.max():
                if full_output:
                    return tau, M
                return tau

            # If the autocorrelation time is too long to be estimated reliably
            # from the chain, it should fail.
            if c * tau.max() >= size:
                break

        raise AutocorrError("The chain is too short to reliably estimate "
                            "the autocorrelation time")
github guillochon / MOSFiT / mosfit / mossampler.py View on Github external
Returns:
            float or array: An estimate of the integrated autocorrelation time
                of the time series ``x`` computed along the axis ``axis``.
            Optional[int]: The final window size that was used. Only returned
                if ``full_output`` is ``True``.

        Raises
            AutocorrError: If the autocorrelation time can't be reliably
                estimated from the chain. This normally means that the chain
                is too short.

        """
        size = 0.5 * x.shape[axis]
        if int(c * low) >= size:
            raise AutocorrError("The chain is too short")

        # Compute the autocorrelation function.
        f = function_1d(x)

        # Check the dimensions of the array.
        oned = len(f.shape) == 1
        m = [slice(None), ] * len(f.shape)

        # Loop over proposed window sizes until convergence is reached.
        if high is None:
            high = int(size / c)
        for M in np.arange(low, high, step).astype(int):
            # Compute the autocorrelation time with the given window.
            if oned:
                # Special case 1D for simplicity.
                tau = 1 + 2 * np.sum(f[1:M])
github guillochon / MOSFiT / mosfit / fitter.py View on Github external
axis=2) if len(all_chain) else
                            sampler.chain[:, :, :li + 1:slr, :])
                        for a in range(acorc, 1, -1):
                            ms = self._burn_in
                            if ms >= emi - low:
                                break
                            try:
                                acorts = sampler.get_autocorr_time(
                                    chain=cur_chain, low=low, c=a,
                                    min_step=int(np.round(float(ms) / sli)),
                                    max_walkers=5, fast=True)
                                acort = max([
                                    max(x)
                                    for x in acorts
                                ])
                            except AutocorrError:
                                continue
                            else:
                                aa = a
                                aacort = acort * sli
                                ams = ms
                                break
                        acor = [aacort, aa, ams]

                        actc = int(np.ceil(aacort / sli))
                        actn = np.int(float(emi - ams) / actc)

                        if (convergence_type == 'acor' and
                            convergence_criteria is not None and
                            actn >= convergence_criteria and
                                emi > iterations):
                            prt.message('converged')