Example #1
0
def runStats(runf,
             props=[
                 'star_mass', 'log_Teff', 'c_core_mass', 'total_mass_h1',
                 'total_mass_he4', 'log_L', 'log_R'
             ]):
    """Prints out relevant run information such as remnant C core and 
    final mass.
    
    Args:
        runf (str): run folder to look in.
        props (list of str): h.header names to print out. default is 
        ['star_mass', 'log_Teff', 'c_core_mass', 'total_mass_h1', 
        'total_mass_he4', 'log_L', 'log_R'].
    
    """
    h = mr.MesaData(os.path.join(runf, "LOGS/history.data"))
    l = mr.MesaLogDir(os.path.join(runf, "LOGS"))
    print ("Version: {version_number}\nInitial Mass(Z): "\
          "{initial_mass} ({initial_z})".format(**h.header_data))
    print("Profiles found: {}".format(len(l.profile_numbers)))
    print("Models run: {}".format(h.data('model_number')[-1]))
    print("Initial zones: {}".format(max(h.data('num_zones'))))
    print("\nSimtime: {:10.9} Gyr\n".format(h.data('star_age')[-1] / 1e9))
    print("{:20}{:<20} {:<20}\n".format('Prop', 'Initial', 'Final'))
    otp = "{:20}{:<20.5f} {:<20.5f}"
    for arg in props:
        print(otp.format(arg, h.data(arg)[0], h.data(arg)[-1]))
    if 'c_core_mass' in props:
        p = l.profile_data()
        zone = np.where(p.mass < p.c_core_mass)[0][0]
        print ("Final Mass and Radius of the Carbon Core: "\
              "{:6.5e} Msun {:6.5e} cm".format(p.mass[zone], p.R[zone]*_Rs))
        print("150km match head x_match: {:.6e}".format(p.R[zone] * _Rs /
                                                        np.sqrt(2.)))
    return len(l.profile_numbers)
Example #2
0
def plot_hist(folder, xaxis, yaxis, save=False, name=None):
    '''
    Basic function to quick plot any parameter from history file

    Parameters:
    -----------
    folder : str
            LOGS directory
    xaxis  : str
            parameter from history to plot on xaxis
    yaxis  : str
            parameter from history to plot on yaxis
    save    : bool
            True to save the plot, False to only show. Default is False
    name    : str
            if save = True, name is a string with filename to ouput
    '''

    path = ms.MesaLogDir(folder)
    hist = path.history
    x = hist.data(xaxis)
    y = hist.data(yaxis)
    plt.plot(x, y, 'k.-')
    plt.ylabel(yaxis)
    plt.xlabel(xaxis)

    if save is True:
        plt.savefig(name + '.pdf')
        plt.savefig(name + '.png')
        return 'File save with name ' + name
    else:
        plt.show()
Example #3
0
def getprofile(fname, pnumber):

    #print(fname, pnumber)

    profiles_indir = mr.MesaLogDir(fname)
    pr = profiles_indir.profile_data(profile_number=pnumber)

    teff = pr.Teff
    r = pr.photosphere_r
    l = pr.photosphere_L
    m = pr.initial_mass
    m_solar = 1.9892 * 10**(33)
    r_solar = 6.9598 * 10**(10)
    R = r * r_solar
    M = m * m_solar
    G = 6.67428 * 10**(-8)
    g = G * M / R**2

    chi_l = (np.abs(np.log10(l) - Log_L_obs) / Log_L_obs_unc)**2
    chi_teff = (np.abs(np.log10(teff) - Log_Teff_obs) / Log_Teff_obs_unc)**2
    chi_g = (np.abs(np.log10(g) - Log_g_obs) / Log_g_obs_unc)**2

    observations = [chi_l, chi_teff, chi_g]

    return observations
Example #4
0
def getpdata(newdir, pnumber):

    l = mr.MesaLogDir(newdir)

    p = l.profile_data(profile_number=pnumber)
    mass = p.initial_mass

    return mass
Example #5
0
def mesa_args(direc, profile):
    '''read in what mesa data file to use'''
    arg1 = direc
    arg = arg1.split('_')
    hist = "history_" + arg[0] + ".data"
    direc = mr.MesaLogDir(log_path=arg1, history_file=hist)
    prof = direc.profile_data(int(profile))

    # read info about the MESA star
    lab_mass = str(round(prof.star_mass, 3))
    year = str(round(prof.star_age, 3))
    model = str(round(prof.model_number, 3))
    mesa_lab = year + " yr, " + lab_mass + " $M_{\\odot}$, " + model
    return (prof, mesa_lab, lab_mass)
Example #6
0
def getWholeHistory(folders, xkey='log_Teff', ykey='log_L'):
    """returns aggregated history for a pair of 
    keys from a list of sorted folders. 
    Defaults to HR variables log_Teff and log_L
    """
    xvals, yvals = np.array([]), np.array([])
    for f in folders:
        h = mr.MesaData(os.path.join(f, "LOGS/history.data"))
        l = mr.MesaLogDir(os.path.join(f, "LOGS"))
        p = l.profile_data(profile_number=len(l.profile_numbers))
        xrow, yrow = getHistProp(p, h, xkey, ykey)
        xvals = np.append(xvals, xrow)
        yvals = np.append(yvals, yrow)
    return xvals, yvals
def getobsparams(fname):
    filename = 'temp1_l012.txt'
    list_of_lists = []
    pdata = []

    with open(filename) as f:
        for line in f:
            inner_list = [elt.strip() for elt in line.split(',')]
            list_of_lists.append(inner_list)

    for i in range(0, len(list_of_lists)):
        profnum = list_of_lists[i][4]
        profiles_indir = mr.MesaLogDir(fname)

        pr = profiles_indir.profile_data(profile_number=profnum)

        teff = pr.Teff
        r = pr.photosphere_r
        l = pr.photosphere_L
        m = pr.initial_mass
        m_solar = 1.9892 * 10**(33)
        r_solar = 6.9598 * 10**(10)
        R = r * r_solar
        M = m * m_solar
        G = 6.67428 * 10**(-8)
        g = G * M / R**2

        pdata += [[np.log10(teff), np.log10(g), np.log10(l)]]

    np.asarray(pdata)
    np.savetxt("temp2_l012.txt", pdata, delimiter=",", newline="\n", fmt="%s")

    filename1 = 'temp1_l012.txt'
    filename2 = 'temp2_l012.txt'
    files = [[filename1, filename2]]

    with open('results_l012.txt', 'w') as outfile:
        for file in files:
            with open(file[0]) as newfile, open(file[1]) as newfile1:
                lines = zip(newfile, newfile1)
                for line in lines:
                    outfile.write(line[0].rstrip() + "," + line[1])

    return


#getobsparams('/home/janne/Gunter_project/44_tau/output_postms_3ms/LOGS-1.5-0.02-0.7-0.2')
Example #8
0
def centralCond(runf, prof_number, show=False, tstamp=True):
    """Plots central rho vs central t found in the profile.
    
    Args:
        runf (str): run folder to look in.
        prof_number (int): profile to plot.
        byM (bool): plot by mass (True) or by radius (False).
        show (bool): if True, returns the mpl.figure object. 
        
    Returns:
        mpl.figure: plot of central rho vs central t.

    """
    h = mr.MesaData(os.path.join(runf, "LOGS/history.data"))
    l = mr.MesaLogDir(os.path.join(runf, "LOGS"))
    profs = l.profile_numbers
    if prof_number > len(profs):
        print("Profile not found. ({}/{})".format(prof_number, len(profs)))
    else:
        print("Plotting T_c vs Rho_c. {}/{}.".format(prof_number, len(profs)))
    p = l.profile_data(profile_number=prof_number)
    rmax = l.profile_data(profile_number=1).photosphere_r
    fig = plt.figure(figsize=(7, 5))
    layout = (1, 1)
    ax1 = plt.subplot2grid(layout, (0, 0),
                           aspect="auto",
                           adjustable='box-forced')
    plotCenterTRho(p, h, ax1)
    plt.tight_layout()
    if tstamp:
        ax1.annotate("{:0=8.7f}$\cdot 10^9$ yr".format(
            float(p.star_age) / 1e9),
                     xy=(0.70, 0.08),
                     xycoords='axes fraction',
                     fontsize=10)
    tag = 'trhoc'
    if not os.path.exists("{}/png/".format(runf)):
        os.mkdir("{}/png/".format(runf, tag))
        os.mkdir("{}/png/{}".format(runf, tag))
    elif not os.path.exists("{}/png/{}/".format(runf, tag)):
        os.mkdir("{}/png/{}".format(runf, tag))
    if show:
        return fig
    else:
        plt.savefig("{0}/png/{1}/{1}_{2:05}".format(runf, tag, p.model_number))
        plt.close(fig)
    print("Wrote: {0}/png/{1}/{1}_{2:05}".format(runf, tag, p.model_number))
def prep_mesa(base):
	'''
	Extract relevant information from MESA model for use with the ModeAnalyzer class below

	base--location of the mesa model
	
	'''
	ld=mesa_reader.MesaLogDir(base+'/LOGS')
	pidx=mesa_reader.MesaProfileIndex(base+'/LOGS/profiles.index')
	idx_last=pidx.model_numbers[-1]
	
	prof=ld.profile_data(model_number=idx_last)

	prof.R=(prof.R*u.R_sun).cgs
	prof.mass=(prof.mass*u.M_sun).cgs

	prof.Rho=prof.Rho*u.g*u.cm**-3.
	prof.P=prof.P*u.g*u.cm**-1.*u.s**-2.
	return prof
Example #10
0
def plot_prof(folder, xaxis, yaxis, mod_n, save=False, name=None):
    '''
    Basic function to quick plot any parameter from profiles file

    Parameters:
    -----------
    folder : str
            LOGS directory
    xaxis  : str
            parameter from history to plot on xaxis
    yaxis  : str
            parameter from history to plot on yaxis
    save    : bool
            True to save the plot, False to only show. Default is False
    name    : str
            if save = True, name is a string with filename to ouput
    '''

    path = ms.MesaLogDir(folder)

    if mod_n is None:
        profiles = path.model_numbers
        model = profiles[-1]
        # m_ind = -1
    else:
        model = mod_n
        # m_ind = -1  # mod_n

    prof = path.profile_data(model)
    x = prof.data(xaxis)
    y = prof.data(yaxis)
    plt.plot(x, y, 'k.-')
    plt.ylabel(yaxis)
    plt.xlabel(xaxis)

    if save is True:
        plt.savefig(name + '.pdf')
        plt.savefig(name + '.png')
        return 'File save with name ' + name
    else:
        plt.show()
Example #11
0
def print_totalm(path):
    '''
    Print final mass and total mass of h1, he4, c12 and o16

    Parameter
    --------
    path : strings
            path for LOGS directory
    '''

    np.set_printoptions(formatter={'float': '{: 0.5}'.format})

    print('Total mass of isotopes (Msun)')
    print('mf,     h1,     he4,     c12,     o16,')
    fol = ms.MesaLogDir(path)
    hist = fol.history
    mass = hist.data('star_mass')
    t_h1 = hist.data('total_mass_h1')
    t_he = hist.data('total_mass_he4')
    t_c12 = hist.data('total_mass_c12')
    t_o16 = hist.data('total_mass_o16')
    print(mass[-1], t_h1[-1], t_he[-1], t_c12[-1], t_o16[-1])
Example #12
0
def plot_lum(folder, title=' ', save=False, name=None):
    '''
    Function to plot the Luminosity versus Age to check if occured
    cristalization

    Parameter
    ---------
    folder  : str
            path to LOGS folder -> '/path/to/LOGS/'
    title   : str
            title to use on the plot -> 'title'
    save    : bool
            if True, save a .png file of the plot
    name    : str
            name of the .png file if the parameter save is True

    Returns
    -------
    show the plot or save a .png file
    '''

    path = ms.MesaLogDir(folder)
    hist = path.history
    lum = hist.data('log_L')
    age = hist.data('star_age')  # age = hist.data('star_age')
    mi = hist.initial_mass
    plt.figure(figsize=(10, 8))
    plt.plot(age, lum)
    plt.suptitle(r'$\log L$ X Age', fontsize=18)
    plt.title('Mi = ' + str(mi) + '  ' + title)
    plt.xlabel('Age [Years]',
               fontsize=16)  # plt.xlabel('Age [years]', fontsize=16)
    plt.ylabel(r'$\log L$', fontsize=16)

    if save is True:
        plt.savefig(name + '.pdf')
        return 'File save with name ' + name
    else:
        plt.show()
Example #13
0
def hrd(folder, title=' ', save=False, name=None):
    '''
    Function to plot the Hertzsprung-Russel diagram

    Parameter
    ---------
    folder  : str
            path to LOGS folder -> '/path/to/LOGS/'
    title   : str
            title to use on the plot -> 'title'
    save    : bool
            if True, save a .png file of the plot
    name    : str
            name of the .png file if the parameter save is True

    Returns
    -------
    show the plot or save a .png file
    '''

    path = ms.MesaLogDir(folder)
    hist = path.history
    lum = hist.data('log_L')
    teff = hist.data('log_Teff')
    mi = hist.initial_mass
    plt.figure(figsize=(10, 8))
    plt.plot(teff, lum)
    plt.gca().invert_xaxis()
    plt.suptitle('HR Diagram', fontsize=18)
    plt.title('Mi = ' + str(mi) + '  ' + title)
    plt.xlabel(r'$\log T_{Eff}$', fontsize=16)
    plt.ylabel(r'$\log L$', fontsize=16)

    if save is True:
        plt.savefig(name + '.pdf')
        return 'File save with name ' + name
    else:
        plt.show()
Example #14
0
def get_mat_mcenter(path):
    '''
    Extract the initial and final mass, total star age, log L and Teff in the
    last model of evolution, and central masses of h1, he4, c12, n14, o16, ne20
    and mg24. Age in years

    Parameters
    ----------
    path : string
            LOGS directory path

    Returns
    -------
    total star age in years, log Teff, Teff
    '''

    fol = ms.MesaLogDir(log_path=path)
    h = fol.history
    age = h.data('star_age')
    logT = h.data('log_Teff')
    teff = 10**logT
    logL = h.data('log_L')
    c_h1 = h.data('center_h1')
    c_he4 = h.data('center_he4')
    c_c12 = h.data('center_c12')
    c_n14 = h.data('center_n14')
    c_o16 = h.data('center_o16')
    c_ne20 = h.data('center_ne20')
    mi = h.data('star_mass')

    prof_numbers = fol.profile_numbers
    prof = fol.profile_data(profile_number=prof_numbers[-1])
    c_mg24 = prof.data('mg24')

    return np.array([
        mi[0], mi[-1], age[-1], logL[-1], teff[-1], c_h1[-1], c_he4[-1],
        c_c12[-1], c_n14[-1], c_o16[-1], c_ne20[-1], c_mg24[0]
    ])
Example #15
0
def get_profs(history, dirs):
    '''get the indices of profiles during various interesting points in the stars evolution '''
    # 2d array
    profs = []

    # run thru each star we want to plot
    for i in range(len(history)):
        direc = mr.MesaLogDir(log_path=dirs[i], history_file=history[i])

        profs_star = []
        # cycle thru all profiles sequentially
        for j in range(len(dirs[i].profile_numbers)):
            # data for this profile
            dat = dirs[i].profile_data(profile_numbers[j])

            # preZAMS
            nucpercent = 10**(dat.power_nuc_burn / dat.photosphere_L)
            if nucpercent > 0.900 and hit_ZAMS == False and history[
                    i].star_age[j] > 50.0:
                print("")

        # add this array to our 2D array
        profs.append(profs_star)
Example #16
0
# plot_mesa_hr.py
# plots the output of mesa onto an hr diagram

import sys
import os
import string
import numpy as np
import pandas as pd
from astropy.io import ascii
from astropy.io import fits
import matplotlib.pyplot as plt
import mesa_reader as mr

# Read MESA Output
log_dir = mr.MesaLogDir('/Users/galaxies-air/Courses/Stars/ps1_mesa/LOGS')
profile = log_dir.profile_data(800)

# Read polytrope files
poly_colnames = ['xi', 'theta', 'd_theta']

n15_file = '/Users/galaxies-air/code/courses/stars/ps2/output/Poly-n1.5.txt'
n15_df = ascii.read(n15_file).to_pandas()
n15_df.columns = poly_colnames

n3_file = '/Users/galaxies-air/code/courses/stars/ps2/output/Poly-n3.0.txt'
n3_df = ascii.read(n3_file).to_pandas()
n3_df.columns = poly_colnames

axisfont = 14
ticksize = 12
ticks = 8
Log_g_obs_unc = 0.1

n = 10
#Three sigma intervals
Log_Teff_ns = n * Log_Teff_obs_unc
Log_L_ns = n * Log_L_obs_unc
Log_g_ns = n * Log_g_obs_unc

Log_Teff_lower = Log_Teff_obs - Log_Teff_ns
Log_Teff_upper = Log_Teff_obs + Log_Teff_ns
Log_L_lower = Log_L_obs - Log_L_ns
Log_L_upper = Log_L_obs + Log_L_ns
Log_g_lower = Log_g_obs - Log_g_ns
Log_g_upper = Log_g_obs + Log_g_ns

dire = mr.MesaLogDir('/home/janne/Gunter_project/44_tau/example_3ms/LOGS-1')

histnos = []
modelnos = []
profnos = []
filtered = []
#filtered1 = []
#filtered2 = []
#filtered3 = []
profarray = []

for root, dirs, files in sorted(
        os.walk('/home/janne/Gunter_project/44_tau/example_3ms/LOGS-3')):
    for file in files:
        if file.startswith('profile') and file.endswith(
                '.data'):  #and os.path.exists(file)==True:
Example #18
0
            #print(natsort.natsorted(dirs,reverse=True))

            h = mr.MesaData(dirs)
            mass = h.initial_mass
            index = h.star_age > 2.0e7
            noms_Teff = h.log_Teff[index]
            noms_L = h.log_L[index]
            #plot(h.log_Teff, h.log_L)
            #plot(noms_Teff, noms_L, label='%s$M_{\odot}$' %mass)
            #plt.gca().invert_xaxis()

            if file.endswith('profile1.data'):

                pdirs = os.path.join(root)
                print(pdirs)
                l = mr.MesaLogDir(pdirs)
                p = l.profile_data()
                Z = p.initial_z
                #M = p.initial_mass

            plt.plot(Log_Teff_obs, Log_L_obs, 'r*', MarkerSize=10)
            plt.rcParams.update({'font.size': 20})
            plt.plot(noms_Teff,
                     noms_L,
                     '.',
                     MarkerSize=5,
                     label='Mass=%s' % mass)

# set axis labels
xlabel(r'$\logT_{eff}$')
ylabel(r'$\logL$')
Example #19
0
def snapshot(runf,
             prof_number=1,
             byM=False,
             rmax=0.0,
             species=_ap13,
             show=False,
             core=False):
    """Plots a grid of general plots for the profile: Dens, 
    Temp, Pres, Abundances(X), and HR.
    
    Args:
        runf (str): run folder to look in or file to use.
        prof_number (int): profile to plot(skipped if runf is a file).
        byM (bool): plot by mass (True) or by radius (False).
        rmax (float): radius limit in Rsun/Msun (depending on byM).
        species (list): list of named species to plot on the X plot.
        show (bool): if True, returns the mpl.figure object. 

    """
    if os.path.isdir(runf):
        folder = True
        h = mr.MesaData(os.path.join(runf, "LOGS/history.data"))
        l = mr.MesaLogDir(os.path.join(runf, "LOGS"))
        profs = l.profile_numbers
        if prof_number > len(profs):
            print("Profile not found. ({}/{})".format(prof_number, len(profs)))
        else:
            print("Plotting Abundances. {}/{}.".format(prof_number,
                                                       len(profs)))
        p = l.profile_data(profile_number=prof_number)
        if byM and not rmax:
            rmax = p.initial_mass
        elif not byM and not rmax:
            rmax = l.profile_data(profile_number=1).photosphere_r
    else:
        folder = False
        p = mr.MesaData(os.path.join(runf))
        h = None
        if byM and not rmax:
            rmax = p.initial_mass
        elif not byM and not rmax:
            rmax = p.photosphere_r

    fig = plt.figure(figsize=(15, 9))
    # fill the grid with axes
    layout = (3, 3)
    ax1 = plt.subplot2grid(layout, (0, 0), aspect="auto")
    ax2 = plt.subplot2grid(layout, (1, 0),
                           aspect="auto",
                           adjustable='box-forced')  #, sharex=ax1)
    ax3 = plt.subplot2grid(layout, (2, 0),
                           aspect="auto",
                           adjustable='box-forced')
    ax4 = plt.subplot2grid(layout, (0, 1),
                           aspect="auto",
                           adjustable='box-forced',
                           rowspan=2)
    ax5 = plt.subplot2grid(layout, (2, 1),
                           aspect="auto",
                           adjustable='box-forced')

    plotMainProp(p,
                 ax1,
                 prop='dens',
                 byM=byM,
                 rmax=rmax,
                 tstamp=True,
                 color='black',
                 core=core)
    plotMainProp(p,
                 ax2,
                 prop='temp',
                 byM=byM,
                 rmax=rmax,
                 tstamp=False,
                 color='red',
                 core=core)
    plotMainProp(p,
                 ax3,
                 prop='pres',
                 byM=byM,
                 rmax=rmax,
                 tstamp=False,
                 color='green',
                 xtitle=True,
                 core=core)
    plotAbundances(p, ax4, species=species, byM=byM, rmax=rmax, core=core)
    if h is not None:
        plotHR(p, h, ax5)

    fig.subplots_adjust(hspace=0.5, wspace=0.4)
    tag = 'prof'
    if folder:
        # build filetree and show or save the figure
        if not os.path.exists("{}/png/".format(runf)):
            os.mkdir("{}/png/".format(runf, tag))
            os.mkdir("{}/png/{}".format(runf, tag))
        elif not os.path.exists("{}/png/{}/".format(runf, tag)):
            os.mkdir("{}/png/{}".format(runf, tag))
        if show:
            return fig
        else:
            plt.savefig("{0}/png/{1}/{1}_{2:05}".format(
                runf, tag, p.model_number))
            plt.close(fig)
        print("Wrote: {0}/png/{1}/{1}_{2:05}".format(runf, tag,
                                                     p.model_number))
    else:
        # don't save, just return the profile to the notebook
        return fig
def onedir(fname):
    Log_Teff_obs = 3.839
    #Log_L_obs = 1.340
    Log_g_obs = 3.6
    
    Log_Teff_obs_unc = 0.007
    #Log_L_obs_unc = 0.0065 
    Log_g_obs_unc = 0.1
    
    n = 3
    
    Log_Teff_ns = n*Log_Teff_obs_unc
    #Log_L_ns = n*Log_L_obs_unc
    Log_g_ns = n*Log_g_obs_unc
    
    Log_Teff_lower = Log_Teff_obs - Log_Teff_ns
    Log_Teff_upper = Log_Teff_obs + Log_Teff_ns
    #Log_L_lower = Log_L_obs - Log_L_ns
    #Log_L_upper = Log_L_obs + Log_L_ns
    Log_g_upper = Log_g_obs + Log_g_ns
    Log_g_lower = Log_g_obs - Log_g_ns
    
    radial_funda = 6.8980
    #radial_first = 8.9606
    
    #l = 10
    #radial_unc = l* 0.05
    #radial_funda_lower = radial_funda - radial_unc
    #radial_funda_upper = radial_funda + radial_unc
    #radial_first_upper = radial_first + radial_unc
    #radial_first_lower = radial_first - radial_unc

    frequencies = []
    frequency_dirs = []
    frequency_roots = []
    temp = []
    dires = []
    test_result = []
    logg_dires = []
    diffsndirs = []
    minimum = []


    for root, dirs, files in sorted(os.walk(fname)):
        logdirs = os.path.join(root)
        dires += [logdirs]
        for file in files:
            
            if file.startswith('history'):
                  
                    #print(os.path.join(root,file))
                direcs = os.path.join(root,file)
                rooties = os.path.join(root)
                #print(natsort.natsorted(dirs,reverse=True))
                
                h = mr.MesaData(direcs)
                mass = h.initial_mass
                model = h.model_number
                index = h.star_age > 2.0e7
                noms_model = model[index]
                noms_logg = h.log_g[index]
                
                
                logg_dir = [noms_logg, noms_model, rooties]
                logg_dires.append(logg_dir)
               
                noms_Teff = h.log_Teff[index]
                noms_L = h.log_L[index]
        
                test_result = np.zeros((len(noms_model),3))
                #rint(test_result)
                for i in range(0,len(noms_model)):
                    test_result[i][0] = noms_model[i]
                    test_result[i][1] = noms_logg[i]
                    test_result[i][2] = noms_Teff[i]
               
                plt.plot(noms_Teff, noms_logg, '-',label='M=%s' %mass)
            
            if file.startswith('profile') and file.endswith('.data'):
                
                profiledirs = os.path.join(root,file)
                
                pnum = re.search('profile(.+?).data', profiledirs)
            
                if pnum: 
                    pnums = pnum.group(1)  
                
                profiles_indir = mr.MesaLogDir(fname)
                pr = profiles_indir.profile_data(profile_number=pnums)
                pr_modelnos = pr.model_number
                
                
                if pr_modelnos == noms_model[0]:
                    cutoff = pnums
        
            if file.endswith('freqs.dat'):
                gyredirs = os.path.join(root,file)
                gyreroots = os.path.join(root)
                fnum = re.search('profile(.+?)-freqs.dat', gyredirs)
            
                if fnum: 
                    fnums = fnum.group(1)  
                if int(cutoff) <= int(fnums):
                    #print(fnums)
                    
                    #print(gyredirs)
                    
                    freqs = gyr.readmesa(gyredirs)
                    
                    frequencies += [freqs]
                    frequency_dirs += [gyredirs]
                    frequency_roots += [gyreroots]
                    allfreqs = [freqs ,gyredirs,gyreroots]
                    temp.append(allfreqs)
    
    profiles = []
    differs = []
    temp3 = []
    minValue = None
    
    
    for i in range(0,len(temp)):
        if size(temp[i][0]) ==1:
            continue
        if temp[i][0][0][1] == 1 and temp[i][0][1][1] == 2:
            #print('hej')
            
            succesfull_profiles = temp[i][1]
            profile_directories = temp[i][2]
            difference = np.abs(temp[i][0][0][4]-radial_funda)
            #print(difference)
            
            #difference_next = np.abs(temp[i+1][0][0][4]-radial_funda)
           
            currentValue = difference
            
            if minValue == None:
                minValue = currentValue
            else:
                minValue = min(minValue, currentValue)
                
        
            temp2 = [succesfull_profiles, difference]
            diffsndirs.append(temp2)
            
            profiles.append(profile_directories)
            differs.append(difference)
    
    minimum = differs.index(minValue)
    minimum_profile = diffsndirs[minimum]
    
    gnum = re.search('profile(.+?)-freqs.dat', minimum_profile[0])
            
    if gnum: 
        gnums = gnum.group(1)        
        
    profiledata = mr.MesaLogDir(fname)
    p = profiledata.profile_data(profile_number=gnums)
    
    teff = p.Teff
    #print(teff)
    logteff = np.log10(teff)
    lmodel = p.photosphere_L
    logl = np.log10(lmodel)
    modelno_profile = p.model_number 
    
    entry = np.where(logg_dires[0][1]== modelno_profile)
    best_logg = logg_dires[0][0][entry]
    
    plt.plot(logteff,best_logg,'k.', MarkerSize = 15)
    
    """

    results_final = []

    for root, dirs, files in sorted(os.walk('/home/janne/Gunter_project/44_tau/example_3ms/')):
        for dire in dirs:
            plt.figure(dire)
            dires = os.path.join(root,dire)
            #print(dires)
            results = petersen_plot(dires)
            results_final.append(results)
            #print(results)
            
            results
        #print(logteff)           
                    
    
    #alllogteffs.append(logteffs)
    
    #plt.plot([alllogteffs[i][0],alllogteffs[i][-1]],[working_logg_dires[0], working_logg_dires[-1]],'k--') 
    
    """

    # set axis labels
    xlabel(r'$\logT_{eff}$')
    ylabel(r'$\log(g)$')
    legend()
    plt.gca().invert_xaxis()
    plt.gca().invert_yaxis()
    plt.rcParams.update({'font.size': 20})
    

    #PLOT ERRORBOX:

    plt.plot([Log_Teff_lower, Log_Teff_upper, Log_Teff_upper, Log_Teff_lower, Log_Teff_lower], [Log_g_lower, Log_g_lower, Log_g_upper, Log_g_upper, Log_g_lower], 'r-.', alpha=0.5, linewidth=3)
    
    return best_logg,logteff
Example #21
0
# plot_mesa_hr.py
# plots the output of mesa onto an hr diagram

import sys
import os
import string
import numpy as np
import pandas as pd
from astropy.io import ascii
from astropy.io import fits
import matplotlib.pyplot as plt
import mesa_reader as mr

# Read MESA Output
log_dir_solar = mr.MesaLogDir(
    '/Users/galaxies-air/Courses/Stars/ps4/ps4_mesa_z0/LOGS')
log_dir_lowz = mr.MesaLogDir(
    '/Users/galaxies-air/Courses/Stars/ps4/ps4_mesa_z-2/LOGS')
profile_solar = log_dir_solar.profile_data(817)
profile_lowz = log_dir_lowz.profile_data(918)

axisfont = 14
ticksize = 12
ticks = 8
titlefont = 24
legendfont = 14
textfont = 16


def plot_mesa(x_solar, y_solar, x_lowz, y_lowz, xlabel, ylabel, savename):
    fig, ax = plt.subplots(figsize=(8, 7))
Example #22
0
def useful_profiles(dirname):
    histnos = []
    modelnos = []
    profnos = []
    filtered = []
    #filtered1 = []
    #filtered2 = []
    #filtered3 = []
    profarray = []

    dire = mr.MesaLogDir(dirname)
    for root, dirs, files in sorted(os.walk(dirname)):
        for file in files:
            if file.startswith('profile') and file.endswith(
                    '.data'):  #and os.path.exists(file)==True:
                #print(root,file)

                m = re.search('profile(.+?).data', file)

                if m:
                    modelno = m.group(1)
                    #print(modelnos)

                modelnos += [modelno]

            if file.startswith('history'):
                dirs = os.path.join(root, file)
                #print(dirs)
                #print(natsort.natsorted(dirs,reverse=True))

                h = mr.MesaData(dirs)
                Log_Teff_theo = h.log_Teff
                Log_L_theo = h.log_L
                Log_g_theo = h.log_g

                #mask = Log_Teff_lower < Log_Teff_theo and Log_Teff_upper > Log_Teff_theo

                histno = h.model_number
                histnos += [histno]
                histnos = np.array(histnos)

                for i in range(0, len(Log_Teff_theo)):
                    mask1 = Log_Teff_lower < Log_Teff_theo[
                        i] and Log_Teff_upper > Log_Teff_theo[
                            i] and Log_L_lower < Log_L_theo[
                                i] and Log_L_upper > Log_L_theo[
                                    i] and Log_g_lower < Log_g_theo[
                                        i] and Log_g_upper > Log_g_theo[i]
                    filtered += [mask1]

                filtered = np.array(filtered)

                array = histnos[0]
                array_filtered = array[filtered]

        #     for j in filtered:
        #         if j == True:
    profiles = []

    for i in modelnos:
        #i = int(i)

        p = dire.profile_data(profile_number=i)
        profno = p.model_number
        #print('Trues:')
        for number in array_filtered:
            #print(number)
            #for l in range(1,len(array_filtered)):
            if profno == number:
                print(i)

                #models = 'profile{}-freqs.data'.format(i)
                profiles.append(i)
                #print(models)
        #profnos += [profno]
    profiles

    return profiles
Example #23
0
#!/usr/bin/env python
import mesa_reader as mr
import matplotlib.pyplot as plt
import numpy as np
import sys

# set up some ploting stuff
fig = plt.figure(figsize=(12, 8))
plt.style.use('fast')
pallette = plt.get_cmap('magma')
pallette1 = plt.get_cmap('viridis')

# command line arguments
ddd = str(sys.argv[1])
hhh = str(sys.argv[2])
direc = mr.MesaLogDir(log_path=ddd, history_file=hhh)
profs = []
names = []
for i in range(3, len(sys.argv) - 1):
    profs.append(direc.profile_data(int(sys.argv[i])))
    names.append("model " + str(sys.argv[i]))

# last argument is name for plots
ttl = sys.argv[-1]

# temp
for i in range(len(profs)):
    # set label
    year = str(int(profs[i].star_age))
    mass = str(round(profs[i].star_mass, 2))
    model = str(profs[i].model_number)
def main():
  print("In main analysis")
  run_dir = "/home/vishal/UMassD/sem2/astro_phy/project/runs"
  os.chdir(run_dir)
  cmd = 'find shock_* -iname LOGS_part5'
  results = os.popen(cmd).read().split('\n')
  #print(results)
  count = 1
  masses = []
  Zs = []
  all_data = []
  fe_core_z1 = [] # z=0.0001
  fe_core_z2 = [] # z=0.001
  fe_core_z3 = [] # z=0.01
  fe_core_z4 = [] # z=0.1
  
  si_core_z1 = [] # z=0.0001
  si_core_z2 = [] # z=0.001
  si_core_z3 = [] # z=0.01
  si_core_z4 = [] # z=0.1

  initial_mass_z1 = []
  initial_mass_z2 = []
  initial_mass_z3 = []
  initial_mass_z4 = []

  final_rem_masses = []
  corrs_mass = []
  tot_ran = 0
  G = 6.67408e-11
  M_sol = 1.98e+30
  for paths in results:
    if paths == "":
      continue
    print(paths)
    count += 1
    #pdb.set_trace()
    model_name = paths.split('/')[1]
    mass = float(re.findall('M_[0-9.]+',model_name)[0].split('_')[-1])# this is a string
    masses.append(mass)
    print("mass:"+str(mass))
    z = float(re.findall('Z_[0-9.]+',model_name)[0].split('_')[-1])# this is a string
    print("z:"+str(z))
    Zs.append(z)
    # read the history.data file and extract the Fe, Si mass.
    
    #LOG_name = 'LOGS_finish/'
    #data_path = paths.split('/')[-3] + "/" + paths.split('/')[-2]
    # us the data_path
    #pdb.set_trace()
    try:
      l = mr.MesaLogDir(paths)
      pl = l.profile_data()
    except:
      print("Not able to read data from " + paths)
      continue
    M_in = pl.data('mass') * M_sol
    R_in = pl.data('radius_cm') * 10**-2
    vel_esc_sq = 2 * G * (M_in/R_in)

    vel_sq = (pl.data('vel_km_per_s') * 10**3)**2

    a = vel_sq[-200:-1] < vel_esc_sq[-200:-1]
    try:
      mass_indx = np.where(a==True)[0][0]
    except:
      print("issues")
      continue
    rem_mass = pl.data('mass')[-200:-1][mass_indx] # solar masses
    tot_ran += 1
    final_rem_masses.append(rem_mass)
    corrs_mass.append(mass)

    """
    #d = mr.MesaData(data_path + "/LOGS_finish/history.data")
    fe_core_mass = d.data('fe_core_mass')[-1]
    si_core_mass = d.data('si_core_mass')[-1]
    all_data.append((mass,z,fe_core_mass,si_core_mass))
    #pdb.set_trace()
    if (z == 0.0001):
      fe_core_z1.append(fe_core_mass)
      si_core_z1.append(si_core_mass)
      initial_mass_z1.append(mass)
    elif (z==0.001):
      fe_core_z2.append(fe_core_mass)
      si_core_z2.append(si_core_mass)
      initial_mass_z2.append(mass)
    elif (z == 0.01):
      fe_core_z3.append(fe_core_mass)
      si_core_z3.append(si_core_mass)
      initial_mass_z3.append(mass)
    elif (z==0.1):
      fe_core_z4.append(fe_core_mass)
      si_core_z4.append(si_core_mass)
      initial_mass_z4.append(mass)
    """
  pdb.set_trace()

########################################################################
# Plot for Fe core and Si shell mass after the ms_to_ccsn models
  pdb.set_trace()
  # Plot the results:
  plt.figure(1)
  plt.subplot(2,2,1)
  plt.scatter(initial_mass_z1,fe_core_z1,marker='^')
  plt.scatter(initial_mass_z1,si_core_z1,marker='s')
  #plt.scatter(initial_mass_z1,np.log10(fe_core_z1))
  plt.title('z=0.0001')
  #plt.xlabel('Initial Progenitor($M_\odot\$)')
  plt.ylabel('Core Mass($M_{\odot}$)')

  plt.subplot(2,2,2)
  plt.scatter(initial_mass_z2,fe_core_z2,marker='^')
  plt.scatter(initial_mass_z2,si_core_z2,marker='s')
  #plt.scatter(initial_mass_z2,np.log10(fe_core_z2))
  plt.title('z=0.001')
  #plt.xlabel('Initial Progenitor($M_\odot\$)')
  #plt.ylabel('Fe Core($M_\odot\$)')

  plt.subplot(2,2,3)
  plt.scatter(initial_mass_z3,fe_core_z3,marker='^')
  plt.scatter(initial_mass_z3,si_core_z3,marker='s')
  #plt.scatter(initial_mass_z3,np.log10(fe_core_z3))
  plt.title('z=0.01')
  plt.xlabel('Main Sequence Mass($M_{\odot}$)')
  plt.ylabel('Core Mass($M_{\odot}$)')

  plt.subplot(2,2,4)
  plt.scatter(initial_mass_z4,fe_core_z4,marker='^')
  plt.scatter(initial_mass_z4,si_core_z4,marker='s')
  #plt.scatter(initial_mass_z4,np.log10(fe_core_z4))
  plt.title('z=0.1')
  plt.xlabel('Main Sequence Mass($M_{\odot}$)')
  #plt.ylabel('Fe Core($M_\odot\$)')

  plt.figlegend(['Fe Core' ,'Si Shell'])
  plt.savefig('Fe_core_vs_initial_mass_log10.png')

  plt.show()
########################################################################
# All the Fe core vs Initial mass model:
  pdb.set_trace()
  all_fe_core = fe_core_z1 + fe_core_z2 + fe_core_z3 + fe_core_z4
  all_si_core = si_core_z1 + si_core_z2 + si_core_z3 + si_core_z4
  all_initial_mass = initial_mass_z1 + initial_mass_z2 + initial_mass_z3 + initial_mass_z4
  plt.figure(2)
  plt.scatter(initial_mass_z1,fe_core_z1,marker='^',color="gray",alpha=0.25)
  plt.scatter(initial_mass_z2,fe_core_z2,marker='^',color="gray",alpha=0.5)
  plt.scatter(initial_mass_z3,fe_core_z3,marker='^',color="gray",alpha=0.75)
  plt.scatter(initial_mass_z4,fe_core_z4,marker='^',color="gray",alpha=1.0)
  plt.legend(["0.0001","0.001","0.01","0.1"], title="Metallicity")
  plt.xlabel('Main Sequence Mass($M_{\odot}$)')
  plt.ylabel('Core Mass($M_{\odot}$)')
  plt.show()
###########################################################################
# Pickle the data up:
  pdb.set_trace()
  all_data = [all_fe_core , all_si_core]
  pickle.dump(all_data,open('pickle_data.p','w'))
Example #25
0
def species(runf,
            prof_number=1,
            byM=False,
            rmax=0.0,
            rmin=0.0,
            core=False,
            species=_ap13,
            thresh=-6,
            tstamp=True,
            show=False):
    """Plots species found in a specified profile or a file.
    
    Args:
        runf (str): run folder to look in or file to use.
        prof_number (int): profile to plot(skipped if runf is a file).
        byM (bool): plot by mass (True) or by radius (False).
        rmin/max (float): radius limits in Rsun/Msun (depending on byM).
        core (bool): show c_core_mass in plot.
        species (list): list of named species to plot.
        thresh (float): sets lower limit of the plot.
        tstamp (bool): write sim time on plot.
        show (bool): if True, returns the mpl.figure object. 
        
    Returns:
        mpl.figure: plot of abundances.

    """
    if os.path.isdir(runf):
        folder = True
        l = mr.MesaLogDir(os.path.join(runf, "LOGS"))
        profs = l.profile_numbers
        if prof_number > len(profs):
            print("Profile not found. ({}/{})".format(prof_number, len(profs)))
        else:
            print("Plotting Abundances. {}/{}.".format(prof_number,
                                                       len(profs)))
        p = l.profile_data(profile_number=prof_number)
        if byM and not rmax:
            rmax = p.initial_mass
        elif not byM and not rmax:
            rmax = l.profile_data(profile_number=1).photosphere_r
    else:
        folder = False
        p = mr.MesaData(runf)
        if byM and not rmax:
            rmax = p.initial_mass
        elif not byM and not rmax:
            rmax = p.photosphere_r

    fig = plt.figure(figsize=(11, 7))
    layout = (1, 1)
    ax1 = plt.subplot2grid(layout, (0, 0),
                           aspect='auto',
                           adjustable='box-forced')
    plotAbundances(p,
                   ax1,
                   species=species,
                   byM=byM,
                   core=core,
                   tstamp=tstamp,
                   rmax=rmax,
                   rmin=rmin,
                   xtitle=True,
                   thresh=thresh)
    lgd = ax1.legend(ncol=6,
                     loc='upper left',
                     bbox_to_anchor=(1.0, 1.02),
                     columnspacing=0.3,
                     labelspacing=0.1,
                     markerfirst=False,
                     numpoints=3)
    plt.tight_layout(pad=1.0, h_pad=0.0, w_pad=0.5, rect=(0, 0, 0.5, 1))
    tag = 'abun'
    if folder:
        # build filetree and show or save the figure
        if not os.path.exists("{}/png/".format(runf)):
            os.mkdir("{}/png/".format(runf, tag))
            os.mkdir("{}/png/{}".format(runf, tag))
        elif not os.path.exists("{}/png/{}/".format(runf, tag)):
            os.mkdir("{}/png/{}".format(runf, tag))
        if show:
            return fig
        else:
            plt.savefig("{0}/png/{1}/{1}_{2:05}".format(
                runf, tag, p.model_number))
            plt.close(fig)
        print("Wrote: {0}/png/{1}/{1}_{2:05}".format(runf, tag,
                                                     p.model_number))
    else:
        # don't save, just return the profile to the notebook
        return fig
        if file.startswith('profile') and file.endswith('.data'):
            profiledirs = os.path.join(root, file)
            profileroots = os.path.join(root)

            constraint_noprems = 500

            pnum = re.search('profile(.+?).data', profiledirs)

            if pnum:
                pnums = pnum.group(1)
            if int(pnums) >= int(constraint_noprems):
                #print(pnums)

                profiles_indir = mr.MesaLogDir(
                    '/home/janne/Gunter_project/44_tau/example_10_masses/LOGS-1.50-0.02-0.7-0.4'
                )
                pr = profiles_indir.profile_data(profile_number=pnums)
                pr_modelnos = pr.model_number

                teff = pr.Teff
                #logteff = np.log(teff)
                r = pr.photosphere_r
                m = pr.initial_mass
                g = m / r**2
                #logg = np.log(g)

                profile_numbers.append(pnums)
                loggs.append(g)
                logteffs.append(teff)
                alle = [g, teff, pnums]
Example #27
0
def main():
    print("In main analysis")
    run_dir = "/home/vishal/UMassD/sem2/astro_phy/project/runs"
    os.chdir(run_dir)
    cmd = 'find set_* -iname final.mod'
    results = os.popen(cmd).read().split('\n')

    cmd2 = 'find shock_* -iname LOGS_part5'
    results2 = os.popen(cmd2).read().split('\n')

    #print(results)
    count = 1
    masses = []
    Zs = []
    all_data = []
    fe_core_z1 = []  # z=0.0001
    fe_core_z2 = []  # z=0.001
    fe_core_z3 = []  # z=0.01
    fe_core_z4 = []  # z=0.1

    si_core_z1 = []  # z=0.0001
    si_core_z2 = []  # z=0.001
    si_core_z3 = []  # z=0.01
    si_core_z4 = []  # z=0.1

    initial_mass_z1 = []
    initial_mass_z2 = []
    initial_mass_z3 = []
    initial_mass_z4 = []

    final_rem_masses_z1 = []
    final_rem_masses_z2 = []
    final_rem_masses_z3 = []
    final_rem_masses_z4 = []

    corrs_mass_z1 = []
    corrs_mass_z2 = []
    corrs_mass_z3 = []
    corrs_mass_z4 = []
    tot_ran = 0
    G = 6.67408e-11
    M_sol = 1.98e+30

    for paths in results:
        if paths == "":
            continue
        print(paths)
        count += 1
        model_name = paths.split('/')[-2]
        mass = float(re.findall(
            'M_[0-9.]+', model_name)[0].split('_')[-1])  # this is a string
        masses.append(mass)
        print("mass:" + str(mass))
        z = float(re.findall('Z_[0-9.]+',
                             model_name)[0].split('_')[-1])  # this is a string
        print("z:" + str(z))
        Zs.append(z)
        # read the history.data file and extract the Fe, Si mass.
        LOG_name = 'LOGS_finish/'
        data_path = paths.split('/')[-3] + "/" + paths.split('/')[-2]
        #pdb.set_trace()
        d = mr.MesaData(data_path + "/LOGS_finish/history.data")
        fe_core_mass = d.data('fe_core_mass')[-1]
        si_core_mass = d.data('si_core_mass')[-1]
        all_data.append((mass, z, fe_core_mass, si_core_mass))
        #pdb.set_trace()
        if (z == 0.0001):
            fe_core_z1.append(fe_core_mass)
            si_core_z1.append(si_core_mass)
            initial_mass_z1.append(mass)
        elif (z == 0.001):
            fe_core_z2.append(fe_core_mass)
            si_core_z2.append(si_core_mass)
            initial_mass_z2.append(mass)
        elif (z == 0.01):
            fe_core_z3.append(fe_core_mass)
            si_core_z3.append(si_core_mass)
            initial_mass_z3.append(mass)
        elif (z == 0.1):
            fe_core_z4.append(fe_core_mass)
            si_core_z4.append(si_core_mass)
            initial_mass_z4.append(mass)

    for paths in results2:
        if paths == "":
            continue
        print(paths)
        count += 1
        model_name = paths.split('/')[1]
        mass = float(re.findall(
            'M_[0-9.]+', model_name)[0].split('_')[-1])  # this is a string
        print("mass:" + str(mass))
        z = float(re.findall('Z_[0-9.]+',
                             model_name)[0].split('_')[-1])  # this is a string
        print("z:" + str(z))

        try:
            l = mr.MesaLogDir(paths)
            pl = l.profile_data()
        except:
            print("Not able to read data from " + paths)
            continue
        M_in = pl.data('mass') * M_sol
        R_in = pl.data('radius_cm') * 10**-2
        vel_esc_sq = 2 * G * (M_in / R_in)
        vel_sq = (pl.data('vel_km_per_s') * 10**3)**2
        a = vel_sq[-200:-1] < vel_esc_sq[-200:-1]
        try:
            mass_indx = np.where(a == True)[0][0]
        except:
            print("issues")
            continue
        rem_mass = pl.data('mass')[-200:-1][mass_indx]  # solar masses
        tot_ran += 1
        if (z == 0.0001):
            final_rem_masses_z1.append(rem_mass)
            corrs_mass_z1.append(mass)
        elif (z == 0.001):
            final_rem_masses_z2.append(rem_mass)
            corrs_mass_z2.append(mass)
        elif (z == 0.01):
            final_rem_masses_z3.append(rem_mass)
            corrs_mass_z3.append(mass)
        elif (z == 0.1):
            final_rem_masses_z4.append(rem_mass)
            corrs_mass_z4.append(mass)

    #pdb.set_trace()
    for indx, m in enumerate(initial_mass_z1):
        if m in corrs_mass_z1:
            plt.scatter(m,
                        fe_core_z1[indx],
                        marker='^',
                        color='blue',
                        alpha=0.25)
            plt.scatter(m,
                        si_core_z1[indx],
                        marker='s',
                        color='orange',
                        alpha=0.25)
    for indx, m in enumerate(initial_mass_z2):
        if m in corrs_mass_z2:
            plt.scatter(m,
                        fe_core_z2[indx],
                        marker='^',
                        color='blue',
                        alpha=0.5)
            plt.scatter(m,
                        si_core_z2[indx],
                        marker='s',
                        color='orange',
                        alpha=0.5)

    for indx, m in enumerate(initial_mass_z3):
        if m in corrs_mass_z3:
            plt.scatter(m,
                        fe_core_z3[indx],
                        marker='^',
                        color='blue',
                        alpha=0.75)
            plt.scatter(m,
                        si_core_z3[indx],
                        marker='s',
                        color='orange',
                        alpha=0.75)
    for indx, m in enumerate(initial_mass_z4):
        if m in corrs_mass_z4:
            plt.scatter(m,
                        fe_core_z4[indx],
                        marker='^',
                        color='blue',
                        alpha=1.0)
            plt.scatter(m,
                        si_core_z4[indx],
                        marker='s',
                        color='orange',
                        alpha=1.0)

    #plt.legend(['Si Shell'])
    #plt.scatter(corrs_mass_z1,final_rem_masses_z1,color='red',alpha=0.25)
    plt.scatter(corrs_mass_z2, final_rem_masses_z2, color='red', alpha=0.5)
    plt.scatter(corrs_mass_z3, final_rem_masses_z3, color='red', alpha=0.75)
    pdb.set_trace()
    plt.legend(['Fe Core', 'Si Shell'])
    #plt.scatter(corrs_mass_z4,final_rem_masses_z4,color='red',alpha=1.0)
    #plt.legend(['Z=0.001','Z=0.01'])
    #plt.legend(['Bound mass'])

    plt.xlabel('Main Sequence Mass($M_{\odot}$)')
    plt.ylabel('Core Mass($M_{\odot}$)')
    plt.show()
Example #28
0
def mod_abun(path,
             h12=None,
             h23=None,
             name='abun.dat',
             output=None,
             profile_number=None,
             iso1=None,
             iso2='he4',
             iso3='h1'):
    '''
    Function to modify abundance profile of one star
    
    Parameters:
    -----------
    path            : str
                    LOGS folder
    h12            : float
                    mass of iso1 to exchange by iso2 (usually mass of c12 to
                    exhange by he4)
    h23            : float
                    h12 = mass of iso2 to exchange by iso3 (usually mass of
                    he4 to exhange by h1)
    name           : str
                    name of output file
    ouput          : str
                    output directory. If None, output to current folder
    profile_number : int
                    profile number to extract information. If None, program
                    will search for last profile
    iso1           : str
                    first isotope to exchange mass. Usually c12, default is
                    None -> in this case exchange only he4 by h1
    iso2           : str
                    second isotope to exchange mass. Usually he4, default is
                    he4
    iso3           : str
                    last isotope to exchange mass. Usually h1, default is h1
    '''

    out = out_dir(output)
    path = ms.MesaLogDir(path)
    hist = path.history
    star_m = hist.data('star_mass')

    if profile_number is None:
        profiles = path.model_numbers
        model = profiles[-1]
        model_index = -1
    else:
        model = profile_number
        model_index = profile_number - 1

    prof = path.profile_data(model)

    headers = [
        'q', 'dm', 'xq', 'h1', 'he3', 'he4', 'c12', 'c13', 'n13', 'n14', 'n15',
        'o16', 'o17', 'o18', 'f19', 'ne20', 'ne22', 'mg24', 'si28'
    ]

    data = np.array([
        prof.data('q'),
        prof.data('dm'), 1 - prof.data('q'),
        prof.data('h1'),
        prof.data('he3'),
        prof.data('he4'),
        prof.data('c12'),
        prof.data('c13'),
        prof.data('n13'),
        prof.data('n14'),
        prof.data('n15'),
        prof.data('o16'),
        prof.data('o17'),
        prof.data('o18'),
        prof.data('f19'),
        prof.data('ne20'),
        prof.data('ne22'),
        prof.data('mg24'),
        prof.data('si28')
    ])

    df = pd.DataFrame(data.T, columns=headers)

    if iso1 is None:
        print('Substituindo {} por {}'.format(str(iso2), str(iso3)))
        m23 = h23 * star_m[model_index]
        new_abun = exchange_isotopes(iso2, iso3, m23, df)
        # print('massa estrela = {}, valor que multiplicou a massa = {}'.format
        # (star_m[model_index], h23))
        print('Substituido {} de {} por {}'.format(
            np.sum(new_abun[str(iso3)] * df['dm'] * 5.027652086e-34),
            str(iso2), str(iso3)))
    else:
        print('Substituindo {} por {}'.format(str(iso1), str(iso2)))
        print('E tambem substituindo {} por {}'.format(str(iso2), str(iso3)))
        m12 = h12 * star_m[model_index]
        abun12 = exchange_isotopes(iso1, iso2, m12, df)
        m23 = h23 * star_m[model_index]
        new_abun = exchange_isotopes(iso2, iso3, m23, abun12)
        print('Substituido {} de {} por {}'.format(
            np.sum(new_abun[str(iso2)] * df['dm'] * 5.027652086e-34),
            str(iso1), str(iso2)))
        print('Substituido {} de {} por {}'.format(
            np.sum(new_abun[str(iso3)] * df['dm'] * 5.027652086e-34),
            str(iso2), str(iso3)))

    data_clean = new_abun.drop(['q', 'dm'], axis=1)
    # Dados de colunas e linhas para o header do arquivo
    h1 = data_clean.shape[0]
    h2 = data_clean.shape[1] - 1
    header = str(h1) + ', ' + str(h2)

    # Salvando os dados
    np.savetxt(os.path.join(out, str(name)),
               data_clean,
               fmt='%1.15f',
               header=header,
               comments='')
Example #29
0
def abun_plot(folder,
              mod_n=None,
              x_lim=12,
              title=' ',
              save=False,
              name=None,
              isotope=None,
              x_axis='atm'):
    '''
    Plot the abundance profile at model number using log(1-q) on x-axis
    (better to see information on atmosfere)

    Parameter
    ---------
    folder  : str
            path to LOGS folder -> '/path/to/LOGS/'
    mod_n   : int
            model number to calculate the profiles. If None, the last model
            will be used
    x_lim   : int
            limit to x-axis on profile plot. Default = 12
    title   : str
            title to use on the plot -> 'title'
    save    : bool
            if True, save a .png file of the plot
    name    : str
            name of the .png file if the parameter save is True
    x_axis  : str
            can be 'atm' or 'nuc'. If 'atm' is chosen, x-axis will be -log(1-q)
            (better for atmosfere region). If 'nuc', x-axis will be q (better
            for nucleus region). Default is 'atm'
    isotope: Not implemented yet

    Returns
    -------
    show the plot or save a .png file
    '''
    # Talvez implementar um parametro para escolher quais isotopos
    # serao plotados
    # if isotope == 'CO':
    #     isos = ['h1', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']
    # elif isotope == 'ONe':
    #     isos = ['h1', 'he3','he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']

    path = ms.MesaLogDir(folder)
    hist = path.history
    # models = hist.data('model_number')
    mass = hist.data('star_mass')
    mi = hist.initial_mass
    teff = hist.data('log_Teff')

    if mod_n is None:
        profiles = path.model_numbers
        model = profiles[-1]
        m_ind = -1
    else:
        model = mod_n
        m_ind = -1  # mod_n

    prof = path.profile_data(model)
    # isos = ['h1', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']
    # for i in isos:
    if x_axis == 'atm':
        x = -prof.data('logxq')
        xlabel = r'$\log (1 - q)$'
    else:
        x = prof.data('q')
        x_lim = 1
        xlabel = r'$\frac{m}{M}$'

    h1 = prof.data('h1')
    #he3 = prof.data('he3')
    he4 = prof.data('he4')
    c12 = prof.data('c12')
    #c13 = prof.data('c13')
    #n13 = prof.data('n13')
    n14 = prof.data('n14')
    #n15 = prof.data('n15')
    o16 = prof.data('o16')
    #o18 = prof.data('o18')
    ne20 = prof.data('ne20')
    #ne22 = prof.data('ne22')
    mg24 = prof.data('mg24')

    plt.figure(figsize=(14, 7))
    # plt.plot(x, he3, color='c', lw=1.5, label=r'$He3$')
    plt.plot(x, he4, color='darkolivegreen', lw=1.5, label=r'$He4$')
    plt.plot(x, c12, color='k', lw=1.5, label=r'$C12$')
    # plt.plot(x, c13, color='grey', lw=1.5, label=r'$C13$')
    # plt.plot(x, n13, color='darkred', lw=1.5, label=r'$N13$')
    plt.plot(x, n14, color='r', lw=1.5, label=r'$N14$')
    # plt.plot(x, n15, color='salmon', lw=1.5, label=r'$N15$')
    plt.plot(x, o16, color='g', lw=1.5, label=r'$O16$')
    # plt.plot(x, o18, color='limegreen', lw=1.5, label=r'$O18$')
    plt.plot(x, ne20, color='y', lw=1.5, label=r'$Ne20$')
    # plt.plot(x, ne22, color='orange', lw=1.5, label=r'$Ne22$')
    # plt.plot(x, mg24, color='m', lw=1.5, label=r'$Mg24$')
    plt.plot(x, h1, color='b', lw=1.5, label=r'$H1$')

    plt.xlim(0, x_lim)
    plt.xlabel(xlabel)
    plt.ylabel('mass fraction')
    plt.suptitle(title)
    plt.title('Abundance at model ' + str(model) + r' $M_i = $ ' + str(mi) +
              r' $M_f = $ ' + str(mass[m_ind]) + r' $Teff = $ ' +
              str(10**teff[m_ind]))

    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)

    if save is True:
        plt.savefig(name + '.pdf')
        plt.savefig(name + '.png')
        return 'File save with name ' + name
    else:
        plt.show()
Example #30
0
def massconstrain(fname):

    Log_Teff_obs = 3.839
    Log_g_obs = 3.6

    Log_Teff_obs_unc = 0.007
    #Log_L_obs_unc = 0.0065
    Log_g_obs_unc = 0.1

    n = 3

    Log_Teff_ns = n * Log_Teff_obs_unc
    #Log_L_ns = n*Log_L_obs_unc
    Log_g_ns = n * Log_g_obs_unc

    Log_Teff_lower = Log_Teff_obs - Log_Teff_ns
    Log_Teff_upper = Log_Teff_obs + Log_Teff_ns
    #Log_L_lower = Log_L_obs - Log_L_ns
    #Log_L_upper = Log_L_obs + Log_L_ns
    Log_g_upper = Log_g_obs + Log_g_ns
    Log_g_lower = Log_g_obs - Log_g_ns

    radial_funda = 6.8980
    radial_first = 8.9606

    loggs = []
    logteffs = []
    profile_numbers = []
    alle_final = []
    #best_gs_radial = []
    #best_teffs_radial = []
    #best_gs_first = []
    #best_teffs_first = []

    for root, dirs, files in sorted(os.walk(fname)):
        files.sort(key=lambda x: '{0:0>20}'.format(x))
        for file in files:

            if file.startswith('profile') and file.endswith('.data'):
                profiledirs = os.path.join(root, file)
                profileroots = os.path.join(root)

                constraint_noprems = 450

                pnum = re.search('profile(.+?).data', profiledirs)

                if pnum:
                    pnums = pnum.group(1)
                if int(pnums) >= int(constraint_noprems):
                    #print(pnums)

                    profiles_indir = mr.MesaLogDir(fname)
                    pr = profiles_indir.profile_data(profile_number=pnums)
                    pr_modelnos = pr.model_number

                    teff = pr.Teff
                    #logteff = np.log(teff)r = pr.photosphere_r
                    r = pr.photosphere_r
                    m = pr.initial_mass
                    m_solar = 1.9892 * 10**(33)
                    r_solar = 6.9598 * 10**(10)
                    R = r * r_solar
                    M = m * m_solar
                    G = 6.67428 * 10**(-8)
                    #logg = np.log(g)
                    g = G * M / R**2

                    profile_numbers.append(pnums)
                    loggs.append(g)
                    logteffs.append(teff)
                    alle = [g, teff, pnums]
                    alle_final.append(alle)

    plt.plot(np.log10(logteffs), np.log10(loggs), label='mass = %f' % m)

    plt.plot([
        Log_Teff_lower, Log_Teff_upper, Log_Teff_upper, Log_Teff_lower,
        Log_Teff_lower
    ], [Log_g_lower, Log_g_lower, Log_g_upper, Log_g_upper, Log_g_lower],
             'r-.',
             alpha=0.5,
             linewidth=3)
    plt.plot(Log_Teff_obs, Log_g_obs, 'r*')

    #ax.set_xlim([3.7,4.05])
    #ax.set_ylim([3.2,4.2])

    alle = []
    differences_radial = []
    differences_first = []
    minValueRadial = None
    minValueFirst = None
    diffsndirs_radial = []
    diffsndirs_first = []

    for root, dirs, files in sorted(os.walk(fname)):
        files.sort(key=lambda x: '{0:0>20}'.format(x))
        for file in files:

            if file.endswith('freqs.dat'):

                gyredirs = os.path.join(root, file)
                gyreroots = os.path.join(root)
                gnum = re.search('profile(.+?)-freqs.dat', gyredirs)

                if gnum:
                    gnums = gnum.group(1)
                if int(gnums) >= int(constraint_noprems):
                    #print(gnums)
                    freqs = gyr.readmesa(gyredirs)

                    if freqs[0][1] == 1 and freqs[1][1] == 2:
                        difference_funda = np.abs(freqs[0][4] - radial_funda)
                        difference_first = np.abs(freqs[1][4] - radial_first)
                        #differences.append()

                        currentValueRadial = difference_funda

                        if minValueRadial == None:
                            minValueRadial = currentValueRadial
                        else:
                            minValueRadial = min(minValueRadial,
                                                 currentValueRadial)

                        currentValueFirst = difference_first

                        if minValueFirst == None:
                            minValueFirst = currentValueFirst
                        else:
                            minValueFirst = min(minValueFirst,
                                                currentValueFirst)

                        differences_radial.append(difference_funda)
                        differences_first.append(difference_first)
                        temp_radial = [gyredirs, difference_funda]
                        temp_first = [gyredirs, difference_first]
                        diffsndirs_radial.append(temp_radial)
                        diffsndirs_first.append(temp_first)

    minimum_radial = differences_radial.index(minValueRadial)
    minimum_profile_radial = diffsndirs_radial[minimum_radial]
    minimum_first = differences_first.index(minValueFirst)
    minimum_profile_first = diffsndirs_first[minimum_first]

    best_g_radial = alle_final[minimum_radial][0]
    best_teff_radial = alle_final[minimum_radial][1]
    best_g_first = alle_final[minimum_first][0]
    best_teff_first = alle_final[minimum_first][1]

    allbest_radial = [
        best_g_radial, best_teff_radial, minimum_profile_radial[0]
    ]
    allbest_first = [best_g_first, best_teff_first, minimum_profile_first[0]]

    plt.plot(np.log10(best_teff_radial),
             np.log10(best_g_radial),
             'k.',
             MarkerSize=15)
    plt.plot(np.log10(best_teff_first),
             np.log10(best_g_first),
             'g.',
             MarkerSize=8)

    allbest = [allbest_radial, allbest_first]
    xlabel(r'$\logT_{eff}$')
    ylabel(r'$\log(g)$')
    legend()

    plt.rcParams.update({'font.size': 15})
    #plt.axis((3.8,3.9,3.3,4.0))
    plt.gca().invert_xaxis()
    plt.gca().invert_yaxis()

    return allbest