Exemplo n.º 1
0
def bigplots(agb_tracks, infile):
    if type(agb_tracks[0]) == str:
        agb_tracks = [fileIO.get_numeric_data(a) for a in agb_tracks]
    out_fig = os.path.join(infile.diagnostic_dir, 'hrd_%.4f.png' % agb_tracks[0].metallicity)
    plot_title = '$\dot{M}_{\\rm M13}\ Z=%.4f$' % agb_tracks[0].metallicity
    nagb_tracks = len(agb_tracks)
    fig, (axs) = rspg.setup_multiplot(nagb_tracks,
                                      ylabel='$\log\ L\ (L_\odot)$',
                                      xlabel='$\log\ T_{\\rm eff}\ (K)$',
                                      title =plot_title,
                                      subplots_kwargs={'figsize': (30,30),
                                                       'squeeze': True})
    axs = axs.flatten()
    [hrd_slopes(agb_tracks[i], ax=axs[i]) for i in range(nagb_tracks)]
    plt.savefig(out_fig, dpi=300)
    ylabel = ['$C/O$', '$\log\ L\ (L_\odot)$', '$\log\ T_{\\rm eff}\ (K)$']
    ycol = ['C/O', 'logl', 'logt']
    for i in range(len(ylabel)):
        fig, (axs) = rspg.setup_multiplot(nagb_tracks,
                                          ylabel=ylabel[i],
                                          xlabel='${\\rm Age (yr)}$',
                                          title =plot_title,
                                          subplots_kwargs={'figsize': (30,30),
                                                           'squeeze': True})
        axs = axs.flatten()
        [age_vs_plot(agb_tracks[j], infile, ycol=ycol[i], ax=axs[j], annotate=True,
                     xlabels=False, ylabels=False, save_plot=False)
         for j in range(len(agb_tracks))]
        out_fig = out_fig.replace('hrd', 'age_v_%s' % ycol[i].lower().replace('c/o',
                                                                              'co'))
        plt.savefig(out_fig, dpi=300)
def plot_integrated_colors(filenames, labels='Z'):
    if type(filenames) is str:
        filenames = [filenames]
        ax = None
        cols = ['k']
    else:
        fig, ax = plt.subplots()
        cols = brewer2mpl.get_map('Spectral', 'Diverging',
                                  len(filenames)).mpl_colors

    if labels == 'Z':
        fmt = '$Z=%.4f$'
        labels = [fmt % float(l.replace('.dat', '').split('Z')[1])
                  for l in filenames]
    else:
        print 'need to fix labels'
        labels = [''] * len(filenames)
    for i, filename in enumerate(filenames):
        data = rsp.fileIO.readfile(filename)
        ycol = 'V-K'
        xcol = 'Age'
        ax = rg.color_color(data, xcol, ycol, xscale='log', ax=ax,
                            plt_kw={'lw': 2, 'color': cols[i],
                                    'label': labels[i]})

    plot_cluster_data(ax)
    ax.legend(frameon=False, loc=0, numpoints=1)
    ax.set_xlabel(r'${\rm %s}$' % xcol, fontsize=20)
    ax.set_ylabel(r'${\rm %s}$' % ycol, fontsize=20)
    plt.tick_params(labelsize=16)
    return ax
def plot_mc_integrated_colors(filenames):
    fig, ax = plt.subplots()
    for i, filename in enumerate(filenames):
        data = rsp.fileIO.readfile(filename)
        ycol = 'V-K'
        xcol = 'Age'
        ax = rg.color_color(data, xcol, ycol, xscale='log', ax=ax,
                            plt_kw={'marker': '.', 'color': 'k',
                                    'alpha': 0.3})

    plot_cluster_data(ax)
def test_ycen(et):
    import ResolvedStellarPops.graphics.GraphicsUtils as rspg
    eeps = ['YCEN_0.000', 'YCEN_0.100', 'YCEN_0.200', 'YCEN_0.400',
            'YCEN_0.500', 'YCEN_0.550']
    cols = rspg.discrete_colors(len(eeps))
    ptcri_inds_kw = {'hb': False, 'sandro': False}
    add_eep_inds([et], *eeps, **ptcri_inds_kw)
    fig, ax = plt.subplots(figsize=(8, 8))
    for i, track in enumerate(et.tracks):
        if track.mass == 0.5 or track.mass == 0.55:
            continue
        tinds =  track.ptcri.inds_between_ptcris('YCEN_0.550', 'YCEN_0.000',
                                                 sandro=False)
        inds = np.array([et.__getattribute__(s) for s in et.__dict__.keys() if s.startswith('ycen')]).T
        if np.sum(inds) == 0:
            continue
        #ax.plot(track.data.LOG_TE, track.data.LOG_L, color='black', alpha=0.1)
        ax.plot(track.data.LOG_TE[tinds], track.data.LOG_L[tinds], color='red')
        [ax.plot(track.data.LOG_TE[inds[i][j]], track.data.LOG_L[inds[i][j]], 'o', color=cols[j]) for j in range(len(eeps))]
        ax.text(track.data.LOG_TE[inds[i][0]], track.data.LOG_L[inds[i][0]], '%.3g' % track.mass)
    ax.set_title('Z=%.4f' % track.Z)
Exemplo n.º 5
0
    def vary_the_SFH(self, cmd_input_file, prep_tri_kw=None, make_many_kw=None,
                     dry_run=False, diag_plots=False):
        
        tri_sfr_fmt = os.path.join(self.outfile_loc, 'tri_%s' % self.prefix)
        tri_sfr_fmt += '_003i.sfr'

        (sfr_out_file, object_mass) = zip(*[self._make_trilegal_sfh(outfile=tri_sfr_fmt % i, **make_many_kw)
                                            for i in range(nsfhs)])
        self.sfr_files = list(sfr_out_file)

        prep_tri_kw = dict({'loidl': True, photsys: '2mass'}.items() + prep_tri_kw.items())
        self.galaxy_inputs = [self.prepare_trilegal(tri_sfr_file=self.sfr_files[i], object_mass[i],
                                                    **prep_tri_kw)
                              for i in range(len(nsfhs))

        output = ADKLJSFL:KAJD
        # set up the trilegal run and then test!!!
        rsp.TrilegalUtils.run_trilegal(cmd_input_file, self.galaxy_input[i], output,
                                               loud=True)



def load_raw_vmc_data():
    #photom_file = research_path + 'TP-AGBcalib/LMC_Calib/photom.dat'
    #photom = rsp.fileIO.readfile(photom_file)
    results_file = research_path + 'TP-AGBcalib/LMC_Calib/photom_model.dat'
    dtype = [('RAJ2000', '<f8'), ('DEJ2000', '<f8'), ('recno', '<f8'),
             ('Seq', '<f8'), ('tau', '<f8'), ('logML', '<f8'), ('Lsun', '<f8'),
             ('Cl', '|S4'), ('Q', '|S1'), ('P', '|S1'), ('SED', '|S3'),
             ('recno1', '<f8'), ('Seq1', '<f8'), ('Umag', '<f8'),
             ('Bmag', '<f8'), ('Vmag', '<f8'), ('Imag', '<f8'),
             ('YmagV', '<f8'), ('JmagV', '<f8'), ('KsmagV', '<f8'),
             ('Jmag2', '<f8'), ('Hmag2', '<f8'), ('Ksmag2', '<f8'),
             ('[3.6]1', '<f8'), ('[3.6]2', '<f8'), ('[4.5]1', '<f8'),
             ('[4.5]2', '<f8'), ('[5.8]1', '<f8'), ('[5.8]2', '<f8'),
             ('[8.0]1', '<f8'), ('[8.0]2', '<f8'), ('[24]1', '<f8'),
             ('[24]2', '<f8'), ('chi2C', '<f8'), ('chi2O', '<f8')] 
    results = np.genfromtxt(results_file, dtype=dtype)
    return results

def read_vmc_table(filename):
    dtype = [('DEJ2000d', '<f8'),
             ('RAJ2000d', '<f8'),
             ('num', '<f8'),
             ('seq', '<f8'),
             ('RAJ2000', '|S12'),
             ('DEJ2000', '|S12'),
             ('tau', '<f8'),
             ('logMdot', '<f8'),
             ('Lum', '<f8'),
             ('Cl', '|S4'),
             ('Q', '|S1'),
             ('P', '|S1'),
             ('SED', '|S3'),
             ('Umag', '<f8'),
             ('Bmag', '<f8'),
             ('Vmag', '<f8'),
             ('Imag', '<f8'),
             ('YmagV', '<f8'),
             ('JmagV', '<f8'),
             ('KsmagV', '<f8'),
             ('Jmag2', '<f8'),
             ('Hmag2', '<f8'),
             ('Ksmag2', '<f8'),
             ('u3.6_1', '<f8'),
             ('u3.6_2', '<f8'),
             ('u4.5_1', '<f8'),
             ('u4.5_2', '<f8'),
             ('u5.8_1', '<f8'),
             ('u5.8_2', '<f8'),
             ('u8.0_1', '<f8'),
             ('u8.0_2', '<f8'),
             ('u24_1', '<f8'),
             ('u24_2', '<f8'),
             ('chi2C', '<f8'),
             ('chi2O', '<f8')]
    return np.genfromtxt(filename, dtype=dtype)


def read_lmc_cat(filename):
    with open(filename, 'r') as f:
        header = f.readline()
    col_keys = header.replace('#', '').strip().split()
    
    return np.genfromtxt(filename, names=col_keys)


def make_plot(output, extra='', photsys='2mass', tpagb_mass_bins=None):
    if tpagb_mass_bins is None:
        tpagb_mass_bins = np.arange(1., 6, 0.5)

    filter1 = 'J'
    if 'ubv' in photsys:
        filter2 = 'K'
    elif '2mass' in photsys:
        filter2 = 'Ks'
    sgal = rsp.Galaxies.simgalaxy(output, filter1=filter1, filter2=filter2)
    sgal.all_stages('TPAGB')
    sgal.mix_modelname(sgal.name)
    # http://vizier.cfa.harvard.edu/viz-bin/VizieR?-source=J/A+A/537/A105
    #vmcagbs = research_path + 'TP-AGBcalib/LMC_Calib/VMCAGBS_fmt.dat'
    #data = read_vmc_table(vmcagbs)

    vmcagbs = research_path + 'TP-AGBcalib/LMC_Calib/VMCAGBS_fmt2.dat'
    gal = rsp.Galaxies.galaxy(vmcagbs, filter1='Jmag2', filter2='Ksmag2', hla=False, 
                              angst=False)
    gal.filters = [filter1, filter2]
    #gal.maglims = [13., 12.]
    gal.target = sgal.mix

    smg = rsp.Galaxies.sim_and_gal(gal, sgal)
    outfile = output.replace('.dat','_%s.png' % extra)
    fig, axs, top_axs = smg.make_LF(filter1, filter2, color_hist=False,
                                    plot_tpagb=True , add_boxes=False,
                                    plot_LF_kw={'xlim': (0.5, 4)},
                                    figname=outfile)
    axs[1].cla()
    ax = sgal.color_by_arg(0,0,0, xdata=sgal.color, ydata=sgal.mag2,
                           coldata=sgal.data.get_col('m_ini'),
                           bins=tpagb_mass_bins, slice_inds=sgal.itpagb,
                           ax=axs[1], xlim=axs[0].get_xlim(),
                           ylim=axs[0].get_ylim(), fig=fig)

    tpagb_masses = sgal.data.get_col('m_ini')[sgal.itpagb]
    tpinds = np.digitize(tpagb_masses, tpagb_mass_bins)
    tpinds = tpinds[tpinds < len(tpagb_mass_bins)]
    tpagb_mass_inds = [sgal.itpagb[tpinds==i] for i in np.unique(tpinds)]
    # some masses are not recovered.
    tpagb_mass_bins = tpagb_mass_bins[np.unique(tpinds)]
    if 3 <= len(tpagb_mass_bins) <= 11:
        bmap = brewer2mpl.get_map('Paired', 'Qualitative', len(tpagb_mass_bins))
        cols = bmap.mpl_colors
    else:
        cols = rspg.discrete_colors(len(tpagb_mass_bins), colormap='RdYlGn')

    for i, tpagb_mass_ind in enumerate(tpagb_mass_inds):
        hist, _ = np.histogram(sgal.mag2[tpagb_mass_ind], bins=smg.bins)
        axs[2].semilogx(hist, smg.bins[1:], color=cols[i], ls='steps', lw=2)

    fig1, ax1 = plt.subplots()
    tpagb_imasses = sgal.data.get_col('m_ini')[sgal.itpagb]                
    tpagb_amasses = sgal.data.get_col('Mact')[sgal.itpagb]                
    dm = tpagb_imasses-tpagb_amasses
    ax1.plot(dm, sgal.mag2[sgal.itpagb], '.')
    
    outfile = outfile.replace('%s.png' % extra, '%s_by_mass.png' % extra)
    plt.savefig(outfile, dpi=300, bbox_to_inches='tight')
    print 'wrote %s' % outfile
    return sgal

def cslf(sgals, outfile=None):
    '''
    A simple CSLF plot.
    Takes a list of rsp.simgalaxy types.
    This takes the mag to be Mbol, and uses the first line of the trilegal
    catalogue to get dmod and Av.
    
    If an outfile is specified, will save fig.
    '''
    #sgals = [rsp.Galaxies.simgalaxy(tri_out, filter1='J', filter2='Ks',
    #                                photsys='2mass') for tri_out in tri_outs]

    [sgal.load_ic_mstar() for sgal in sgals]
    bmap = brewer2mpl.get_map('Set1', 'Qualitative', 3)
    cols = bmap.mpl_colors  
    bins = np.arange(-6.5, -2.5, 0.15)

    fig, ax = plt.subplots(figsize=(8, 8))
    for i, sgal in enumerate(sgals):
        model = sgal.name.split('_')[-1].split('.dat')[0]
        lab = galaxy_tests.translate_model_name(model) + ', $N=%i$' % (len(sgal.icstar))
        Mbol = sgal.data.get_col('mbol') - sgal.data.get_col('m-M0')[0] - sgal.data.get_col('Av')[0]
        plt.hist(Mbol[sgal.icstar], bins=bins, histtype='step', lw=5-i, color='white')
        plt.hist(Mbol[sgal.icstar], bins=bins, histtype='step', label=lab, lw=4-i, color=cols[i])
    ax.legend(frameon=False, prop={'size': 16}, loc=0)
    ax.set_xlim()[::-1]
    ax.set_xlabel('$M_{\\rm bol}$', fontsize=20)
    ax.set_ylabel('$N_c$', fontsize=20)
    plt.tick_params(labelsize=16)
    if outfile is not None:
        plt.savefig(outfile, dpi=300)
    return

def color_mdot_plot(sgals):
    nmodels = len(sgals)
    bmap = brewer2mpl.get_map('Set1', 'Qualitative', nmodels)
    cols = bmap.mpl_colors
    results = load_raw_vmc_data()
    data_color = results['Jmag2'] - results['Ksmag2']
    data_logML = results['logML']
    data_icstar = np.nonzero(results['Cl'] == 'C')
    data_imstar = np.nonzero(results['Cl'] == 'O')
    fig, (axs) = plt.subplots(nrows=nmodels, sharex=True, sharey=True, figsize=(8,8))
    for i, sgal in enumerate(sgals):
        model = sgal.name.split('_')[-1].split('.dat')[0]
        lab = galaxy_tests.translate_model_name(model)
        logml = sgal.data.get_col('logML')
        color = sgal.data.get_col('J') - sgal.data.get_col('Ks')
        axs[i].plot(color[sgal.icstar], logml[sgal.icstar], '.', label=lab, color=cols[i])
        axs[i].plot(color[sgal.imstar], logml[sgal.imstar], 'x', label=lab, color=cols[i])
        axs[i].plot(data_color[data_icstar], data_logML[data_icstar], '.', color='k')
        axs[i].plot(data_color[data_imstar], data_logML[data_imstar], 'x', color='k')
        axs[i].text(0.85, 0.1, lab, transform=axs[i].transAxes, fontsize=16)
    
    axs[1].set_ylabel('$\log \dot{M}\ ({\\rm M_\odot/yr})$', fontsize=20)
    axs[0].set_ylim(-11, -4)
    axs[0].yaxis.set_major_locator(MultipleLocator(2))
    axs[0].yaxis.set_minor_locator(MultipleLocator(.5))
    axs[0].xaxis.set_minor_locator(MultipleLocator(.2))
    axs[2].set_xlabel('$J-Ks$', fontsize=20)
    plt.tick_params(labelsize=16)
    fig.savefig('mdot_jks.png', dpi=300)
    return

def main():
    overwrite = True
    loidl = [True, False]
    photsys = '2mass'
    extra = ''
    for i in range(len(loidl)):
        if loidl is True:
            extra = '_loidl_%s' % photsys
        else:
            extra = '_%s' % photsys
        outputs = make_trilegal_sim(loidl=loidl[i],
                                    photsys=photsys,
                                    overwrite=overwrite,
                                    extra=extra)

        sgals = [make_plot(output, extra=extra) for output in outputs]
        outfile = os.path.join(os.path.split(output)[0], 'cslf%s.png' % extra)
        cslf(sgals, outfile=outfile)
        
if __name__ == "__main__":
    import pdb
    pdb.set_trace()
    main()
Exemplo n.º 6
0
def color_by_arg(bins=None,
                 cmap=None,
                 ax=None,
                 fig=None,
                 labelfmt='$%.3f$',
                 xdata=None,
                 ydata=None,
                 coldata=None,
                 xlim=None,
                 ylim=None,
                 slice_inds=None,
                 legend=True,
                 filter1=None,
                 filter2=None,
                 ymag=None):
    if fig is None:
        fig = plt.figure()
    if ax is None:
        ax = plt.axes()
    if bins is None:
        bins = 10
    if slice_inds is not None:
        xdata = xdata[slice_inds]
        ydata = ydata[slice_inds]
        coldata = coldata[slice_inds]
    # need the bins to be an array to use digitize.
    if type(bins) == int:
        hist, bins = np.histogram(coldata, bins=bins)
    inds = np.digitize(coldata, bins)
    uinds = np.unique(inds)
    # digitize sticks all points that aren't in bins in the final bin
    # cut that bin, or plot will be meaningless..
    if uinds[-1] == len(bins):
        uinds = uinds[:-1]
    if cmap is None:
        if 3 <= len(uinds) <= 11:
            #bmap = brewer2mpl.get_map('Spectral', 'Diverging', len(uinds))
            bmap = brewer2mpl.get_map('Paired', 'Qualitative', len(uinds))
            cols = bmap.mpl_colors
        else:
            cols = rg.discrete_colors(len(uinds), colormap='RdYlGn')
    else:
        cols = rg.discrete_colors(len(uinds), colormap=cmap)
    sub_inds = np.array([])
    nc = len(cols[0])
    colors = np.ndarray(shape=(len(xdata), nc), dtype=float)
    labs = []
    for j, i in enumerate(uinds):
        sinds, = np.nonzero(inds == i)
        N = len(sinds)
        if N == 0:
            continue
        if labelfmt != '':
            labs.append(labelfmt % bins[i])  # bins are left bin edges.
        colors[sinds] = cols[j]
        sub_inds = np.append(sub_inds, sinds)
    inds = map(int, sub_inds[:])
    np.random.shuffle(inds)

    ax.scatter(xdata[inds],
               ydata[inds],
               marker='o',
               s=15,
               edgecolors='none',
               color=colors[inds])

    if xlim is None:
        xlim = (xdata.min(), xdata.max())
    if ylim is None:
        ylim = (ydata.max(), ydata.min())
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    if ymag is None:
        ymag = filter2
    if filter1 is not None and filter2 is not None:
        ax.set_xlabel('$%s-%s$' % (filter1, filter2), fontsize=20)
        ax.set_ylabel('$%s$' % ymag, fontsize=20)
        ax.tick_params(labelsize=16)

    if legend is True:
        # fake out the legend...
        [
            ax.plot(999, 999, 'o', color=cols[i], mec=cols[i], label=labs[i])
            for i in range(len(labs))
        ]
        ax.legend(loc=0, numpoints=1, frameon=False)

    return fig, ax