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)
Exemplo n.º 2
0
def do_everything(infile):
    '''
    This script formats Paola's tracks and creates the files needed to use them
    with TRILEGAL as well as the option to make diagnostic plots.

    infile is an input_file object. See class InputFile

    WHAT'S GOING ON:
    Here is what it takes to go from Paola's agb tracks to trilegal:

    1. Paola's tracks
    2. Paola's tracks formatted for trilegal
    3. trilegal files that link to Paola's formatted tracks

    1. Paola's tracks should have naming scheme
        [mix]/[set]/[Trash]_[metallicity]_[Y]/[track_identifier]
    ex agb_caf09_z0.008/S1/agb_*Z*.dat
    ex CAF09/S_SCS/*Z*/agb_*Z*.dat
    These can go anywhere, and do not need to be included in trilegal
    directories.

    2. Paola's tracks are formatted for trilegal with no header file.
    These go in trilegal_1.3/isotrack/AGB_TRACKS/Z[metallicity]_[mix]_[set].dat
    They only include the quiescent phases and also a column with dL/dT
    See AGBTracks class.

    3. trilegal needs two files to link to Paola's formatted tracks
       a. track file goes here: trilegal_1.3/isotrack/tracce_[mix]_[set].dat
       b. cmd_input_file that links to the track file
          goes here trilegal_1.3/cmd_input_[mix]_[set].dat
    '''
    # set up file names and directories, cd to paola's tracks.
    AGB_file_setup(infile)

    # list of isofiles, zs, and ys to send to tracce file.
    isofiles, Zs, Ys = [], [], []
    imfr_data = np.array([])
    lifetime_data = np.array([])
    for metal_dir in infile.metal_dirs:
        metallicity, Y = metallicity_from_dir(metal_dir)
        print 'Z = %.4f' % metallicity
        if infile.diagnostic_dir0 is not None:
            diagnostic_dir = os.path.join(infile.diagnostic_dir0,
                                          infile.agb_mix,
                                          infile.set_name,
                                          metal_dir)  + '/'
            rsp.fileIO.ensure_dir(diagnostic_dir)
            # update infile class to place plots in this directory
            infile.diagnostic_dir = diagnostic_dir

        agb_tracks = rsp.fileIO.get_files(os.path.join(infile.working_dir,
                                                   metal_dir),
                                                   infile.track_identifier)
        agb_tracks.sort()

        iso_name_conv = '_'.join(('Z%.4f' % metallicity, infile.name_conv))
        isofile = os.path.join(infile.home, infile.isotrack_dir, iso_name_conv)

        if infile.over_write is False and os.path.isfile(isofile):
            print 'not over writing %s' % isofile
            out = None
        if infile.over_write is True:
            out = open(isofile, 'w')
            out.write('# age(yr) logL logTe m_act mcore c/o period ip')
            out.write(' Mdot(Msun/yr) logTe X Y CNO dlogTe/dlogL \n')

        isofile_rel_name = os.path.join('isotrack', infile.isotrack_dir,
                                        iso_name_conv)
        print 'found %i tracks' % len(agb_tracks)
        for agb_track in agb_tracks:
            # load track
            track = fileIO.get_numeric_data(agb_track)
            if track == -1:
                continue

            if track.bad_track is True:
                continue

            #if not track.mass in infile.masses:
            #    continue

            assert metallicity == track.metallicity, \
                'directory and track metallicity do not match'

            # make iso file for trilegal
            if out is not None:
                fileIO.make_iso_file(track, out)

            # save information for lifetime file.
            lifetime_datum = np.array([metallicity, track.mass, track.tauc,
                                       track.taum])

            lifetime_data = np.append(lifetime_data, lifetime_datum)

            # make diagnostic plots
            if infile.diagnostic_dir0 is not None and infile.diag_plots is True:
                assert metallicity_from_dir(infile.diagnostic_dir)[0] == \
                    track.metallicity, 'diag dir met wrong!'
                graphics.diag_plots(track, infile)

            # save information for imfr
            if infile.make_imfr is True:
                M_s = track.get_col('M_star')
                imfr_datum = np.array([M_s[0], M_s[-1], float(metallicity)])
                imfr_data = np.append(imfr_data, imfr_datum)

        if out is not None:
            out.close()
            print 'wrote', isofile

        fileIO.make_local_copy(isofile, dest=infile.make_copy)
        # keep information for tracce file
        isofiles.append(isofile_rel_name)
        Ys.append(Y)
        Zs.append(metallicity)
        #graphics.bigplots(agb_tracks, infile)

    # make file to link cmd_input to formatted agb tracks
    fileIO.make_met_file(infile.tracce_file, Zs, Ys, isofiles)

    fileIO.make_local_copy(infile.tracce_file, dest=infile.make_copy)

    # make cmd_input file
    cmd_in_kw = {'cmd_input_file': infile.cmd_input_file,
                 'file_tpagb': infile.tracce_file_rel,
                 'mass_loss': infile.mass_loss,
                 'file_isotrack': infile.file_isotrack}
    fileIO.write_cmd_input_file(**cmd_in_kw)

    if infile.make_imfr is True and infile.diagnostic_dir0 is not None:
        ifmr_file = os.path.join(infile.diagnostic_dir0, infile.agb_mix,
                                 infile.set_name,
                                 '_'.join(('ifmr', infile.name_conv)))
        ncols = 3
        nrows = imfr_data.size/ncols
        fileIO.savetxt(ifmr_file, imfr_data.reshape(nrows, ncols),
                       header='# M_i M_f Z \n')
        graphics.plot_ifmr(ifmr_file)

    if infile.diagnostic_dir0 is not None and infile.diag_plots is True:
        lifetime_file = os.path.join(infile.diagnostic_dir0, infile.agb_mix,
                                     infile.set_name,
                                     '_'.join(('tau_cm', infile.name_conv)))
        ncols = 4
        nrows = lifetime_data.size/ncols
        fileIO.savetxt(lifetime_file, lifetime_data.reshape(nrows, ncols),
                       header='# z mass tauc taum\n')
        graphics.plot_cluster_test(lifetime_file, infile)

    os.chdir(infile.home)
    return infile.cmd_input_file
Exemplo n.º 3
0
def compare_mass_loss(masses=1.0, z=0.001, sets=['NOV13', 'OCT13', 'NOV13eta0'],
              paola=False):
    '''
    made to plot a comparison between several mass prescriptions.
    Labels for the plot are set up stupidly, maybe in in_dict or labels arg...
    '''
    from matplotlib.ticker import NullFormatter

    teff_max = 3.5
    track_files = None
    if paola is True:
    # hack to use specific tracks from paola
        track_dir = research_path + '/TP-AGBcalib/AGBTracks/plots_for_paperI/'
        file_end = '_Mc0.00_dMc0.00_Tbd6.40_L0.00_dL0.00_C0.00_Nr3.00_rates0_KOPv_KMOLv.dat'
        if masses == 2.0:
            track_files = \
             [track_dir + 'agb_2.00_Z0.00100000_Mdot50_eta0.00' + file_end,
              track_dir + 'agb_2.00_Z0.00100000_Mdot49_eta0.40' + file_end,
              track_dir + 'agb_2.00_Z0.00100000_Mdot48_eta8.00' + file_end,
              track_dir + 'agb_2.00_Z0.00100000_Mdot50_eta0.40' + file_end]
            teff_max = 3.4
        if masses == 1.0:
            track_files = \
             [track_dir + 'agb_1.00_Z0.00100000_Mdot50_eta0.00' + file_end,
              track_dir + 'agb_1.00_Z0.00100000_Mdot49_eta0.40' + file_end,
              track_dir + 'agb_1.00_Z0.00100000_Mdot48_eta8.00' + file_end,
              track_dir + 'agb_1.00_Z0.00100000_Mdot50_eta0.40' + file_end]
            teff_max = 3.4

    labels = ['$\\dot{M}_{\\rm{pre-dust}}=0.0$','$\\rm{R75}$',
          '$\\rm{SC05}$', '$\\rm{mSC05}$']

    if track_files is not None:
        nrows = len(track_files)
    else:
        nrows = len(sets)
    fig, axs = plt.subplots(nrows=nrows, ncols=2, figsize=(8, 8))
    anorm = 1e6
    xlab0 = '\\rm{Age}\ (10^6\ \\rm{yr})'
    ylab0 = '\log\ \dot{M}\ (\\rm{M_\odot\ yr}^{-1})'
    ylab1 = '\log\ L\ (L_\odot)'
    xlab1 = '\log\ T_{\\rm eff}\ (\\rm{K})'

    agb_tracks_dir = research_path + 'TP-AGBcalib/AGBTracks/CAF09'

    if type(masses) is not list:
        masses = [masses]
    cols = ['k']

    for j, mass in enumerate(masses):
        if track_files is None:
            tnames = []
            labels = []
            for tset in sets:
                label = translate_model_name(tset)
                direc = os.path.join(agb_tracks_dir, 'S_' + tset)
                direc, = [os.path.join(direc, d)
                        for d in os.listdir(direc) if str(z) in d]
                tname = rsp.fileIO.get_files(direc, 'agb_%.2f*' % mass)[0]
                tnames.append(tname)
                labels.append('$%s$' % label)
            tracks = [fileIO.get_numeric_data(t) for t in tnames]
        else:
            tracks = [fileIO.get_numeric_data(t) for t in track_files]

        for i in range(len(tracks)):
            axs[i][0].plot(tracks[i].data_array['ageyr']/anorm,
                           tracks[i].data_array['dMdt'],
                           label='$M=%g\ M_\odot$' % mass, lw=1, color=cols[j])
            axs[i][0].plot(tracks[i].data_array['ageyr'][tracks[i].cstar]/anorm,
                           tracks[i].data_array['dMdt'][tracks[i].cstar],
                           lw=1, color='darkred')
            axs[i][1].plot(tracks[i].data_array['T_star'],
                           tracks[i].data_array['L_star'],
                           label='$M=%g\ M_\odot$' % mass, lw=1, color=cols[j])
            axs[i][1].plot(tracks[i].data_array['T_star'][tracks[i].cstar],
                           tracks[i].data_array['L_star'][tracks[i].cstar],
                           lw=1, color='darkred')
            axs[i][0].annotate(labels[i], (0.03, 0.96), fontsize=fontlarge,
                               xycoords='axes fraction', va='top')
    axs[-1, 0].set_xlabel('$%s$' % xlab0, fontsize=fontlarge)
    axs[-1, 1].set_xlabel('$%s$' % xlab1, fontsize=fontlarge)
    plt.annotate('$%s$' % ylab0, (0.03, 0.5), fontsize=fontlarge, va='center',
               xycoords='figure fraction', rotation='vertical')
    plt.annotate('$%s$' % ylab1, (0.95, 0.5), fontsize=fontlarge, va='center',
               xycoords='figure fraction', rotation='vertical')

    [ax.yaxis.tick_right() for ax in axs.flatten()[1::2]]
    [ax.xaxis.set_major_formatter(NullFormatter())
     for ax in axs.flatten()[:-2]]

    # mass loss
    [ax.set_ylim(-11.5, -4.5) for ax in axs[:, 0]]

    # log l
    [ax.set_ylim(2.81, 4.25) for ax in axs[:, 1]]

    # log te
    [ax.set_xlim(3.66, teff_max) for ax in axs[:, 1]]

    # age Myr
    [ax.set_xlim(0, 2.45) for ax in axs[:, 0]]

    # top left plot only
    if paola is False:
        [ax.legend(loc=4, fontsize=fontlarge, frameon=False)
     for ax in [axs.flatten()[0]]]

    fig.subplots_adjust(wspace=0.02, hspace=0.02)
    plt.savefig('compare_massloss_M%g_Z%g.png' % (masses[0], z), dpi=150)
    return axs
Exemplo n.º 4
0
def compare_agb_lifetimes():
    import glob
    track_loc = research_path + \
    'TP-AGBcalib/AGBTracks/plots_for_paperI/agbz001_3dup/'

    models = ['NOV13', 'NOV13eta0', 'OCT13']
    model_name = translate_model_name('nov13')

    # these two have to line up:
    search_formats = ['*dL0.0*', '*dL0.50*', '*dL2*']
    labels = [r'%s' % model_name,
              r'%s: $0.5\lambda$' % model_name,
              r'%s: $2\lambda$'  % model_name]

    track_sets = [rsp.fileIO.get_files(track_loc, sf) for sf in search_formats]
    cols1 =  ['k', '#d73027', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4']
    bmap = brewer2mpl.get_map('Blues', 'Sequential', 9)
    cols2 = bmap.mpl_colors[3::2]

    fig, axs = plt.subplots(ncols=2, figsize=(10, 5), sharex=True, sharey=True)

    for i, track_set in enumerate(track_sets):
        tracks = np.array([fileIO.get_numeric_data(t) for t in track_set])
        tracks = tracks[np.argsort([t.mass for t in tracks])]
        masses = np.array([t.mass for t in tracks])
        taus = np.array([np.sum(t.data_array['dt']) for t in tracks])
        plt_kw = {'lw': 3, 'label': labels[i], 'color': cols1[i]}
        if i == 0:
            for ax in axs:
                ax.plot(masses, taus/1e6, lw=4, color='k')
                plt_kw['color'] = cols2[0]
                ax.plot(masses, taus/1e6, **plt_kw)
        else:
            axs[1].plot(masses, taus/1e6, lw=4, color='k')
            axs[1].plot(masses, taus/1e6, **plt_kw)

    for j in range(len(models)):
        model_name = models[j].replace('.dat', '').split('_')[-1]
        if models[j].lower() == 'nov13':
            continue

        base = research_path + \
            'TP-AGBcalib/AGBTracks/CAF09/S_%s' % model_name

        agb_track_loc = os.path.join(base, glob.glob1(base, '*0.001*')[0])

        track_names = [os.path.join(agb_track_loc, a)
                       for a in os.listdir(agb_track_loc)
                       if a.startswith('agb_') and not 'b_1.75' in a
                       and not 'b_1.80' in a]
        tracks = [fileIO.get_numeric_data(t) for t in track_names]
        tracks = [t for t in tracks if not t == -1 and t.data_array.size > 1]
        tracks = np.array(tracks)[np.argsort([t.mass for t in tracks])]

        masses = np.array([t.mass for t in tracks])
        taus = np.array([np.sum(t.data_array['dt']) for t in tracks])

        model_name = translate_model_name(model_name)
        plt_kw = {'lw': 3, 'label': model_name, 'color': cols2[j]}
    axs[0].plot(masses, taus/1e6, lw=4, color='k')
    axs[0].plot(masses, taus/1e6, **plt_kw)

    for ax in axs:
        ax.legend(loc=0, frameon=False, fontsize=fontsmall)
        ax.set_xlim(1, 2.95)
        ax.set_ylim(.25, 3.7)
        ax.set_xlabel(r'${\rm Initial\ Mass\ (M_\odot)}$', fontsize=fontlarge)
        ax.tick_params(labelsize=fontmid)

    fig.subplots_adjust(left=0.08, right=0.98, bottom=0.15, top=0.95,
                        wspace=0.01)
    axs[0].set_ylabel(r'${\rm Lifetime\ (Myr)}$', fontsize=fontlarge)

    plt.savefig('lambda_plot.png', dpi=150)
    return axs
Exemplo n.º 5
0
def agb_lifetimes(models, z=0.002):
    import glob
    tauss = []
    btauss = []
    for j in range(len(models)):
        print models[j]
        print
        fig, ax = plt.subplots()
        fig2, ax2 = plt.subplots()
        model_name = models[j].replace('.dat', '').split('_')[-1]
        agb_track_loc = research_path + \
            'TP-AGBcalib/AGBTracks/CAF09/S_%s/' % model_name
        base = research_path + \
            'TP-AGBcalib/AGBTracks/CAF09/S_%s' % model_name
        if z == 'all':
            zs = np.array([d.split('_')[1].replace('Z','')
                           for d in glob.glob1(base, '*')], dtype=float)
        else:
            zs = [z]
        zs = np.array([i for i in zs if i <= 0.008])
        if len(zs) > 8.:
            zs = zs[::2]
        print zs
        cnum = np.max([len(zs), 3])
        bmap = brewer2mpl.get_map('Blues', 'Sequential', cnum + 1)
        cols = bmap.mpl_colors[1:]
        for i, z in enumerate(np.sort(zs)):
            try:
                agb_track_loc = os.path.join(base, glob.glob1(base, '*%g*' % z)[0])
            except IndexError:
                print 'no Z=%g tracks in %s' % (z, base)
                continue
            if not os.path.isdir(agb_track_loc) is True:
                print model_name, 'no agb tracks found'
            model_name = translate_model_name(models[j])
            agb_track_names = [os.path.join(agb_track_loc, a)
                               for a in os.listdir(agb_track_loc)
                               if a.startswith('agb_')]
            tracks = [fileIO.get_numeric_data(agb_track)
                      for agb_track in agb_track_names]
            tracks = [t for t in tracks if not t == -1 and t.data_array.size > 1]
            masses = np.array([t.mass for t in tracks])
            sort = np.argsort(masses)
            masses = masses[sort]
            tracks = np.array(tracks)[sort]
            logls = np.array([t.get_col('L_star') for t in tracks])
            brights = np.array([np.nonzero(logl > 3.4)[0] for logl in logls])
            #m_cs = np.array([t.get_col('M_c')[0] for t in tracks])
            #ax2.plot(masses, m_cs, lw=2, color='black')

            taus = np.array([np.sum(t.data_array['dt']) for t in tracks])
            btaus = np.array([np.sum(t.data_array['dt'][b])
                              for t, b in zip(tracks, brights)])
            tauss.append(taus)
            btauss.append(btaus)
            plt_kw = {'lw': 3, 'label': '$Z=%g$' % z, 'color': cols[i]}
            ax.plot(masses, taus/1e6, lw=4, color='k')
            ax2.plot(masses, btaus/1e6, lw=4, color='k')

            ax.plot(masses, taus/1e6, **plt_kw)
            ax2.plot(masses, btaus/1e6, **plt_kw)
            with open('tpagb_lifetimes_S_%s_Z%g.dat' % (models[j], z), 'w') as out:
                out.write('# mass tpagb_tau tpagb_tau_bright \n')
                np.savetxt(out, np.array([masses, taus, btaus]).T, fmt='%.3f')


        for ax in [ax, ax2]:
            ax.set_xlabel('${\\rm Initial\ Mass\ (M_\odot)}$', fontsize=fontlarge)
            ax.set_ylabel('${\\rm Lifetime\ (Myr)}$', fontsize=fontlarge)
            ax.legend(loc=0, frameon=False)
            ax.set_xlim(0, 5)
            ax.set_ylim(0, 5)
        ax2.annotate('$\log L/L_\odot > 3.4$', (0.03, 0.97), xycoords='axes fraction',
                     fontsize=fontlarge, va='top')
        ax2.set_ylabel(ax2.get_ylabel().replace('(Myr)', '(Myr)'))
        #ax2.set_ylabel('${\\rm Pre\!-\!Flash\ Core\ Mass\ (M_\odot)}$', fontsize=24)

        fig.savefig('tpagb_lifetime_%s.png' % (models[j]), dpi=150)
        fig2.savefig('tpagb_lifetime_bright_%s.png' % (models[j]), dpi=150)

    return