Esempio n. 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)
Esempio n. 2
0
def plot(x):
	h = mr.MesaData(x)
	plt.plot(h.log_Teff, h.log_L)
	plt.gca().invert_xaxis()
	plt.xlabel('log Effective Temp')
	plt.ylabel('log Luminosity')
	plt.show()
Esempio n. 3
0
    def load_all_history(self):
        self.h = {}
        for k, PATH in self.path_dict.items():
            self.h[k] = mr.MesaData(path.join(PATH, 'history.data'))

        self._h_keys = np.array([k for k in self.h.keys()])
        self._h_M = np.array([float(k) for k in self._h_keys])

        idx = self._h_M.argsort()
        self._h_keys = self._h_keys[idx]
        self._h_M = self._h_M[idx]
Esempio n. 4
0
    def evaluate_initial_grid(self):
        """Reads history files in a directory tree and creates a grid of parameters.
        Saves the grid to a file and creates a directory with .mod files.

        Parameters
        ----------

        Returns
        ----------
        """

        if not os.path.exists(self.output_dir):
            os.mkdir(self.output_dir)
            print(f"Output directory created: {self.output_dir}")
        else:
            print(f"Output directory '{self.output_dir}' already exists.")

        i = 0
        for log_dir in sorted(self.log_dirs):
            print(log_dir)
            initial_parameters = self.read_progenitor_name(
                os.path.basename(log_dir))
            data = mesa.MesaData(os.path.join(log_dir, "history.data"))
            if data.center_h1[-1] < 1e-4:
                rgb_tip = self.find_rgb_tip(data)  # model number, not index!
                default_model = rgb_tip // 10 * 10 + 10

                for n in range(-self.number_of_minus_models,
                               self.number_of_plus_models + 1):
                    model_number = default_model + 10 * n
                    model_name = f"model_{model_number:05d}.mod"
                    if os.path.isfile(os.path.join(log_dir, model_name)):
                        self.add_one_row(i, model_number, n,
                                         initial_parameters, data)
                        shutil.copyfile(
                            os.path.join(log_dir, model_name),
                            os.path.join(
                                self.output_dir,
                                self.create_mod_name(os.path.basename(log_dir),
                                                     n, model_number)))
                        i += 1
                    else:
                        print(f"{model_name} does not exist!")
            else:
                try:
                    shutil.rmtree(log_dir)
                    print(f"Deleted: {log_dir}")
                except OSError as e:
                    print(f"Error: {log_dir} : {e.strerror}")
            print('')

            self.save_grid_to_file(self.output_file)
Esempio n. 5
0
def graphing():
    if os.getcwd() != answer1:
        os.chdir('..')
    gname = var2.get()
    if gname == "RR":
        h = mr.MesaData('mesa/star/test_suite/rsp_RR_Lyrae/LOGS/history.data')
    elif gname == "C":
        h = mr.MesaData('mesa/star/test_suite/rsp_Cepheid/LOGS/history.data')
    else:
        ProgressBar2.delete(1.0, END)
        ProgressBar2.insert(END, "Choose which star to graph")
    r1 = h.data(comboBox1.get())
    r2 = h.data(comboBox2.get())
    ProgressBar2.delete(1.0, END)
    ProgressBar2.insert(END, "Processing...")
    pl.plot(r1, r2)
    pl.xlabel(comboBox1.get())
    pl.ylabel(comboBox2.get())
    pl.gca().invert_xaxis()
    pl.show()
    ProgressBar2.delete(1.0, END)
    ProgressBar2.insert("Successful Graph")
Esempio n. 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
Esempio n. 7
0
def getClosestModel(modelNumber, workingDirectory):
    """Returns the MESA profile with the closest model number in a specified directory.
    
    Keyword arguments:
    modelNumber -- target/desired model number
    workingDirectory -- target directory
    """
    print('Looking for the profile closest to model #' + str(modelNumber) +
          ' in ' + str(workingDirectory))
    filenames = []

    for root, dirs, files in os.walk(workingDirectory):
        for file in files:
            if file.endswith("profiles.index"):
                filenames.append(os.path.join(root, file))

    profiles = []
    # import files
    for file in filenames:
        i = mr.MesaProfileIndex(file)
        profiles.append(i)

    # find the closest model number - ugly but functional
    closest = 0
    diff = 1e10
    profilePath = ''
    j = 0
    for index in profiles:
        values = index.model_numbers
        profileNums = index.profile_numbers
        k = 0
        for i in values:
            if (abs(modelNumber - i) < diff):
                diff = abs(modelNumber - i)
                closest = i
                og = filenames[j]
                og = og[:-14]  # put together the file name given the directory
                profilePath = og + 'profile' + str(profileNums[k]) + '.data'
            k += 1
        j += 1

    print('Actual model number: ' + str(closest))
    print('Difference between target and actual model: ' + str(diff))
    print('File path: ' + str(profilePath))
    print('')

    # import target profile
    p = mr.MesaData(profilePath)
    return p
Esempio n. 8
0
    def read_history(self,
                     log_dir: str,
                     top_dir: str,
                     dest_dir: Path = Path('.'),
                     delete_file: bool = True,
                     rename: bool = False,
                     keep_tree: bool = False) -> mesa.MesaData:
        """Reads a MESA history file and returns a MesaData object.

        Parameters
        ----------
        log_dir : str
            Log directory.
        top_dir : str
            Top directory.
        dest_dir : Path, optional
            Temporary directory for the required track. Default: Path('.').
        delete_file : bool, optional
            If True delete the extracted track. The track is not deleted if
            'keep_tree' is True. Default: True.
        rename : bool, optional
            If True it renames the history file to include information about
            the model contained in log_dir.
        keep_tree : bool, optional
            If True extract file with its directory structure (default
            ZipFile.extract() behaviour), otherwise extract file directly to
            'dest_dir'. Default: False.

        Returns
        ----------
        MesaData
            Evolutionary track (MESA history file) as MesaData object.
        """

        if rename:
            history_name = f'history{log_dir[4:]}.data'
        else:
            history_name = 'history.data'
        if keep_tree:
            file_name = dest_dir.joinpath(top_dir, log_dir, history_name)
        else:
            file_name = dest_dir.joinpath(history_name)
        if not self.model_extracted(file_name):
            self.extract_history(log_dir, top_dir, dest_dir, rename, keep_tree)
        data = mesa.MesaData(str(file_name))
        if delete_file and not keep_tree:
            file_name.unlink()
        return data
Esempio n. 9
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))
Esempio n. 10
0
    def read_evol_model(self,
                        log_dir: str,
                        top_dir: str,
                        he4: float,
                        dest_dir: Path = Path('.'),
                        delete_file: bool = True,
                        keep_tree: bool = False) -> mesa.MesaData:
        """Reads a single evolutionary model (a profile) and returns a MesaData
        object.

        Parameters
        ----------
        log_dir : str
            Log directory.
        top_dir : str
            Top directory.
        he4 : float
            Central helium abundance of the required model.
        dest_dir : Path, optional
            Directory for the required model. Default: Path('.').
        delete_file : bool, optional
            If True delete the extracted model. The model is not deleted if
            'keep_tree' is True. Default: True.
        keep_tree : bool, optional
            If True extract file with its directory structure (default
            ZipFile.extract() behaviour), otherwise extract file directly to
            'dest_dir'. Default: False.

        Returns
        ----------
        MesaData
            Evolutionary model (MESA profile file) as MesaData object.
        """

        if keep_tree:
            file_name = dest_dir.joinpath(top_dir, log_dir,
                                          self.evol_model_name(he4))
        else:
            file_name = dest_dir.joinpath(self.evol_model_name(he4))
        if not self.model_extracted(file_name):
            self.extract_evol_model(log_dir, top_dir, he4, dest_dir, keep_tree)
        data = mesa.MesaData(str(file_name))
        if delete_file and not keep_tree:
            file_name.unlink()
        return data
Esempio n. 11
0
def getMesa(profileFile):
    data = mr.MesaData(profileFile)

    logT = data.logT
    mass = data.mass
    logR = data.logR
    logRho = data.logRho
    logP = data.logP

    mass = mass * Msun
    T = np.power(10., logT)
    P = np.power(10., logP) / G
    radius = np.power(10., logR)
    rSun = 7e10
    radius = radius * rSun
    rho = np.power(10., logRho)

    return T, mass, radius, rho, P
Esempio n. 12
0
def evolution(param1, param2, filename):

    star = ms.MesaData(filename)

    plot1 = star.data(param1)
    if param2 == 'rhobar':
        mass = star.data('star_mass')
        mass = mass * 1.989e33
        r = star.data('radius_cm')
        plot2 = 3 * mass / (4 * np.pi * r**3)
    else:
        plot2 = star.data(param2)
    if param1 == 'star_mass':
        plot1 = plot1 * 1.989e33
    if param2 == 'star_mass':
        plot2 = plot2 * 1.989e33

    plt.plot(plot1, plot2)
    plt.xlabel(param1)
    plt.ylabel(param2)
Esempio n. 13
0
def getMesaEnt2(profileFile):
    data = mr.MesaData(profileFile)

    logT = data.logT
    mass = data.mass
    mass = mass * Msun
    logP = data.logP
    logR = data.logR
    logRho = data.logRho

    P = np.power(10., logP) / G
    rho = np.power(10., logRho)

    # dm = np.zeros(len(mass))
    # for i in range(0,len(mass)-1) :
    # 	dm[i] = mass[i] - mass[i+1]
    # dm[len(mass)-1] = mass[len(mass)-1]

    ent = np.divide(P, np.power(rho, gamma))

    return ent
Esempio n. 14
0
def getMesaEnt(profileFile):
    data = mr.MesaData(profileFile)

    logT = data.logT
    mass = data.mass
    mass = mass * Msun
    logP = data.logP
    logR = data.logR

    T = np.power(10., logT)
    P = np.power(10., logP) / G

    dm = np.zeros(len(mass))
    for i in range(0, len(mass) - 1):
        dm[i] = mass[i] - mass[i + 1]
    dm[len(mass) - 1] = mass[len(mass) - 1]

    ent = R * (5. / 2. + np.log(
        np.power(k * T, 2.5) / P / h / h / h *
        np.power(2. * math.pi * mpart, 1.5)))

    return ent, dm
Esempio n. 15
0
def make_HR(direc, numTracks):

    for i in range(1, numTracks + 1):
        #profilefile = direc + "/i"+str(i).zfill(3)+"_profiles.index"
        #        profilefile = direc + "profiles.index"
        #        prof_info = np.loadtxt(profilefile,skiprows=1)
        #        print "how many lines?", prof_info.size, profilefile
        #        if prof_info.size < 4:
        #            continue
        #        modnum = prof_info[:,0]
        #        profnum = prof_info[:,2]
        #        firstpoint = np.int(modnum[profnum==2][0])-1
        history_file = "history.data"
        star = ms.MesaData(file_name=direc)
        effectiveT = star.data("log_Teff")
        logL = star.data("log_L")
    plt.plot(effectiveT, logL, 'k-', linewidth=2)
    #for profile in profnum:
    #            if np.mod(profile,2) == 0:
    #                index_num = np.int(modnum[profnum == profile][0]) - 1
    #                print index_num
    #                plt.plot(np.log10(effectiveT[index_num]),logL[index_num],'kd')
    plt.gca().invert_xaxis()
            #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[
Esempio n. 17
0
                    action='store_true',
                    default=False)
args = parser.parse_args()

if not (args.indata):
    parser.error('No indata supplied. Add "-i mesadata.dat", for example.')

import matplotlib.pyplot as plt
from astropy.io import ascii
from astropy.table import Table
import numpy as np
import mesa_reader as mr
import astropy.constants as c
R_SUN_CGS = c.R_sun.cgs.value

prof = mr.MesaData(args.indata)
#prof = ascii.read(args.indata, header_start=4, data_start=5, format='basic', guess=False)
#print prof.colnames

# plot something if we want to
if args.plot:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(prof.data('logRho'), prof.data('logP'), '-', color='black', lw=2)
    fig.savefig('P_vs_Rho.png')

# mass fraction of each of the elements we wish to track
mf_els = np.empty([len(args.els), len(prof.logR)])
for i in np.arange(0, len(args.els)):
    mf_els[i] = prof.data(args.els[i])
Esempio n. 18
0
# ~plt.axvline(0.0, c='k', label=r'$\alpha = 2.0$')
# ~plt.subplots_adjust(bottom = 0.13)
# ~plt.title(string_met)
# ~lgnd = plt.legend(loc='best', fontsize=12)
# ~plt.xlabel(r'$\rm \Delta_{\alpha}$', fontsize=16)
# ~plt.ylabel(r'$\rm \Delta_{color}$', fontsize=16)
# ~plt.show()
# ~plt.close()
# ~kill

########################################################################
########################################################################
string_mass = 'M075'
string_met = 'Z00025'
h1 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/' +
                 string_mass + '/scatter_test/' + string_met +
                 '/history_fid.data')
col1, mag1, mp1 = cut2(h1)
h2 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/' +
                 string_mass + '/scatter_test/' + string_met +
                 '/history_m1sigma.data')
col2, mag2, mp2 = cut2(h2)
h3 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/' +
                 string_mass + '/scatter_test/' + string_met +
                 '/history_p1sigma.data')
col3, mag3, mp3 = cut2(h3)

plt.figure()
if string_met == 'Z00015':
    h4 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/' +
                     string_mass + '/scatter_test/' + string_met +
Esempio n. 19
0
def getMaxRadiusProfile(workingDirectory):
    """Returns the profile with the biggest radius in a directory.
    
    Keyword arguments:
    workingDirectory -- target directory
    """

    import os
    import mesa_reader as mr
    from heapq import nlargest
    import numpy as np

    filenames = []

    for root, dirs, files in os.walk(workingDirectory):
        for file in files:
            if file.endswith("history.data"):
                filenames.append(os.path.join(root, file))

    # for each file, go in and correct that quotation mark error
    # replace 10.14-2019 with 10.14-2019"
    for file in filenames:
        s = open(file).read()
        s = s.replace('10.14-2019 ', '10.14-2019"')
        f = open(file, 'w')
        f.write(s)
        f.close()

    # for each file, read it into a variable based on which log folder it's in
    hBRExists = False
    hARExists, hRExists = False, False
    htSBExists, htlgTExists = False, False
    hCExists, hFExists, hLExists = False, False, False

    for file in filenames:
        if 'before_remove' in file:
            hBR = mr.MesaData(file)
            hBRExists = True

        elif 'after_remove' in file:
            hAR = mr.MesaData(file)
            hARExists = True

        elif 'remove' in file:
            hR = mr.MesaData(file)
            hRExists = True

        elif 'to_si_burn' in file:
            htSB = mr.MesaData(file)
            htSBExists = True

        elif 'to_lgT_9.9' in file:
            htlgT = mr.MesaData(file)
            hlgTExists = True

        elif 'convert' in file:
            hC = mr.MesaData(file)
            hCExists = True

        elif 'finish' in file:
            hF = mr.MesaData(file)
            hFExists = True

        else:
            hL = mr.MesaData(file)
            hLExists = True

    # frankenstein the data together because MESA is MESA

    hModels = []
    hRadius = []

    if hBRExists:
        hRadius.append(hBR.log_R)
        hModels.append(hBR.model_number)

    if hRExists:
        hRadius.append(hR.log_R)
        hModels.append(hR.model_number)

    if hARExists:
        hRadius.append(hAR.log_R)
        hModels.append(hAR.model_number)

    if htSBExists:
        hRadius.append(htSB.log_R)
        hModels.append(htSB.model_number)

    if htlgTExists:
        hRadius.append(htlgT.log_R)
        hModels.append(htlgT.model_number)

    if hCExists:
        hRadius.append(hC.log_R)
        hModels.append(hC.model_number)

    # these are behaving weirdly
    # if hFExists:
    #     hRadius.append(hF.log_R)
    #     hModels.append(hF.model_number)

    if hLExists:
        hRadius.append(hL.log_R)
        hModels.append(hL.model_number)

    # find the model number for when the radius is at its maximum
    maxValues = []
    maxModelNumbers = []

    # find the biggest 5 in each history file
    for x in range(len(hRadius)):
        data = hRadius[x]
        maxValues.append(nlargest(1, data))
        index = nlargest(1, range(len(data)), key=lambda idx: data[idx])
        maxModelNumbers.append(hModels[x][index])

    print(maxValues)
    print(maxModelNumbers)
    print('-----')
    print(max(maxValues))
    modelNumber = int(maxModelNumbers[np.argmax(maxValues)])
    print(modelNumber)

    # import desired profile

    # find all profile.index files
    filenames = []

    for root, dirs, files in os.walk(workingDirectory):
        for file in files:
            if file.endswith("profiles.index"):
                filenames.append(os.path.join(root, file))

    profiles = []
    # import files
    for file in filenames:
        i = mr.MesaProfileIndex(file)
        profiles.append(i)

    return getClosestModel(modelNumber, workingDirectory)
Esempio n. 20
0
#!/usr/bin/env python
import mesa_reader as mr
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import sys

cgsLsun = 3.848 * (10**33)
palette = plt.get_cmap('viridis')

history = []
for i in range(1, len(sys.argv)):
    history.append(mr.MesaData(str(sys.argv[i])))

# HR
# for all stars
for i in range(len(history)):
    lab = str(history[i])
    plt.plot(history[i].log_Teff,
             history[i].log_L,
             color=palette(i / len(history)),
             ls='-',
             linewidth=2,
             label=lab)

    # anotation
    hit_ZAMS = False

    # for all timesteps in a star
    for j in range(len(history[i].star_age)):
        nucpercent = 10**(history[i].log_Lnuc[j]) / 10**(history[i].log_L[j])
Esempio n. 21
0
    def run_support(self, inlist, check_age):
        """ Helper function for running MESA.

        Args:
            inlist (str): Inlist to run.
            check_age (bool): Check whether the output
                              model has the desired max_age.
        """

        # to-do: implement option to store terminal
        # output in a log file
        self.remove_file('inlist')
        self.remove_file('restart_photo')
        copy2(inlist, 'inlist')
        ma = MesaAccess()
        self.model_name = ma['save_model_filename']
        self.profile_name = ma['filename_for_profile_when_terminate']

        try:
            self.history_name = ma['star_history_name']
        except KeyError:
            self.history_name = 'history.data'

        if(self.pause):
            ma['pause_before_terminate'] = True
        else:
            ma['pause_before_terminate'] = False

        if(self.pgstar):
            ma['pgstar_flag'] = True
        else:
            ma['pgstar_flag'] = False

        self.remove_file(self.model_name)
        self.remove_file(self.profile_name)

        start_time = datetime.datetime.now()
        if(os.path.isfile('star')):
            print('Running', inlist)
            subprocess.call('./star')
        else:
            print('You need to build star first!')
            sys.exit()
        end_time = datetime.datetime.now()
        run_time = str(end_time - start_time)
        self.run_time = run_time
        micro_index = run_time.find('.')

        if(check_age):
            if(os.path.isfile(self.profile_name)):
                md = mr.MesaData(self.profile_name)
                star_age = md.star_age
                max_age = ma['max_age']

                if(star_age < max_age):
                    print(42 * '%')
                    print('Star age is {:.2E}, while max age is {:.2E}'
                          .format(star_age, max_age))
                    print('Failed to complete', inlist,
                          'after {} h:mm:ss'.format(run_time[:micro_index]))
                    print(42 * '%')
                    self.convergence = False
                else:
                    print(42 * '%')
                    print('Evolving the star took:',
                          '{} h:mm:ss'.format(run_time[:micro_index]))
                    print(42 * '%')
                    self.convergence = True
            else:
                print(42 * '%')
                print('Failed to complete', inlist,
                      'after {} h:mm:ss'.format(run_time[:micro_index]))
                print(42 * '%')
                self.convergence = False

        else:
            if(os.path.isfile(self.model_name)):
                print(42 * '%')
                print('Evolving the star took:',
                      '{} h:mm:ss'.format(run_time[:micro_index]))
                print(42 * '%')
                self.convergence = True
            else:
                print(42 * '%')
                print('Failed to complete', inlist,
                      'after {} h:mm:ss'.format(run_time[:micro_index]))
                print(42 * '%')
                self.convergence = False
Esempio n. 22
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')
    #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 = []

    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)

########################################################################
# 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'))
Esempio n. 23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-D",
                        "--dir",
                        nargs='+',
                        help="directory containing data files",
                        type=str)
    parser.add_argument("--HR", help="plot an HR diagram", action='store_true')
    parser.add_argument("-f",
                        "--filename",
                        help="filename for the plots to be produced",
                        type=str)
    parser.add_argument("--PDF",
                        help="produce PDFs of the plots",
                        action='store_true')
    # parser.add_argument("-H", "--heatmap", help="plot heatmaps for alpha, beta, and gamma", action='store_true')
    args = parser.parse_args()

    # assign various physical constants as global variables
    assign_const()

    # set up some plotting stuff
    fig = plt.figure(figsize=(12, 8))
    # plt.style.use('fast')
    plt.style.use('Solarize_Light2')
    palette = plt.get_cmap('magma')
    vir = plt.get_cmap('viridis')

    # filename handling
    if args.filename:
        # custom file name
        filename = args.filename
    else:
        # or just concatinate all the directory names
        filename = ''.join(args.dir)

    # make our history list
    if args.dir:
        history = []
        for i in range(len(args.dir)):
            # pick up the data from MESA files
            # history.append(mr.MesaLogDir(log_path=args.dir[i], history_file='history_' + args.dir[i] + '.data'))
            history.append(
                mr.MesaData(args.dir[i] + '/history_' + args.dir[i] + '.data'))

    # create our legend labels
    hist_lab = gen_hist_labels(history)

    # find the interesting profile indices
    # profs = gen_profs(history, args.dir)

    # create our profile labels
    # prof_lab = gen_prof_lab(profs)

    # hurtsburger and rustal
    if args.HR:
        for i in range(len(history)):
            # make actual plot
            plt.plot(history[i].log_Teff,
                     history[i].log_L,
                     color=vir(i / len(history)),
                     ls='-',
                     linewidth=2,
                     label=hist_lab[i])

        # add ZAMS anotation
        hit_ZAMS = False

        # for all timesteps in a star
        for j in range(len(history[i].star_age)):
            nucpercent = 10**(history[i].log_Lnuc[j]) / 10**(
                history[i].log_L[j])
            if nucpercent > 0.900 and hit_ZAMS == False and history[
                    i].star_age[j] > 50.0:
                plt.scatter(history[i].log_Teff[j],
                            history[i].log_L[j],
                            c="#E0115F",
                            s=10)
                plt.annotate(
                    str(round(history[i].star_age[j])) + " yr " +
                    str(round(history[i].radius[j], 2)) + " $R_{\odot}$",
                    (history[i].log_Teff[j], history[i].log_L[j]))
                hit_ZAMS = True

        # make the plot
        plt.title("HR Diagram: " + filename)
        plt.legend()
        plt.gca().invert_xaxis()
        plt.ylabel('log($L$) [$L_{\odot}$]')
        plt.xlabel('log($T_{eff}$) [K]')
        plt.savefig(filename + ".png", dpi=400)
        if args.PDF:
            plt.savefig(filename + ".pdf")
        plt.clf()
Esempio n. 24
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
Esempio n. 25
0
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
Esempio n. 26
0
def evaluate_initial_grid(grid_dir, output):
    """Reads history files in a directory tree and saves parameters to a single file.

    Parameters
    ----------
    grid_dir : str
        Path to the directory with history files.
    output : str
        The name of output file.

    Returns
    ----------
    None
    """

    history_files = glob.glob(grid_dir + '/history*')
    n = len(history_files)

    # model_number's type should be int64, but there is an issue with
    # formatting pandas output for integers
    grid = np.zeros(n, dtype= \
  [('m_i', 'float64'), \
        ('rot', 'float64'), \
        ('z', 'float64'), \
        ('y', 'float64'), \
        ('fh', 'float64'), \
        ('fhe', 'float64'), \
        ('fenv', 'float64'), \
        ('mlt', 'float64'), \
        ('sc', 'float64'), \
        ('reimers', 'float64'), \
        ('blocker', 'float64'), \
        ('turbulence', 'float64'), \
        ('m', 'float64'), \
        ('model_number', 'float64'), \
        ('log_Teff', 'float64'), \
        ('log_L', 'float64'), \
        ('age', 'float64'), \
        ('m_core', 'float64')])

    for i, track in enumerate(history_files):
        print(track)
        initial_parameters = read_progenitor_name(os.path.basename(track))
        data = mesa.MesaData(track)
        if data.center_h1[-1] < 1e-4:
            rgb_tip = find_rgb_tip(data)

            grid['m_i'][i] = initial_parameters['m']
            grid['rot'][i] = initial_parameters['rot']
            grid['z'][i] = initial_parameters['z']
            grid['y'][i] = initial_parameters['y']
            grid['fh'][i] = initial_parameters['fh']
            grid['fhe'][i] = initial_parameters['fhe']
            grid['fenv'][i] = initial_parameters['fenv']
            grid['mlt'][i] = initial_parameters['mlt']
            grid['sc'][i] = initial_parameters['sc']
            grid['reimers'][i] = initial_parameters['reimers']
            grid['blocker'][i] = initial_parameters['blocker']
            grid['turbulence'][i] = initial_parameters['turbulence']
            grid['m'][i] = data.star_mass[rgb_tip]
            grid['model_number'][i] = data.model_number[rgb_tip]
            grid['log_Teff'][i] = data.log_Teff[rgb_tip]
            grid['log_L'][i] = data.log_L[rgb_tip]
            grid['age'][i] = data.star_age[rgb_tip]
            grid['m_core'][i] = data.he_core_mass[rgb_tip]
        else:
            os.remove(track)
            print("Deleted!")
        print('')

    save_grid_to_file(grid, output)
Esempio n. 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()
Esempio n. 28
0
def buildStar(profileFile="profile15.data", makePlot=False):
    data = mr.MesaData(profileFile)

    logT = data.logT
    mass = data.mass
    logR = data.logR
    logRho = data.logRho
    logP = data.logP
    Hfrac = data.x_mass_fraction_H
    dlogTdlogP = (logT[1:] - logT[:-1]) / (logP[1:] - logP[:-1])
    dlogTdlogP = np.append(np.array([dlogTdlogP[0]]), dlogTdlogP)
    R = 1e1**logR

    mtot = mass.max()
    print 'mtot = ' + str(mtot)
    maxR = R.max()

    rho = 1e1**logRho
    if (makePlot):
        plt.clf()
        plt.semilogy(R, 1e1**logRho, lw=2, color="blue")

    meanRho = mtot * mSun / (4. * math.pi / 3. * (maxR * rSun)**3)
    print 'mean density = ' + str(meanRho)
    # cutoffRho = 10.0*meanRho
    cutoffRho = 0.5
    print 'cutoff density = ' + str(cutoffRho)

    boolArray = rho < cutoffRho
    nboolArray = np.logical_not(boolArray)
    massCentral = 0.
    logRCentral = -9.
    if (any(nboolArray)):
        massCentral = mass[nboolArray].max()
        logRCentral = logR[nboolArray].max()

    mass = mass[boolArray]
    logR = logR[boolArray]
    logT = logT[boolArray]
    logRho = logRho[boolArray]
    logP = logP[boolArray]
    dlogTdlogP = dlogTdlogP[boolArray]
    Hfrac = Hfrac[boolArray]
    R = R[boolArray]

    R = 1e1**logR
    pipe = subprocess.Popen("./hydro",
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE)
    #pipe = subprocess.Popen("./hydro", stdin=subprocess.PIPE)

    input_string = []
    input_string.append("{0:12.10E} {1:12.10E}\n".format(
        massCentral, 1e1**logRCentral))
    input_string.append("{0}\n".format(R.size))
    for m, lgr, lgrho, lgT, lgP, dlTdlP, Xfrac in zip(mass, logR, logRho, logT,
                                                      logP, dlogTdlogP,
                                                      Hfrac)[::-1]:
        input_string.append(
            "{0:12.10E} {1:12.10E} {2:12.10E} {3:12.10E} {4:12.10E} {5:12.10E} {6:12.10E}\n"
            .format(m, lgr, lgrho, lgT, lgP, dlTdlP, Xfrac))
    output_string = pipe.communicate("".join(input_string))[0]
    #pipe.communicate( "".join(input_string))[0]
    print output_string

    mcore, rcore = np.genfromtxt(io.BytesIO(output_string),
                                 max_rows=1,
                                 unpack=True)
    print "core mass: {0}, core radius = {1}".format(mcore, rcore)
    m, r, rho, T, p, Xout = np.genfromtxt(io.BytesIO(output_string),
                                          skip_header=2,
                                          unpack=True)
    print "maxR: {0}, Rmax = {1}".format(maxR, r.max())
    boolArray = filterMonotonicity(rho)
    # for dens,temp,g in zip( rho, T,gamma):
    #   print dens, temp, g
    if (makePlot):
        plt.semilogy(r, rho, ls="dashed", lw=3, color="green")
        plt.savefig("test.pdf")

    return mcore, rcore, m[boolArray], r[boolArray], rho[boolArray], T[
        boolArray], Xout[boolArray]
Esempio n. 29
0
#-----------------------------------------------------------------------
### comparison to isochrone ####
#-----------------------------------------------------------------------


Age = np.log10(13.32e9)
distance = 0
Abs = 0
# ~met1 = -1.95
met1 = -2.0
met2 = -1.75
met3 = -1.5

string_mass = 'M075'
string_met = 'scatter_test'
htest1 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_a1938.data')
coltest1,magtest1, mptest1 = cut2(htest1)
# htest1bis = mr.MesaData('/home/david/codes/data/GC_mixing_length/initial_mesa_dir/LOGS/history_a1938bis.data')
# coltest1bis,magtest1bis, mptest1bis = cut2(htest1bis)
htest2 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_z00045.data')
coltest2,magtest2, mptest2 = cut2(htest2)
htest3 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_z000142.data')
coltest3,magtest3, mptest3 = cut2(htest3)
htest4 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_m080.data')
coltest4,magtest4, mptest4 = cut2(htest4)
# ~htest5 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_a1888.data')
# ~coltest5,magtest5, mptest5 = cut2(htest5)
# ~htest6 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_a1988.data')
# ~coltest6,magtest6, mptest6 = cut2(htest6)
# ~htest7 = mr.MesaData('/home/david/codes/Analysis/GC_mixing_length/catalogs/'+string_mass+'/'+string_met+'/history_a1838.data')
# ~coltest7,magtest7, mptest7 = cut2(htest7)
def Main():

    if (len(sys.argv) == 1):
        print ""
        print "Please include the 'history.data' file:"
        print "  python XRayFreq.py history.data"
        print ""
        print "python XRayFreq.py -h : Help."
        print ""
        return

    if (sys.argv[1] == "-h"):
        PrintHelp()
        return

    print ""
    print "Getting the MESA data..."
    print ""

    # Load the "history.data" file and store it in "h" using Mesa_reader capabilities
    h = mr.MesaData(sys.argv[1])

    # Retrieve the star age (in hours) and save it in "time" array
    time = h.data('star_age_hr')

    # Retrieve the luminosity
    lumi = h.data('log_L')
    #	lumi=h.data('net_energy');

    if (len(sys.argv) == 3) and (sys.argv[2] == "-t"):
        DoTemp(h.data('log_Teff'), time, h.data('star_mass'))
        return

    #Find the peaks
    Peaks = []
    Peak_Times = []
    Valleys = []
    Valley_Times = []
    Averages_In = []

    Peaks, Peak_Times, Valleys, Valley_Times, Averages_In = FindPeaks(
        lumi, time)

    if (len(sys.argv) == 3) and (sys.argv[2] == "-d"):
        DrawData(time, lumi, Peaks, Peak_Times, Valleys, Valley_Times, "draw")

    if (len(sys.argv) == 3) and (sys.argv[2] == "-p"):
        DrawData(time, lumi, Peaks, Peak_Times, Valleys, Valley_Times, "print")

    #Peak_Times = Peak_Times[0:4]
    print "Number of peaks = ", len(Peak_Times)
    print "Peak times [hr]:"
    print Peak_Times
    print "Average Peak Luminosity   = ", Averages_In[0]
    print "Average Valley Luminosity = ", Averages_In[1]
    print "Average Rise Time = ", Averages_In[2]
    print "Average Fall Time = ", Averages_In[3]

    time_period = FindPeakFrequency(Peak_Times)

    frequency = 1 / time_period

    print ""
    print "Time period = ", time_period, " [hr]"
    print "Frequency   = ", frequency, " [1 / hr]"
    print ""

    if (len(sys.argv) == 3) and (sys.argv[2] == "-s"):
        SaveData(time, lumi, Peak_Times, Peaks)

    if (len(sys.argv) == 3) and (sys.argv[2] == "-f"):
        SaveFreqs(frequency, time_period, len(Peaks), h.data('star_mass'),
                  Averages_In, "FrequencyData.txt")