Ejemplo n.º 1
0
def pystan2getdist(fit, texdict=texdict):
    """ convert a pystan fit object into an A Lewis MCSamples object
        texdict is a dictionary mapping from stan parameter names to latex labels, if desired
    """

    ### have to either deal with combining chains (permute=False)
    ###                       or separating vector-valued parameters (permute=True)

    sample_dict = fit.extract(permuted=True)
    names = []
    labels = []
    samples = []
    for par, samps in iteritems(sample_dict):
        if par == "lp__":
            loglikes = -samps
        else:
            if len(samps.shape)==1:
                names.append(par)
                labels.append(texdict.get(par,par))
                samples.append(samps)
            else:
                for i,s in enumerate(samps.T):
                    samples.append(s)
                    names.append(par+str(i+1))

                    labels.append(texdict.get(par,par)+"_"+str(i+1))

    return getdist.MCSamples(names=labels, samples=samples, loglikes=loglikes, labels=labels)
Ejemplo n.º 2
0
        def __init__(self,str_or_dict,trueval=None,debug=False,
                    names=None,labels=None,px='x',**kwargs):
            #Get the getdist MCSamples objects for the samples, specifying same parameter
            #names and labels; if not specified weights are assumed to all be unity

            if debug:
                logging.basicConfig(level=logging.DEBUG)
            self.logger = logging.getLogger(__name__)

            if isinstance(str_or_dict,str):
                
                fileroot=str_or_dict
                self.logger.info('string passed. Loading chain from '+fileroot)                
                self.load_from_file(fileroot,**kwargs)
                
            elif isinstance(str_or_dict,dict):
                d=str_or_dict
                self.logger.info('Chain is passed as dict: keys='+','.join(d.keys()))
                
                chain=d['samples']
                loglikes=d['loglikes']
                weights=d['weights'] if 'weights' in d.keys() else np.ones(len(loglikes))
                ndim=chain.shape[1]

                if names is None:
                    names = ["%s%s"%('p',i) for i in range(ndim)]
                if labels is None:
                    labels =  ["%s_%s"%(px,i) for i in range(ndim)]
                    
                self.names=names
                self.labels=labels
                self.trueval=trueval
                self.samples = gd.MCSamples(samples=chain,
                                            loglikes=loglikes,
                                            weights=weights,
                                            names = names,
                                            labels = labels)
                #Removes parameters that do not vary
                self.samples.deleteFixedParams()
                #Removes samples with zero weight
                #self.samples.filter(weights>0)
                
            else:
               self.logger.info('Passed first argument type is: ',type(str_or_dict))                
               self.logger.error('first argument to samples2getdist should be a string or dict.')
               raise

            # a copy of the weights that can be altered to
            # independently to the original weights
            self.adjusted_weights=np.copy(self.samples.weights)
            #
            self.nparamMC=self.samples.paramNames.numNonDerived()
Ejemplo n.º 3
0
def make_plot(chainfile, savefile, true_parameter_values=None, pnames=None, ranges=None):
    """Make a getdist plot"""
    samples = np.loadtxt(chainfile)
    ticks = {}
    if pnames is None:
        #Default emulator parameters
        pnames = [r"d\tau_0", r"\tau_0", r"n_s", r"A_\mathrm{P} \times 10^9", r"H_S", r"H_A", r"h"]
        samples[:,3] *= 1e9
        true_parameter_values[3] *= 1e9
        #Ticks we want to show for each parameter
        ticks = {pnames[3]: [1.5, 2.0, 2.5], pnames[4]: [-0.6,-0.3, 0.], pnames[5]: [0.5,0.7,1.0,1.3], pnames[6]: [0.66, 0.70, 0.74]}
    prange = None
    if ranges is not None:
        prange = {pnames[i] : ranges[i] for i in range(len(pnames))}
    posterior_MCsamples = gd.MCSamples(samples=samples, names=pnames, labels=pnames, label='', ranges=prange)

    print("Sim=",savefile)
    #Get and print the confidence limits
    for i in range(len(pnames)):
        strr = pnames[i]+" 1-sigma, 2-sigma: "
        for j in (0.16, 1-0.16, 0.025, 1-0.025):
            strr += str(round(posterior_MCsamples.confidence(i, j),5)) + " "
        print(strr)
    subplot_instance = gdp.getSubplotPlotter()
    subplot_instance.triangle_plot([posterior_MCsamples], filled=True)
#     colour_array = np.array(['black', 'red', 'magenta', 'green', 'green', 'purple', 'turquoise', 'gray', 'red', 'blue'])

    for pi in range(samples.shape[1]):
        for pi2 in range(pi + 1):
            #Place horizontal and vertical lines for the true point
            ax = subplot_instance.subplots[pi, pi2]
            ax.yaxis.label.set_size(16)
            ax.xaxis.label.set_size(16)
            if pi == samples.shape[1]-1 and pnames[pi2] in ticks:
                ax.set_xticks(ticks[pnames[pi2]])
            if pi2 == 0 and pnames[pi] in ticks:
                ax.set_yticks(ticks[pnames[pi]])
            ax.axvline(true_parameter_values[pi2], color='gray', ls='--', lw=2)
            if pi2 < pi:
                ax.axhline(true_parameter_values[pi], color='gray', ls='--', lw=2)
                #Plot the emulator points
#                 if parameter_index > 1:
#                     ax.scatter(simulation_parameters_latin[:, parameter_index2 - 2], simulation_parameters_latin[:, parameter_index - 2], s=54, color=colour_array[-1], marker='+')

#     legend_labels = ['+ Initial Latin hypercube']
#     subplot_instance.add_legend(legend_labels, legend_loc='upper right', colored_text=True, figure=True)
    plt.savefig(savefile)
Ejemplo n.º 4
0
def plot_multicomp_velo_2corr(store,
                              group_name,
                              outname='velo_2corr',
                              truths=None):
    group = store.hdf[group_name]
    ncomp = group.attrs['ncomp']
    assert ncomp == 2
    n_params = store.hdf.attrs['n_params']
    post = group['posteriors'][...][:, :-2]  # param values
    par_names = store.model.get_par_names(ncomp)
    ix_v = store.model.IX_VCEN
    ix_s = store.model.IX_SIGM
    par_labels = [''] * n_params * ncomp
    par_labels[ncomp *
               ix_v] = r'$v_\mathrm{lsr}\, (1) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp * ix_v +
               1] = r'$v_\mathrm{lsr}\, (2) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp *
               ix_s] = r'$\sigma_\mathrm{v}\, (1) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp * ix_s +
               1] = r'$\sigma_\mathrm{v}\, (2) \ [\mathrm{km\,s^{-1}}]$'
    samples = getdist.MCSamples(samples=post,
                                names=par_names,
                                labels=par_labels,
                                sampler='nested')
    samples.updateSettings({'contours': [0.68, 0.90]})
    fig = gd_plt.get_subplot_plotter()
    x_names = ['v1', 's1']
    y_names = ['v2', 's2']
    if truths is not None:
        xmarkers = {k: truths[k] for k in x_names}
        ymarkers = {k: truths[k] for k in y_names}
    else:
        xmarkers, ymarkers = None, None
    fig.rectangle_plot(x_names,
                       y_names,
                       roots=samples,
                       filled=True,
                       line_args={
                           'lw': 2,
                           'color': 'peru'
                       },
                       xmarkers=xmarkers,
                       ymarkers=ymarkers)
    fig.export(f'{outname}.pdf')
    plt.close('all')
Ejemplo n.º 5
0
def plot_corner(group, outname='corner', truths=None):
    ncomp = group.attrs['ncomp']
    par_labels = ammonia.TEX_LABELS.copy()
    par_labels[3] = r'$\log(N) \ [\log(\mathrm{cm^{-2}})]$'
    n_params = group.attrs['n_params'] // ncomp
    names = ammonia.get_par_names()
    post = group['posteriors'][...][:, :-2]  # posterior param values
    if truths is not None:
        markers = {
            p: truths[i * ncomp:(i + 1) * ncomp]
            for i, p in zip(range(n_params), ammonia.get_par_names())
        }
    else:
        markers = None
    # Give each model component parameter set its own sampler object so that
    # each can be over-plotted in its own color.
    samples = [
        getdist.MCSamples(samples=post[:, ii::ncomp],
                          names=names,
                          labels=par_labels,
                          label=f'Component {ii+1}',
                          name_tag=f'{ii}',
                          sampler='nested') for ii in range(ncomp)
    ]
    [s.updateSettings({'contours': [0.68, 0.90]}) for s in samples]
    fig = gd_plt.get_subplot_plotter()
    fig.triangle_plot(
        samples,
        filled=True,
        line_args=[{
            'lw': 2,
            'color': 'tab:orange'
        }, {
            'lw': 2,
            'color': 'tab:blue'
        }, {
            'lw': 2,
            'color': 'tab:green'
        }],
        markers=markers,
    )
    fig.export(f'{outname}.pdf')
    plt.close('all')
Ejemplo n.º 6
0
def plot_corner(store, group_name, outname='corner', truths=None):
    n_params = store.hdf.attrs['n_params']
    par_names = store.model.get_par_names()
    par_labels = store.hdf.attrs['tex_labels_with_units']
    group = store.hdf[group_name]
    ncomp = group.attrs['ncomp']
    post = group['posteriors'][...][:, :-2]  # posterior param values
    if truths is not None:
        markers = {
            p: truths[i * ncomp:(i + 1) * ncomp]
            for i, p in zip(range(n_params), par_names)
        }
    else:
        markers = None
    # Give each model component parameter set its own sampler object so that
    # each can be over-plotted in its own color.
    samples = [
        getdist.MCSamples(samples=post[:, ii::ncomp],
                          names=par_names,
                          labels=par_labels,
                          label=f'Component {ii+1}',
                          name_tag=f'{ii}',
                          sampler='nested') for ii in range(ncomp)
    ]
    [s.updateSettings({'contours': [0.68, 0.90]}) for s in samples]
    fig = gd_plt.get_subplot_plotter()
    fig.triangle_plot(
        samples,
        filled=True,
        line_args=[{
            'lw': 2,
            'color': 'tab:orange'
        }, {
            'lw': 2,
            'color': 'tab:blue'
        }, {
            'lw': 2,
            'color': 'tab:green'
        }],
        markers=markers,
    )
    fig.export(f'{outname}.pdf')
    plt.close('all')
Ejemplo n.º 7
0
        def __init__(self,
                     chain,
                     lnprob,
                     trueval=None,
                     names=None,
                     labels=None,
                     px='x'):
            #Get the getdist MCSamples objects for the samples, specifying same parameter
            #names and labels; if not specified weights are assumed to all be unity

            ndim = chain.shape[-1]

            if names is None:
                names = ["%s%s" % ('p', i) for i in range(ndim)]
            if labels is None:
                labels = ["%s_%s" % (px, i) for i in range(ndim)]

            self.names = names
            self.labels = labels
            self.trueval = trueval
            self.samples = gd.MCSamples(samples=chain,
                                        loglikes=lnprob,
                                        names=names,
                                        labels=labels)
Ejemplo n.º 8
0
def load_chain(chain_file, parameters=None, run_name=None, 
               chain_format="cosmosis", parameter_map="cosmomc", strict_mapping=False, 
               values=None, burn_in=0.3, keep_raw_samples=False, ignore_inf=False,
               extra_ranges=None,
               verbose=False):
    with open(chain_file, "r") as f:
        params = f.readline()[1:]
    
    if chain_format == "cosmosis":
        chain_params = [p.strip().lower() for p in params.split("\t")]
        if len(chain_params) == 1:
            chain_params = [p.strip().lower() for p in params.split(" ")]        
    elif chain_format == "montepython":
        chain_params = [p.strip() for p in params.split(",")]
    else:
        raise ValueError(f"Chain format {chain_format} not supported.")
        
    parameter_names = []
    parameter_names_latex = []
    for p in chain_params:
        for mapping in parameter_dictionary.values():
            if chain_format in mapping and mapping[chain_format] == p:
                parameter_names.append(mapping[parameter_map])
                parameter_names_latex.append(mapping["latex"])
                break
        else:
            if strict_mapping:
                raise MissingParameterError(f"Parameter {p} in chain does not have mapping to {parameter_map} format.")
            else:
                warnings.warn(f"Parameter {p} in chain does not have mapping to {parameter_map} format.")
                parameter_names.append(p)
                parameter_names_latex.append(p)

    raw_chain_parameter_names = parameter_names[:]

    column_idx = list(range(len(parameter_names)))
    
    stat_column_idx = {}
    
    # remove statistics columns
    for s in ["weight", "lnlike"]:
        s_map = parameter_dictionary[s][parameter_map]
        if s_map in parameter_names:
            stat_column_idx[s] = column_idx[parameter_names.index(s_map)]
            
    # remove statistic columns from parameter list
    for s, i in stat_column_idx.items():
        del parameter_names[i]
        del parameter_names_latex[i]
        del column_idx[i]
    
    try:
        chain, log_Z, log_Z_err = load_nested_sampling_file(chain_file)
        nested_sampling = True
    except:
        chain = np.atleast_2d(np.loadtxt(chain_file))
        n_sample = chain.shape[0]
        if isinstance(burn_in, float) and burn_in > 0.0 and burn_in < 1.0:
            chain = chain[int(n_sample*burn_in):]
        elif isinstance(burn_in, int):
            chain = chain[burn_in:]
        else:
            raise ValueError(f"Invalid burn_in value: {burn_in}")
        if verbose: print(f"Using {chain.shape[0]} samples out of {n_sample} in the chain.")
        nested_sampling = False
        
    if chain.size == 0:
        raise RuntimeError("No samples in file.")
    
    if values:
        if chain_format != "cosmosis" or parameter_map != "cosmomc":
            raise ValueError("Loading value files is only supported for cosmosis chains and cosmomc parameters.")
        sampled_params_ranges = get_sampled_params_and_ranges(values)
        cosmomc_names = cosmosis_to_cosmomc_param_names([(s,k) for s,k,_ in sampled_params_ranges])
        ranges = {cosmomc_names[i] : sampled_params_ranges[i][2] for i in range(len(cosmomc_names)) if cosmomc_names[i] in parameter_names}
    else:
        ranges = {}

    extra_ranges = extra_ranges or {}
    ranges = {**ranges, **extra_ranges}
    
    if ignore_inf:
        if "lnlike" in stat_column_idx and np.any(~np.isfinite(chain[:,stat_column_idx["lnlike"]])):
            chain = chain[np.isfinite(chain[:,stat_column_idx["lnlike"]])]
        if "weight" in stat_column_idx and np.any(~np.isfinite(chain[:,stat_column_idx["weight"]])):
            chain = chain[np.isfinite(chain[:,stat_column_idx["weight"]])]

    run_name = run_name or os.path.split(chain_file)[1]
    samples = getdist.MCSamples(name_tag=run_name,
                                samples=chain[:,column_idx],
                                weights=chain[:,stat_column_idx["weight"]] if "weight" in stat_column_idx else None,
                                loglikes=chain[:,stat_column_idx["lnlike"]] if "lnlike" in stat_column_idx else None,
                                names=parameter_names,
                                labels=parameter_names_latex,
                                sampler="nested" if nested_sampling else None,
                                ranges=ranges)

    if keep_raw_samples:
        samples.raw_chain_samples = chain
        samples.raw_chain_parameter_names = raw_chain_parameter_names
    
    if nested_sampling:
        samples.log_Z = log_Z
        samples.log_Z_err = log_Z_err
    else:
        samples.chain_offsets = [0, chain.shape[0]]
    
    return samples
Ejemplo n.º 9
0
                  h_0_cmb_samples[:, i, j], \
                  h_0_loc_samples[:, i, j]), 1)
            print rank, i, j, eff
        else:
            all_samples = np.genfromtxt('gw_grb_h_0_' + h_0_true_str + \
                   '_chain_' + \
                   '{:d}.csv'.format(j + 1), \
                   delimiter=',')
            h_0_samples[:, i, j] = all_samples[:, 0]
            h_0_cmb_samples[:, i, j] = all_samples[:, 1]
            h_0_loc_samples[:, i, j] = all_samples[:, 2]

        # process using GetDist. store means and interpolated probability
        # distributions
        gd_samples = gd.MCSamples(samples=all_samples,
                                  names=pars,
                                  labels=par_names,
                                  ranges=par_ranges)
        post_means.append(gd_samples.getMeans())
        post_stds.append(np.sqrt(gd_samples.getVars()))
        p_h_0.append(gd_samples.get1DDensity('h_0'))
        p_h_0_cmb.append(gd_samples.get1DDensity('h_0_cmb'))
        p_h_0_loc.append(gd_samples.get1DDensity('h_0_loc'))

# gather posteriors
if use_mpi:
    mpi.COMM_WORLD.barrier()
ln_prob = complete_array(ln_prob, use_mpi)
ppd_cmb = complete_array(ppd_cmb, use_mpi)
ppd_loc = complete_array(ppd_loc, use_mpi)
if ppd_via_sampling:
    h_0_samples = complete_array(h_0_samples, use_mpi)
Ejemplo n.º 10
0
def make_single_plot(chainfile,
                     savefile,
                     chainfile2=None,
                     pi1=0,
                     pi2=3,
                     true_parameter_values=None,
                     ranges=None,
                     string=True,
                     burnin=10000):
    """Make a getdist plot"""
    ticks = {}
    if string:
        pnames = [
            r"G\mu", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}"
        ]
    else:
        pnames = [
            r"T_\ast", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}",
            r"\alpha"
        ]  #, r"\beta"]
    prange = None
    if ranges is not None:
        prange = {pnames[i]: ranges[i] for i in range(len(pnames))}
    print("Sim=", savefile)
    subplot_instance = gdp.get_single_plotter()
    samples = np.loadtxt(chainfile)
    posterior_MCsamples = gd.MCSamples(samples=samples[burnin:],
                                       names=pnames,
                                       labels=pnames,
                                       label='',
                                       ranges=prange)
    if chainfile2 is not None:
        samples2 = np.loadtxt(chainfile2)
        posterior2 = gd.MCSamples(samples=samples2[burnin:],
                                  names=pnames,
                                  labels=pnames,
                                  label='',
                                  ranges=prange)
        subplot_instance.plot_2d([posterior_MCsamples, posterior2],
                                 pnames[pi1],
                                 pnames[pi2],
                                 filled=True)
        subplot_instance.add_legend(["LIGO+LISA", "LIGO+LISA+TianGo"])
    else:
        subplot_instance.plot_2d([posterior_MCsamples],
                                 pnames[pi1],
                                 pnames[pi2],
                                 filled=True)


#     colour_array = np.array(['black', 'red', 'magenta', 'green', 'green', 'purple', 'turquoise', 'gray', 'red', 'blue'])
#Ticks we want to show for each parameter
    if string:
        ticks = {
            pnames[0]: [
                np.log(1e-17),
                np.log(2e-17),
                np.log(5e-17),
                np.log(1e-16),
                np.log(2e-16),
                np.log(5e-16),
                np.log(1e-15)
            ]
        }
        ticklabels = {
            pnames[0]: [
                r"$10^{-17}$", r"$2\times 10^{-17}$", r"$5\times 10^{-17}$",
                r"$10^{-16}$", r"$2\times 10^{-16}$", r"$5\times 10^{-16}$",
                r"$10^{-15}$"
            ]
        }
    else:
        ticks = {
            pnames[0]: [
                np.log(1e3),
                np.log(2e3),
                np.log(5e3),
                np.log(1e4),
                np.log(2e4),
                np.log(5e4)
            ]
        }  #, np.log(1e6)]}#, np.log(1e11)
        #pnames[4]: [np.log(1e-4), np.log(1e-3), np.log(1e-2), np.log(0.1), 0]}
        ticklabels = {
            pnames[0]: [
                r"$10^{3}$", r"$2\times 10^3$", r"$5\times 10^3$", r"$10^{4}$",
                r"$2\times 10^4$", r"$5\times 10^{4}$"
            ]
        }  #, r"$10^{6}$"]}#, r"$10^{11}$"]},

    #Place horizontal and vertical lines for the true point
    ax = subplot_instance.subplots[0, 0]
    ax.yaxis.label.set_size(16)
    ax.xaxis.label.set_size(16)
    if pnames[pi2] in ticks:
        ax.set_yticks(ticks[pnames[pi2]])
        ax.set_yticklabels(ticklabels[pnames[pi2]])
    if pnames[pi1] in ticks:
        ax.set_xticks(ticks[pnames[pi1]])
        ax.set_xticklabels(ticklabels[pnames[pi1]])
    ax.axhline(true_parameter_values[pi2], color='gray', ls='--', lw=2)
    ax.axvline(true_parameter_values[pi1], color='gray', ls='--', lw=2)
    plt.savefig(savefile)
Ejemplo n.º 11
0
                            result.posterior.iota, \
                            result.posterior.mass_ratio, \
                            result.posterior.lambda_2, \
                            result.posterior.lambda_tilde, \
                            result.posterior.chi_1, \
                            result.posterior.mass_2, \
                            result.posterior.mass_1_source, \
                            result.posterior.mass_2_source]).T
     samples.append(gd.MCSamples(samples=gd_samples, \
                                 names=['a_1', 'mass_1', \
                                        'distance', 'iota', \
                                        'q', 'lambda_2', \
                                        'lambda_tilde', 'chi_1', \
                                        'mass_2', 'mass_1_source', \
                                        'mass_2_source'], \
                                 labels=['a_1', r'm_{\rm BH}', \
                                         distance_label, r'\iota', \
                                         r'm_{\rm NS}/m_{\rm BH}', \
                                         r'\Lambda_{\rm NS}', \
                                         r'\tilde{\Lambda}', \
                                         r'\chi_1', r'm_{\rm NS}', \
                                         r'm_{\rm BH}^{\rm source}', \
                                         r'm_{\rm NS}^{\rm source}'], \
                                 ranges=gd_ranges, weights=weights))
 else:
     gd_samples = np.array([result.posterior.a_1, \
                            result.posterior.mass_1, \
                            delta_distance, \
                            result.posterior.iota, \
                            result.posterior.mass_ratio, \
                            result.posterior.lambda_2, \
                            result.posterior.lambda_tilde, \
Ejemplo n.º 12
0
        bgw_samples = np.array([bilby_samples['luminosity_distance'], \
                                bilby_m_bh, \
                                bilby_m_ns, \
                                bilby_samples['chirp_mass'], \
                                bilby_samples['mass_ratio']]).T
        _, m_min_ns_bgw = chirp_q_to_comp_masses(m_c_min, q_inv_min)
        _, m_max_ns_bgw = chirp_q_to_comp_masses(m_c_max, q_inv_max)
        m_min_bh_bgw, _ = chirp_q_to_comp_masses(m_c_min, q_inv_max)
        m_max_bh_bgw, _ = chirp_q_to_comp_masses(m_c_max, q_inv_min)

        # plot!
        smf_gds = gd.MCSamples(samples=smf_samples, \
                               names=['d', 'm_1', 'm_2', 'm_c', 'q_inv'], \
                               labels=[r'D_L', 'm_1', 'm_2', 'M_c', '1/q'], \
                               ranges={'d':(d_min, d_max), \
                                       'm_1':(m_min_bh, m_max_bh), \
                                       'm_2':(m_min_ns, m_max_ns), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='SMF Priors')
        bgw_gds = gd.MCSamples(samples=bgw_samples, \
                               names=['d', 'm_1', 'm_2', 'm_c', 'q_inv'], \
                               labels=[r'D_L', 'm_1', 'm_2', 'M_c', '1/q'], \
                               ranges={'d':(d_min, d_max), \
                                       'm_1':(m_min_bh_bgw, m_max_bh_bgw), \
                                       'm_2':(m_min_ns_bgw, m_max_ns_bgw), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='Bilby Priors')
        g = gdp.get_subplot_plotter()
        g.settings.lw_contour = lw
Ejemplo n.º 13
0
par_names = ['H_0', 'q_0']
par_vals = [h_0, q_0]
par_ranges = {}
if sample_rate:
    pars.append('gamma')
    par_names.append(r'\Gamma')
    par_vals.append(rate * 1.0e9)
    #par_ranges['gamma'] = (0.0, None)
    par_ranges['gamma'] = (10.0, 1000.0)
if n_bar_det_post:
    pars.append('n_bar_det')
    par_names.append(r'\bar{N}_{\rm det}')
    par_vals.append(n_bar_det_fid)
n_pars = len(pars)
gd_samples = gd.MCSamples(samples=samples[:, 0:n_pars],
                          names=pars,
                          labels=par_names,
                          ranges=par_ranges)
g = gdp.getSubplotPlotter()
g.settings.lw_contour = lw
g.settings.axes_fontsize = 8
g.triangle_plot(gd_samples, pars, filled = True, \
                line_args = {'lw': lw, 'color': 'C0'}, \
                contour_args = {'lws': [lw, lw]}, \
                colors = ['C0'])
for i in range(0, n_pars):
    sp_title = '$' + gd_samples.getInlineLatex(pars[i], \
                                               limit=1) + '$'
    g.subplots[i, i].set_title(sp_title, fontsize=12)
    for ax in g.subplots[i, :i]:
        ax.axhline(par_vals[i], color='gray', ls='--')
        ax.grid(False)
Ejemplo n.º 14
0
n_grid = 500
h_0_min_plot = 60.0
h_0_max_plot = 80.0
h_0_grid = np.linspace(h_0_min_plot, h_0_max_plot, n_grid)
d_h_0 = h_0_grid[1] - h_0_grid[0]
if ntlo:
    fig2d, ax2d = mp.subplots(figsize=(6, 5))
    n_2d_grid = 40
    q_0_min_plot = 1.0
    q_0_max_plot = -2.0
    h_0_grid_2d = np.linspace(h_0_min_plot, h_0_max_plot, n_2d_grid)
    q_0_grid_2d = np.linspace(q_0_min_plot, q_0_max_plot, n_2d_grid)
    h_0_mgrid, q_0_mgrid = np.meshgrid(h_0_grid_2d, q_0_grid_2d)
for i in range(n_overlay):
    gd_samps = gd.MCSamples(samples=samples[..., i_map[i_plot[i]]], \
          names=pars, labels=par_names, \
          ranges=par_ranges)
    h_0_post = norm_dist(gd_samps.get1DDensity('h_0').Prob(h_0_grid), d_h_0)
    axes[0].plot(h_0_grid, h_0_post, color=cols[i], alpha=0.6)
if ntlo:
    for i in range(n_overlay):
        gd_samps = gd.MCSamples(samples=samples[..., i_map[i_plot[i]]], \
              names=pars, labels=par_names, \
              ranges=par_ranges)
        hq_post = gd_samps.get2DDensity('h_0', 'q_0')
        hq_post = hq_post.Prob(h_0_mgrid.flatten(), q_0_mgrid.flatten())
        hq_post = hq_post.reshape(n_2d_grid, n_2d_grid)
        #mp.contour(h_0_grid_2d, q_0_grid_2d, hq_post, \
        #		   levels=[np.exp(-2.0), np.exp(-0.5)], \
        #		   colors=[cols[i]], linestyles=['dashed', 'solid'], \
        #		   alpha=0.6)
Ejemplo n.º 15
0
def make_plot(chainfile,
              savefile,
              chainfile2=None,
              chainfile3=None,
              true_parameter_values=None,
              ranges=None,
              string=True,
              burnin=10000):
    """Make a getdist plot"""
    ticks = {}
    if string:
        pnames = [
            r"G\mu", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}"
        ]
    else:
        pnames = [
            r"T_\ast", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}",
            r"\alpha"
        ]  #, r"\beta"]
    prange = None
    if ranges is not None:
        prange = {pnames[i]: ranges[i] for i in range(len(pnames))}
    samples = np.loadtxt(chainfile)
    posterior_MCsamples = gd.MCSamples(samples=samples[burnin:],
                                       names=pnames,
                                       labels=pnames,
                                       label='LIGO+LISA',
                                       ranges=prange)

    print("Sim=", savefile)
    #Get and print the confidence limits
    for i, pn in enumerate(pnames):
        strr = pn + " 1-sigma, 2-sigma: "
        for j in (0.16, 1 - 0.16, 0.025, 1 - 0.025):
            post = posterior_MCsamples.confidence(i, j)
            if pn == r"G\mu":
                post = np.exp(post)
            strr += " %g" % post
        print(strr)
    subplot_instance = gdp.getSubplotPlotter()
    if chainfile2 is not None:
        samples2 = np.loadtxt(chainfile2)
        posterior_MCsamples2 = gd.MCSamples(samples=samples2[burnin:],
                                            names=pnames,
                                            labels=pnames,
                                            label='LIGO+LISA+TianGo',
                                            ranges=prange)
        if chainfile3 is not None:
            samples3 = np.loadtxt(chainfile3)
            posterior_MCsamples3 = gd.MCSamples(samples=samples3[burnin:],
                                                names=pnames,
                                                labels=pnames,
                                                label='LIGO+LISA+DECIGO',
                                                ranges=prange)
            subplot_instance.triangle_plot([
                posterior_MCsamples3, posterior_MCsamples2, posterior_MCsamples
            ],
                                           filled=True,
                                           legend_loc="right")
        else:
            subplot_instance.triangle_plot(
                [posterior_MCsamples, posterior_MCsamples2],
                filled=True,
                legend_loc="right")
    else:
        subplot_instance.triangle_plot([posterior_MCsamples], filled=True)


#     colour_array = np.array(['black', 'red', 'magenta', 'green', 'green', 'purple', 'turquoise', 'gray', 'red', 'blue'])
#Ticks we want to show for each parameter
    if string:
        if ranges[0][0] < np.log(1e-18):
            ticks = {pnames[0]: [np.log(1e-20), np.log(1e-17), np.log(1e-15)]}
            ticklabels = {
                pnames[0]: [r"$10^{-20}$", r"$10^{-17}$", r"$10^{-15}$"]
            }
        else:
            ticks = {pnames[0]: [np.log(1e-17), np.log(1e-16), np.log(1e-15)]}
            ticklabels = {
                pnames[0]: [r"$10^{-17}$", r"$10^{-16}$", r"$10^{-15}$"]
            }
    else:
        if ranges[0][0] > 1e6:
            ticks = {
                pnames[0]: [np.log(1e2), np.log(1e4),
                            np.log(1e6)]
            }  #, np.log(1e11)
            #pnames[4]: [np.log(1e-4), np.log(1e-3), np.log(1e-2), np.log(0.1), 0]}
            ticklabels = {
                pnames[0]: [r"$10^{2}$", r"$10^{4}$", r"$10^{6}$"]
            }  #, r"$10^{11}$"]},
            #pnames[4]: [r"$10^{-4}$", r"$10^{-3}$", r"$0.01$", r"$0.1$", r"$1.0$"]}
        else:
            ticks = {
                pnames[0]: [np.log(1e2), np.log(1e4)]
            }  #, np.log(1e6)]}#, np.log(1e11)
            #pnames[4]: [np.log(1e-4), np.log(1e-3), np.log(1e-2), np.log(0.1), 0]}
            ticklabels = {
                pnames[0]: [r"$10^{2}$", r"$10^{4}$"]
            }  #, r"$10^{6}$"]}#, r"$10^{11}$"]},

    if np.isnan(true_parameter_values[0]):
        ax = subplot_instance.subplots[0, 0]
        ax.set_visible(False)
    for pi in range(samples.shape[1]):
        for pi2 in range(pi + 1):
            #Place horizontal and vertical lines for the true point
            ax = subplot_instance.subplots[pi, pi2]
            ax.yaxis.label.set_size(16)
            ax.xaxis.label.set_size(16)
            if pi == samples.shape[1] - 1 and pnames[pi2] in ticks:
                ax.set_xticks(ticks[pnames[pi2]])
                ax.set_xticklabels(ticklabels[pnames[pi2]])
            if pi2 == 0 and pnames[pi] in ticks:
                ax.set_yticks(ticks[pnames[pi]])
                ax.set_yticklabels(ticklabels[pnames[pi]])
            if not np.isnan(true_parameter_values[pi2]):
                ax.axvline(true_parameter_values[pi2],
                           color='gray',
                           ls='--',
                           lw=2)
            if pi2 < pi:
                if not np.isnan(true_parameter_values[pi]):
                    ax.axhline(true_parameter_values[pi],
                               color='gray',
                               ls='--',
                               lw=2)
    plt.savefig(savefile)
Ejemplo n.º 16
0
					i_det = np.array([75, 86, 93])
					i_det = np.argwhere(det)[i_det, 0]
					i_plot = np.append(i_det, i_det + n_pars / 2)
					plot_samples = gw_samples[:, i_plot]
					gd_names = ['d_{:d}'.format(j) for j in range(n_plot)] + \
 							   ['c_{:d}'.format(j) for j in range(n_plot)]
 					gd_labels = [r'D\,({\rm Mpc})'] * n_plot + \
 								[r'\cos\iota'] * n_plot
 					gd_pairs = [['d_{:d}'.format(j), 'i_{:d}'.format(j)] \
 								for j in range(n_plot)]
 					gd_limits = merge_dicts({'d_{:d}'.format(j): (0.0, d_max) \
 											 for j in range(n_plot)}, \
 											{'c_{:d}'.format(j): (-1.0, 1.0) \
 											 for j in range(n_plot)})
 					gd_samples = gd.MCSamples(samples=plot_samples, \
											  names=gd_names, \
											  labels=gd_labels, \
											  ranges=gd_limits)
					for j in range(n_plot):
						gd_name = 'i_{:d}'.format(j)
						gd_label = r'\iota\,(\degree)'
						c_j = gw_samples[:, i_plot[j] + n_pars / 2]
						gd_samples.addDerived(np.arccos(c_j) * 180.0 / np.pi, \
											  name=gd_name, label=gd_label)
						gd_samples.setRanges({'i_{:d}'.format(j):(0.0, 180.0)})
					gd_samples.updateBaseStatistics()
					g = gdp.getSubplotPlotter(subplot_size=3)
					g.settings.lw_contour = lw
					g.plots_2d(gd_samples, param_pairs=gd_pairs, \
							   nx=3, filled=True, \
							   colors=[mpc.rgb2hex(cols[2])])
					axes = g.subplots.flatten()
Ejemplo n.º 17
0
     samples.append(None)
     continue
 if aligned_spins:
     gd_samples = np.array([result.posterior.a_1, \
                            result.posterior.mass_1, \
                            delta_distance, \
                            result.posterior.iota, \
                            result.posterior.mass_ratio, \
                            result.posterior.lambda_2, \
                            result.posterior.lambda_tilde, \
                            result.posterior.chi_1]).T
     samples.append(gd.MCSamples(samples=gd_samples, \
                                 names=['a_1', 'mass_1', \
                                        'distance', 'iota', \
                                        'q', 'lambda_2', \
                                        'lambda_tilde', 'chi_1'], \
                                 labels=['|a|_1', r'M_{\rm BH}', \
                                         distance_label, r'\iota', \
                                         'm_2/m_1', r'\Lambda_{\rm NS}', \
                                         r'\tilde{\Lambda}', r'\chi_1'], \
                                 ranges=gd_ranges))
 else:
     gd_samples = np.array([result.posterior.a_1, \
                            result.posterior.mass_1, \
                            delta_distance, \
                            result.posterior.iota, \
                            result.posterior.mass_ratio, \
                            result.posterior.lambda_2, \
                            result.posterior.lambda_tilde]).T
     samples.append(gd.MCSamples(samples=gd_samples, \
                                 names=['a_1', 'mass_1', \
                                        'distance', 'iota', \
Ejemplo n.º 18
0
    n_dims = 14

    multinest_samples = np.loadtxt(args.multinest_dir + '.txt')
    multinest_weights = multinest_samples[:, 0]
    multinest_lnL = multinest_samples[:, 1]  # this is actually -2.0*lnL !
    multinest_params = multinest_samples[:, 2:2 + n_dims]
    multinest_ppd = multinest_samples[:, 2 + n_dims:]

    multinest_chisqs = multinest_ppd[:, -1]
    multinest_modelvecs = multinest_ppd[:, :-1]
    multinest_wps, multinest_deltasigmas = np.split(multinest_modelvecs,
                                                    2,
                                                    axis=1)

    samples = getdist.MCSamples(samples=multinest_samples,
                                weights=multinest_weights,
                                loglikes=multinest_lnL)

    ## read datavector

    rmin_mock, rmax_mock, _, wp_mock = np.loadtxt(
        '../../lowz_mocks/data/lowz_corr.wp.txt', unpack=True)
    rmin_mock, rmax_mock, _, ds_mock = np.loadtxt(
        '../../lowz_mocks/data/lowz_corr.ds.txt', unpack=True)
    #	rmin_mock, rmax_mock, _, wp_mock = np.loadtxt('../../lowz_mocks/data/lowz_corr_blinded.wp.txt',
    #													unpack=True)
    #	rmin_mock, rmax_mock, _, ds_mock = np.loadtxt('../../lowz_mocks/data/lowz_corr_blinded.ds.txt',
    #													unpack=True)

    r_mock = 0.5 * (rmin_mock + rmax_mock)
Ejemplo n.º 19
0
        test = result.posterior
    except ValueError:
        skip[i] = True
        samples.append(None)
        print('run', i, 'incomplete')
        continue
    gd_samples = np.array([result.posterior.lambda_2, \
                           result.posterior.a_1, \
                           result.posterior.iota, \
                           result.posterior.mass_ratio, \
                           result.posterior.chirp_mass]).T
    samples.append(gd.MCSamples(samples=gd_samples, \
                                names=['lambda_2', 'a_1', 'iota', \
                                       'q', 'm_c'], \
                                labels=[r'\Lambda_{\rm NS}', 'a_1', \
                                        r'\iota', 'm_2/m_1', \
                                        r'\mathcal{M}_{\rm c}'], \
                                ranges={'a_1':(0.0, 0.8), \
                                        'iota':(0.0, np.pi), \
                                        'q':(0.02, 0.6), \
                                        'lambda_2':(0.0, 4000.0)}))

# snr-ordered colouring
n_targets = len(samples)
cm = mpcm.get_cmap('plasma')
cols = [mpc.rgb2hex(cm(x)) for x in np.linspace(0.2, 0.8, n_targets)[::-1]]

# generate figure and axes
n_col = 5
n_row = 8
fig, axes = mp.subplots(n_row, n_col, figsize=(20, 30))
g = gdp.get_single_plotter()
Ejemplo n.º 20
0
def main(args):

    log_roots = glob.glob(args.root)

    if args.dim != 0:
        x_dims = [args.dim]
    else:
        x_dims = range(2, 50)

    for log_root in log_roots:

        print()
        print('------------------------')
        print(log_root)
        print('------------------------')
        print()

        # Find
        log_dim_dirs = [[] for _ in x_dims]
        for ix, x_dim in enumerate(x_dims):
            for log_dir in glob.glob(os.path.join(log_root, 'run*')):
                if os.path.exists(os.path.join(log_dir, 'info', 'params.txt')):
                    with open(os.path.join(log_dir, 'info',
                                           'params.txt')) as f:
                        data = json.load(f)
                    if int(data['x_dim']) == x_dim:
                        log_dim_dirs[ix].append(log_dir)

        for ix, log_dim_dir in enumerate(log_dim_dirs):

            logzs = []
            dlogzs = []
            nlikes = []
            ess = []

            if len(log_dim_dir) > 0:
                print()
                print('--------')
                print('Dim: %s' % x_dims[ix])
                print('--------')
                print()

            for log_dir in log_dim_dir:

                with open(os.path.join(log_dir, 'info', 'params.txt')) as f:
                    data = json.load(f)

                if os.path.exists(os.path.join(log_dir, 'chains',
                                               'chain.txt')):
                    names = ['p%i' % i for i in range(int(data['x_dim']))]
                    labels = [r'x_{%i}' % i for i in range(int(data['x_dim']))]
                    files = getdist.chains.chainFiles(
                        os.path.join(log_dir, 'chains', 'chain.txt'))
                    if data['sampler'] == 'nested':
                        mc = getdist.MCSamples(os.path.join(
                            log_dir, 'chains', 'chain.txt'),
                                               names=names,
                                               labels=labels,
                                               ignore_rows=0.0,
                                               sampler='nested')
                    else:
                        mc = getdist.MCSamples(os.path.join(
                            log_dir, 'chains', 'chain.txt'),
                                               names=names,
                                               labels=labels,
                                               ignore_rows=0.3)
                    mc.readChains(files)
                    if args.feedback > 0:
                        print(mc.getMargeStats())

                    if args.plot:
                        g = getdist.plots.getSubplotPlotter()
                        g.triangle_plot(mc, filled=True)
                        g.export(
                            os.path.join(
                                os.path.join(log_dir, 'plots',
                                             'triangle.png')))

                if data['sampler'] == 'nested':
                    if os.path.exists(
                            os.path.join(log_dir, 'results', 'final.csv')):
                        results = pd.read_csv(
                            os.path.join(log_dir, 'results', 'final.csv'))
                        print(results)
                        logzs.append(results['logz'])
                        dlogzs.append(results['logzerr'])
                        nlikes.append(results['ncall'])
                        ess.append(
                            np.sum(mc.weights)**2 / np.sum(mc.weights**2))

            if len(logzs) > 1:
                print()
                print('Num runs: %s' % (len(logzs)))
                print(r'Log Z: $%4.2f \pm %4.2f$' %
                      (np.mean(logzs), np.std(logzs)))
                print(r'Log Z error estimate: $%4.2f \pm %4.2f$' %
                      (np.mean(dlogzs), np.std(dlogzs)))
                print(r'N_like: $%.0f \pm %.0f$' %
                      (np.mean(nlikes), np.std(nlikes)))
                print(r'Posterior ESS: $%.0f \pm %.0f$' %
                      (np.mean(ess), np.std(ess)))