当前位置: 首页>>代码示例>>Python>>正文


Python corner.corner方法代码示例

本文整理汇总了Python中corner.corner方法的典型用法代码示例。如果您正苦于以下问题:Python corner.corner方法的具体用法?Python corner.corner怎么用?Python corner.corner使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在corner的用法示例。


在下文中一共展示了corner.corner方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot_corner

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def plot_corner(xs, ps=None, ms=None, filename=None, **kwargs):
    """
    Produce a corner plot
    """
    import corner
    mask = [i for i in range(xs.shape[-1]) if not all(xs[:,i]==xs[0,i]) ]
    fig  = corner.corner(xs[:,mask], color='k', hist_kwargs={'density':True}, **kwargs)
    if ps is not None:
        mask = [i for i in range(ps.shape[-1]) if not all(ps[:,i]==ps[0,i]) ]
        corner.corner(ps[:,mask], fig = fig, color='g', hist_kwargs={'density':True}, **kwargs)
    if ms is not None:
        mask = [i for i in range(ms.shape[-1]) if not all(ms[:,i]==ms[0,i]) ]
        corner.corner(ms[:,mask], fig = fig, color='r', hist_kwargs={'density':True}, **kwargs)
    if filename is not None:
        plt.savefig(filename,bbox_inches='tight')
    plt.close() 
开发者ID:johnveitch,项目名称:cpnest,代码行数:18,代码来源:plot.py

示例2: plot

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def plot(self):
        """
        Make and either save or display the corner plot
        """

        f = rcParams['font.size']
        rcParams['font.size'] = 12

        _ = corner.corner(
            self.chains[self.labels], labels=self.texlabels, label_kwargs={"fontsize": 14},
            plot_datapoints=False, bins=30, quantiles=[0.16, 0.5, 0.84],
            show_titles=True, title_kwargs={"fontsize": 14}, smooth=True
        )
    
        if self.saveplot is not None:
            pl.savefig(self.saveplot, dpi=150)
            print("Corner plot saved to %s" % self.saveplot)
        else:
            pl.show()

        rcParams['font.size'] = f 
开发者ID:California-Planet-Search,项目名称:radvel,代码行数:23,代码来源:mcmc_plots.py

示例3: plot_corner

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def plot_corner(self, filename="multinest_corner.png"):
        plt.clf()
        if self.retrieval_type == "dynesty":
            fig = corner.corner(self.samples, weights=self.weights,
                          range=[0.99] * self.samples.shape[1],
                          labels=self.fit_info.fit_param_names)
            fig.savefig(filename)
        elif self.retrieval_type == "emcee":
            fig = corner.corner(self.flatchain,
                                range=[0.99] * self.flatchain.shape[1],
                                labels=self.fit_info.fit_param_names)
            fig.savefig(filename)
        else:
            assert(False) 
开发者ID:ideasrule,项目名称:platon,代码行数:16,代码来源:retrieval_result.py

示例4: corner_plot

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def corner_plot(self, renamed_parameters=None, **kwargs):
        """
        Produce the corner plot showing the marginal distributions in one and two directions.

        :param renamed_parameters: a python dictionary of parameters to rename.
             Useful when e.g. spectral indices in models have different names but you wish to compare them. Format is
             {'old label': 'new label'}, where 'old label' is the full path of the parameter
        :param kwargs: arguments to be passed to the corner function
        :return: a matplotlib.figure instance
        """

        assert (
            len(list(self._free_parameters.keys()))
            == self._samples_transposed.T[0].shape[0]
        ), ("Mismatch between sample" " dimensions and number of free" " parameters")

        labels = []
        priors = []

        for i, (parameter_name, parameter) in enumerate(self._free_parameters.items()):

            short_name = parameter_name.split(".")[-1]

            labels.append(short_name)

            # If the user has provided custom names, use them

            if renamed_parameters is not None:

                if parameter.path in renamed_parameters:

                    labels[-1] = renamed_parameters[parameter.path]

            priors.append(self._optimized_model.parameters[parameter_name].prior)

        # default arguments
        default_args = {
            "show_titles": True,
            "title_fmt": ".2g",
            "labels": labels,
            "quantiles": [0.16, 0.50, 0.84],
        }

        # Update the default arguents with the one provided (if any). Note that .update also adds new keywords,
        # if they weren't present in the original dictionary, so you can use any option in kwargs, not just
        # the one in default_args
        default_args.update(kwargs)

        fig = corner(self._samples_transposed.T, **default_args)

        return fig 
开发者ID:threeML,项目名称:threeML,代码行数:53,代码来源:analysis_results.py

示例5: __init__

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def __init__(self, chains, P, saveplot=None):

        self.chains = chains
        self.saveplot = saveplot

        if 'planet_letters' in dir(P):
            planet_letters = P.planet_letters
        else:
            planet_letters = {1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k'}

        # Determine which columns to include in corner plot
        self.labels = []
        self.texlabels = []
        self.units = []
        for i in np.arange(1, P.nplanets + 1, 1):
            letter = planet_letters[i]

            for key in 'mpsini rhop a'.split():
                label = '{}{}'.format(key, i)
                
                is_column = list(self.chains.columns).count(label) == 1
                if not is_column:
                    continue
                
                null_column = self.chains.isnull().any().loc[label]
                if null_column:
                    continue

                tl = texlabel(label, letter)

                # add units to label
                if key == 'mpsini':
                    unit = "M$_{\\oplus}$"
                    if np.median(self.chains[label]) > 100:
                        unit = "M$_{\\rm Jup}$"
                        self.chains[label] *= 0.00315
                    if np.median(self.chains[label]) > 100:
                        unit = "M$_{\\odot}$"
                        self.chains[label] *= 0.000954265748
                elif key == 'rhop':
                    unit = " g cm$^{-3}$"
                elif key == 'a':
                    unit = " AU"
                else:
                    unit = " "

                self.units.append(unit)
                self.labels.append(label)
                self.texlabels.append(tl) 
开发者ID:California-Planet-Search,项目名称:radvel,代码行数:51,代码来源:mcmc_plots.py

示例6: plot_MCMC_chains

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def plot_MCMC_chains(sampler):
    
    chain = sampler.get_chain()
    log_prob = sampler.get_log_prob()
    
    #plot chains; emcee_3.0.0 format = (nsteps, nwalkers, nparameters)
    fig, axes = plt.subplots(config.BASEMENT.ndim+1, 1, figsize=(6,3*config.BASEMENT.ndim) )
    
    #::: plot the lnprob_values; emcee_3.0.0 format = (nsteps, nwalkers)
    axes[0].plot(log_prob, '-', rasterized=True)
    axes[0].axvline( 1.*config.BASEMENT.settings['mcmc_burn_steps']/config.BASEMENT.settings['mcmc_thin_by'], color='k', linestyle='--' )
    mini = np.min(log_prob[int(1.*config.BASEMENT.settings['mcmc_burn_steps']/config.BASEMENT.settings['mcmc_thin_by']):,:])
    maxi = np.max(log_prob[int(1.*config.BASEMENT.settings['mcmc_burn_steps']/config.BASEMENT.settings['mcmc_thin_by']):,:])
    axes[0].set( title='lnprob', xlabel='steps', rasterized=True,
                 ylim=[mini, maxi] )
    axes[0].set_xticklabels( [int(label) for label in axes[0].get_xticks()*config.BASEMENT.settings['mcmc_thin_by']] )
    
    #:::plot all chains of parameters
    for i in range(config.BASEMENT.ndim):
        ax = axes[i+1]
        ax.set(title=config.BASEMENT.fitkeys[i], xlabel='steps')
        ax.plot(chain[:,:,i], '-', rasterized=True)
        ax.axvline( 1.*config.BASEMENT.settings['mcmc_burn_steps']/config.BASEMENT.settings['mcmc_thin_by'], color='k', linestyle='--' )
#        ax.set_xticks(ax.get_xticks()[::2])
        ax.set_xticklabels( [int(label) for label in ax.get_xticks()*config.BASEMENT.settings['mcmc_thin_by']] )

    plt.tight_layout()
    return fig, axes
    
    
    
###############################################################################
#::: plot the MCMC corner plot
###############################################################################
#def plot_MCMC_corner(sampler):
#    samples = sampler.get_chain(flat=True, discard=int(1.*config.BASEMENT.settings['mcmc_burn_steps']/config.BASEMENT.settings['mcmc_thin_by']))
#    
#    fig = corner(samples, 
#                 labels = config.BASEMENT.fitkeys,
#                 range = [0.999]*config.BASEMENT.ndim,
#                 quantiles=[0.15865, 0.5, 0.84135],
#                 show_titles=True, title_kwargs={"fontsize": 14},
#                 truths=config.BASEMENT.fittruths)
#            
#    return fig 
开发者ID:MNGuenther,项目名称:allesfitter,代码行数:47,代码来源:mcmc_output.py

示例7: new_corner

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def new_corner(*args, **kwargs):
    # Get the usual corner plot
    figure = old_corner(*args, **kwargs)

    # Get the axes
    ndim = int(np.sqrt(len(figure.axes)))
    axes = np.array(figure.axes).reshape((ndim, ndim))

    # Smaller tick labels
    for ax in axes[1:, 0]:
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(8)
        formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
        ax.yaxis.set_major_formatter(formatter)
    for ax in axes[-1, :]:
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(8)
        formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
        ax.xaxis.set_major_formatter(formatter)

    # Pad the axes to always include the truths
    truths = kwargs.get("truths", None)
    if truths is not None:
        for row in range(1, ndim):
            for col in range(row):
                lo, hi = np.array(axes[row, col].get_xlim())
                if truths[col] < lo:
                    lo = truths[col] - 0.1 * (hi - truths[col])
                    axes[row, col].set_xlim(lo, hi)
                    axes[col, col].set_xlim(lo, hi)
                elif truths[col] > hi:
                    hi = truths[col] - 0.1 * (hi - truths[col])
                    axes[row, col].set_xlim(lo, hi)
                    axes[col, col].set_xlim(lo, hi)

                lo, hi = np.array(axes[row, col].get_ylim())
                if truths[row] < lo:
                    lo = truths[row] - 0.1 * (hi - truths[row])
                    axes[row, col].set_ylim(lo, hi)
                    axes[row, row].set_xlim(lo, hi)
                elif truths[row] > hi:
                    hi = truths[row] - 0.1 * (hi - truths[row])
                    axes[row, col].set_ylim(lo, hi)
                    axes[row, row].set_xlim(lo, hi)

    return figure 
开发者ID:rodluger,项目名称:starry,代码行数:48,代码来源:notebook_setup.py

示例8: show_corner_plot

# 需要导入模块: import corner [as 别名]
# 或者: from corner import corner [as 别名]
def show_corner_plot(chain, burnin=0.5, save=False, output_dir='', **kwargs):
    """
    Display or save a figure showing the corner plot (pdfs + correlation plots)
    
    Parameters
    ----------
    chain: numpy.array
        The Markov chain. The shape of chain must be nwalkers x length x dim.
        If a part of the chain is filled with zero values, the method will
        discard these steps.
    burnin: float, default: 0
        The fraction of a walker we want to discard.
    save: boolean, default: False
        If True, a pdf file is created.
     
     kwargs:
        Additional attributs are passed to the corner.corner() method.
                    
    Returns
    -------
    Display the figure or create a pdf file named walk_plot.pdf in the working
    directory.
        
    Raises
    ------
    ImportError
    
    """
    try:
        temp = np.where(chain[0, :, 0] == 0.0)[0]
        if len(temp) != 0:
            chain = chain[:, :temp[0], :]
        length = chain.shape[1]
        indburn = int(np.floor(burnin*(length-1)))
        chain = chain[:, indburn:length, :].reshape((-1, 3))
    except IndexError:
        pass

    if chain.shape[0] == 0:
        print("It seems the chain is empty. Have you already run the MCMC?")
    else:
        labels = kwargs.pop('labels', ["$r$", r"$\theta$", "$f$"])
        fig = corner.corner(chain, labels=labels, **kwargs)
    if save:
        plt.savefig(output_dir+'corner_plot.pdf')
        plt.close(fig)
    else:
        plt.show() 
开发者ID:vortex-exoplanet,项目名称:VIP,代码行数:50,代码来源:mcmc_sampling.py


注:本文中的corner.corner方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。