Esempio n. 1
0
def find_final_difference(datafile1, datafile2, print_values=True):
    '''A function to find final absolute difference between mass fraction in two datafiles.
        
        Inputs: datafile1 = ts file to be compared
        datafile2 = second ts file to be compared
        print_values = default to True, if True will print differences, if not will return lists of differences and corresponding nuclide names
        
        Output: largest = list of n largest differences
        names = list of nuclide names corresponding to items in largest
        '''

    import numpy as np
    import read_ts_file as rtf
    import heapq

    #Read ts file, rename variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Set certain parameters based on the data.
    num_species_total = np.shape(xmf1)[1]
    num_timesteps = np.shape(xmf1)[0]

    #Read the second ts file, rename variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Make empty list for maximum differences.
    max_diff = []
    for counter in np.arange(
            0, num_species_total):  #Count through number of species.
        diff_list = []  #Make empty list for differences.
        diff = float(xmf1[-1][counter]) - float(
            xmf2[-1]
            [counter])  #Find differences at end (accessed by -1), add to list.
        diff = abs(diff)
        diff_list.append(diff)
        max_diff.append(
            max(diff_list))  #Add largest difference to max_diff list.

    largest = heapq.nlargest(
        n, max_diff
    )  #list of final absolute differences, from largest to smallest
    names = []  #Make empty list for names to fill in to.
    for item in largest:  #Assign relevant name to each difference.
        foo = max_diff.index(item)
        name = nuc_name[foo]
        names.append(name)

    #Either print or return largest and names.
    if print_values == True:
        for counter in np.arange(0, n):
            print("%s     %s     %s" %
                  (counter + 1, names[counter], largest[counter]))
    else:
        return largest, names
Esempio n. 2
0
def find_point_difference(datafile1, datafile2, t):
    '''A function to find differences between mass fraction in two datafiles at a specific timestep.
        
        Inputs: datafile1 = ts file to be compared
        datafile2 = second ts file to be compared
        t = timestep desired
        
        Output: largest = list of n largest differences
        names = list of nuclide names corresponding to items in largest
    '''

    import numpy as np
    import read_ts_file as rtf
    import heapq

    #Read datafile, rename variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Set certain parameters based on the data.
    num_species_total = np.shape(xmf1)[1]
    num_timesteps = np.shape(xmf1)[0]

    #Read second ts file, rename and use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    diff_list = []  #Make empty list for differences.
    for counter in np.arange(
            0, num_species_total):  #Count through number of species.
        diff = float(xmf1[t][counter]) - float(
            xmf2[t][counter]
        )  #Find each difference at specified timestep, add to list.
        diff = abs(diff)
        diff_list.append(diff)

    largest = heapq.nlargest(
        n, diff_list)  #Rearrange diff_list into largest to smallest order.
    names = []  #Make empty list for names to fill in to.
    for item in largest:  #Assign relevant name to each difference.
        foo = diff_list.index(item)
        name = nuc_name[foo]
        names.append(name)
    return largest, names  #Return lists of differences and names.

    #Print results.
    for counter in np.arange(0, n):
        print("%s     %s     %s" %
              (counter + 1, names[counter], largest[counter]))
def write_final_abundances(directory_files,
                           file_name="test.txt",
                           appending=False):
    '''
        Inputs: directory_files: the full String pathway to the desired files, suggested ending is /ts_final_*
                file_name = String that names the file created or designates which file to append data to
                appending: boolean where False writes a new file and True adds new data onto file_name, defaults to False
        Output: a new file, "file_name", or an expanded file, with final abundance data for each species
        '''
    import numpy as np
    import read_ts_file as rtf
    import glob as g

    #Open a new file, or open a previous one to add to.
    if appending == False:
        f = open(file_name, "w")

    else:
        f = open(file_name, "a")
        f.writelines("\n")

    #Initialize a counter to make the header print only once.
    counter = 1

    #Create a list of all desired files in the given directory.
    files = g.glob(directory_files)
    number_of_files = len(files)

    non_ejecta = []

    for datafile in files:

        print(datafile)
        print("%s" % counter)

        #Read data file, use variable names.
        zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
            datafile, last=True)
        nuc_name = rtf.build_isotope_symbol(zz, aa)

        #Set certain parameters based on the size of the data.
        num_species_total = np.shape(xmf)[1]
        timesteps_total = np.shape(xmf)[0]
        #print timesteps_total

        #Write header with species names only as a first line.
        if counter == 1:
            f.writelines("%s " % item for item in nuc_name)
            f.writelines("\n")

        if timesteps_total < 10:
            non_ejecta.append(datafile)
            counter += 1

        else:
            #Access the last mass fraction value in the array for each species, and make a list of them.
            xmf_list = []
            for counter in np.arange(0, num_species_total):
                foo = xmf[-1][counter]
                xmf_list.append(foo)

            #Write datafile name, each final abundance from xmf_list, and go to a new line at the end of the file.
            f.writelines("%s " % datafile)
            f.writelines("%s " % item for item in xmf_list)
            f.writelines("\n")

            #Makes the header print only once.
            counter += 1

    f.writelines("Non-ejecta: ")
    f.writelines("%s " % item for item in non_ejecta)

    #Tie up loose ends and close the file when finished.
    f.close()
Esempio n. 4
0
def massfractiont9rhovtime2(datafile1,
                            datafile2,
                            end,
                            num_plots=2,
                            num_species=14,
                            min_mf=.00000001,
                            time_spacing=.2,
                            h_ratio=[3, 1],
                            zz_wanted='None',
                            zz_wanted2='None',
                            aa_wanted='None',
                            nuc_names_wanted='None'):
    '''
        Inputs: datafile = must be a .txt file, ev file, any unnamed columns must be named with a single letter
        end = k value at end of desired time
        num_plots = number of plots to be shown simultaneously, default to 2
        num_species = default to 14
        min_mf = cutoff point below which mass fraction does not appear on the graph, default to .00000001
        time_spacing = desired interval between x-axis ticks, default to .2
        h_ratio = height ratio (if plotting several plots), default to 3:1
        
        Outputs: plot of mass fraction, temperature, and density vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    import random
    import string
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import read_ts_file as rtf

    #Create plot space
    plt.figure(1)

    #Read ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set up grid layout
    total_height = h_ratio[0] + h_ratio[1]
    gs = gridspec.GridSpec(total_height, 1)

    #Set parameter based on data.
    num_species_total = np.shape(xmf1)[1]

    #Assign each species a random color.
    #    colors = []
    #for counter in np.arange(0, num_species_total):
    #   item = np.random.rand()
    #   colors.append(item)

    colors = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors.append(item1)
        colors.append(item2)
        colors.append(item3)
    colors = np.asarray(colors)
    colors = colors.reshape((num_species_total, 3))

    #Create first plot according to grid structure.
    ax1 = plt.subplot(gs[:h_ratio[0], :])

    #Plot mf, add a legend.
    for counter in np.arange(0, num_species_total):
        if zz_wanted != 'None':
            if zz1[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                if zz1[counter] == 1 and aa1[
                        counter] == 1:  #Explicitly plots protons and hydrogen.
                    plt.plot(time1,
                             xmf1[:, counter],
                             color='r',
                             label=nuc_name[counter])
                elif zz1[counter] == 1 and aa1[counter] == 2:
                    plt.plot(time1,
                             xmf1[:, counter],
                             color='b',
                             label=nuc_name[counter])
                else:
                    plt.plot(time1,
                             xmf1[:, counter],
                             color=colors[counter],
                             label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
            elif zz1[counter] in zz_wanted and aa1[
                    counter] in aa_wanted:  #Plot by atomic number and mass number.
                plt.plot(time1,
                         xmf1[:, counter],
                         color=colors[counter],
                         label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
                zz_wanted.remove(zz1[counter])
        elif zz_wanted == 'None' and nuc_names_wanted == 'None':  #Plot all species above specified threshold.
            if np.amax(xmf1[:, counter]) >= min_mf:
                plt.plot(time1, xmf1[:, counter], color=colors[counter])
        elif nuc_names_wanted != 'None':  #Listed nuclear names switches plotting mechanism.
            break

    if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            species_number = int(species_number)
            plt.plot(time1,
                     xmf1[:, species_number],
                     color=colors[species_number],
                     label=nuc_name[species_number])
            box = ax1.get_position()
            ax1.set_position([box.x0, box.y0, box.width * 0.995, box.height])
            ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=10)

    #Start of datafile2.

    #Read second ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx
    element = rtf.build_element_symbol()

    #Set parameter based on data size.
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Repeat plotting process above, using dashed lines and second set of provided information.
    num_species_total = np.shape(xmf2)[1]
    for counter in np.arange(0, num_species_total):
        if zz_wanted2 != 'None':
            if zz2[counter] in zz_wanted2 and aa_wanted == 'None':
                if zz[counter] == 1 and aa2[counter] == 1:
                    plt.plot(time2,
                             xmf2[:, counter],
                             color='r',
                             label=nuc_name[counter],
                             linestyle='--')
                elif zz2[counter] == 1 and aa2[counter] == 2:
                    plt.plot(time2,
                             xmf2[:, counter],
                             color='b',
                             label=nuc_name[counter],
                             linestyle='--')
                else:
                    plt.plot(time2,
                             xmf2[:, counter],
                             color=colors[counter],
                             label=nuc_name[counter],
                             linestyle='--')
            elif zz2[counter] in zz_wanted2 and aa2[counter] in aa_wanted:
                plt.plot(time2,
                         xmf2[:, counter],
                         color=colors[counter],
                         label=nuc_name[counter],
                         linestyle='--')
                zz_wanted2.remove(zz2[counter])
                aa_wanted.remove(aa2[counter])
        elif zz_wanted2 == 'None' and nuc_names_wanted == 'None':
            if np.amax(xmf2[:, counter]) >= min_mf:
                plt.plot(time2,
                         xmf2[:, counter],
                         color=colors[counter],
                         linestyle='--')
        elif nuc_names_wanted != 'None':
            break

    if nuc_names_wanted != 'None':
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            plt.plot(time2,
                     xmf2[:, species_number],
                     color=colors[species_number],
                     label=nuc_name[species_number],
                     linestyle='--')

    #Format and label axes.
    plt.yscale('log')
    plt.ylim(min_mf, 1.5)
    plt.ylabel("Mass Fraction")

    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Remove superfluous ticks, show grid line instead.
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)

    plt.title("%s (solid) and %s (dashed)" % (datafile1, datafile2))

    #Create subplot.
    ax2 = plt.subplot(gs[h_ratio[0], :])
    plt.subplots_adjust(wspace=0, hspace=0)

    #Plot temperature vs time, format axis.
    temp_line = plt.plot(time1, temperature1, color='r', label="Temperature")
    temp_line2 = plt.plot(time2,
                          temperature2,
                          color='r',
                          linestyle='--',
                          label="Temperature")
    plt.yscale('linear')
    plt.ylim(0, 10)
    plt.ylabel("Temperature (GK)")

    #Format x axis.
    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Remove superfluous ticks, show grid line instead.
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)

    #Plot density vs time, format axis.
    ax3 = ax2.twinx()
    dens_line = ax3.plot(time1, density1, color='b', label="Density")
    dens_line2 = ax3.plot(time2,
                          density2,
                          color='b',
                          linestyle='--',
                          label="Density")
    plt.yscale('log')
    plt.ylim(10E0, 10E10)
    plt.ylabel("Density g/$\mathregular{cm^3}$")
    loc = plticker.LogLocator(base=100.0)
    ax3.yaxis.set_major_locator(loc)

    #Format x axis (repeated so that it does not go to default settings)
    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Add x ticks at specified intervals.
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)

    #Create a legend with both temperature and density.
    lines = temp_line + dens_line
    labs = [l.get_label() for l in lines]
    ax2.legend(lines, labs, fontsize=10, loc='upper right')

    lines2 = temp_line2 + dens_line2
    labs2 = [l.get_label() for l in lines2]
    #ax3.legend(lines2, labs2, fontsize = 10, loc = 'upper right')

    #Show graph
    plt.show()
Esempio n. 5
0
def write_final_abundances(directory_files,
                           file_name="test.txt",
                           appending=False,
                           print_positions=False,
                           last=False,
                           latex_nuc_name=False):
    '''
        Inputs: directory_files: the full String pathway to the desired files, suggested ending is /ts_final_*
                file_name = String that names the file created or designates which file to append data to
                appending: boolean where False writes a new file and True adds new data onto file_name, defaults to False
                print_positions: boolean where True prints file positions to screen (mostly for debug), defaults to False
                last : boolean where True skips to the end of the file to just read the final abundances, defaults to False
                print_positions and last are passed to read_ts_file
        Output: a new file, "file_name", or an expanded file, with final abundance data for each species
        '''
    import numpy as np
    import read_ts_file as rtf
    import glob as g
    import find_file_type_temp as fft

    #Open a new file, or open a previous one to add to.
    if appending == False:
        f = open(file_name, "w")

    else:
        f = open(file_name, "a")
        f.writelines("\n")

    #Initialize a counter to make the header print only once.
    counter = 1

    #Create a list of all desired files in the given directory.
    files = g.glob(directory_files)
    number_of_files = len(files)
    print(number_of_files)

    non_ejecta = []
    for datafile in files:

        print(datafile)
        filetype = fft.find_file_type(datafile)
        print(filetype)

        if filetype == 'ts':
            print("%s" % counter)

            #Read data file, use variable names.
            zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
                datafile, last=last, print_positions=print_positions)
            #nuc_name = rtf.build_isotope_symbol(zz, aa, latex=latex_nuc_name)
            nuc_name = rtf.build_isotope_symbol(zz, aa)

            #Set certain parameters based on the size of the data.
            num_species_total = np.shape(xmf)[1]
            timesteps_total = np.shape(xmf)[0]
            print(timesteps_total)

            #Write header with species names only as a first line.
            if counter == 1:
                # set size of padding based on first filename
                padding = len(datafile) + 5
                line = " ".ljust(padding)
                for item in nuc_name:
                    line = line + item.ljust(14)
                f.write(line + "\n")
                counter += 1

            if (not last) and (timesteps_total < 10):
                non_ejecta.append(datafile)
                counter += 1

            else:
                #Access the last mass fraction value in the array for each species, and make a list of them.
                xmf_list = []
                for counter2 in np.arange(0, num_species_total):
                    foo = xmf[-1][counter2]
                    xmf_list.append(foo)

                #Write datafile name, each final abundance from xmf_list, and go to a new line at the end of the file.
                line = datafile.ljust(padding)
                for item in xmf_list:
                    line = line + str("%.5e" % item).ljust(14)
                f.writelines(line + "\n")

                #Makes the header print only once.
                counter += 1

    f.writelines("Non-ejecta: ")
    f.writelines("%s " % item for item in non_ejecta)

    #Tie up loose ends and close the file when finished.
    f.close()
Esempio n. 6
0
def massfractionedot(datafile1,
                     end,
                     num_plots=2,
                     num_species=14,
                     min_mf=.00000001,
                     time_spacing=10,
                     h_ratio=[3, 1],
                     zz_wanted='None',
                     zz_wanted2='None',
                     aa_wanted='None',
                     nuc_names_wanted='None'):
    '''
        Inputs: datafile1 = ts file
        end = k value at end of desired time
        num_plots = number of plots to be shown simultaneously, default to 2
        num_species = default to 14
        min_mf = cutoff point below which mass fraction does not appear on the graph, default to .00000001
        time_spacing = desired interval between x-axis ticks, default to .2
        h_ratio = height ratio (if plotting several plots), default to 3:1
        
        Outputs: plot of mass fraction, energy vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    import random
    import string
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import read_ts_file as rtf

    #Create plot space
    plt.figure(1)

    #Read ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set up grid layout
    total_height = h_ratio[0] + h_ratio[1]
    gs = gridspec.GridSpec(total_height, 1)

    #Set parameter based on data.
    num_species_total = np.shape(xmf1)[1]

    #Assign each species a random color.
    colors_array = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors_array.append(item1)
        colors_array.append(item2)
        colors_array.append(item3)
    colors_array = np.asarray(colors_array)
    colors_array = colors_array.reshape((num_species_total, 3))

    #Create upper subplot.
    ax1 = plt.subplot(gs[:h_ratio[0], :])

    #Plot mf, add a legend.
    for counter in np.arange(0, num_species_total):
        if zz_wanted != 'None':
            if zz1[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                if zz1[counter] == 1 and aa1[
                        counter] == 1:  #Explicitly plots protons and hydrogen.
                    plt.plot(time1,
                             xmf1[:, counter],
                             color='r',
                             label=nuc_name[counter])
                elif zz1[counter] == 1 and aa1[counter] == 2:
                    plt.plot(time1,
                             xmf1[:, counter],
                             color='b',
                             label=nuc_name[counter])
                else:
                    plt.plot(time1,
                             xmf1[:, counter],
                             color=colors_array[counter],
                             label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
            elif zz1[counter] in zz_wanted and aa1[
                    counter] in aa_wanted:  #Plot by atomic number and mass number.
                plt.plot(time1,
                         xmf1[:, counter],
                         color=colors_array[counter],
                         label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
                zz_wanted.remove(zz1[counter])
        elif zz_wanted == 'None' and nuc_names_wanted == 'None':  #Plot all species above specified threshold.
            if np.amax(xmf1[:, counter]) >= min_mf:
                plt.plot(time1, xmf1[:, counter], color=colors_array[counter])
        elif nuc_names_wanted != 'None':  #Listed nuclear names switch plotting mechanism.
            break

    if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            species_number = int(species_number)
            plt.plot(time1,
                     xmf1[:, species_number],
                     color=colors_array[species_number],
                     label=nuc_name[species_number])
            box = ax1.get_position()
            ax1.set_position([box.x0, box.y0, box.width * 0.995, box.height])
            ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=10)

    #Format and label axes.
    plt.yscale('log')
    plt.ylim(min_mf, 1.5)
    plt.ylabel("Mass Fraction")

    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Remove superfluous ticks, show grid line instead.
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)

    plt.title("%s" % (datafile1))

    #Create subplot.
    ax2 = plt.subplot(gs[h_ratio[0], :])
    plt.subplots_adjust(wspace=0, hspace=0)

    #Plot edot vs time, format axis.
    edot_line = plt.plot(time1, edot1, color='r', label="dE/dt")
    plt.yscale('log')
    plt.ylim(10E2, 10E15)
    plt.ylabel("Energy Production (erg/g/s)")

    #Format x axis.
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Remove superfluous ticks, show grid line instead.
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)

    #Add x ticks at specified intervals.
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)

    #Create a legend with both temperature and density.
    lines = edot_line
    labs = [l.get_label() for l in lines]
    ax2.legend(lines, labs, fontsize=10, loc='upper right')

    #Show graph
    plt.show()
Esempio n. 7
0
def absolute_largest(datafile1, datafile2, print_values=True):
    '''
        Inputs: datafile1 = ts file
                datafile2 = second ts file
                print_values = default to True, if True will print differences, if not will return lists of differences and corresponding nuclide names
                
        Outputs: names= list of nuclide names corresponding to largest species in datafile1
                 largest = final abundances of species in datafile1 in descending order
                 names2 = list of nuclide names corresponding to largest species in datafile2
                 largest2 = final abundances of species in datafile2 in descending order
        '''

    import numpy as np
    import read_ts_file as rtf
    import heapq

    #Read datafile1, use variable names.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set certain parameters based on the shape of the data.
    num_species_total = np.shape(xmf)[1]
    n = num_species_total

    xmf_list = []  #Make empty list of abundances.
    for counter in np.arange(0,
                             num_species_total):  #Count through all species.
        foo = xmf[-1][counter]  #Find final abundances (shown by -1)
        xmf_list.append(foo)  #Add final abundance to list.

    largest = heapq.nlargest(
        n, xmf_list)  #Rearrange abundance list into descending order.
    names = []  #Create empty list for names to fill into.
    for item in largest:  #Add relevant names to correct position in list.
        bar = xmf_list.index(item)
        name = nuc_name[bar]
        names.append(name)

    #Read second data file, use variable names.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set parameter according to data.
    num_species_total = np.shape(xmf)[1]

    xmf_list2 = []  #Make second empty list of abundances.
    for counter in np.arange(
            0, num_species_total
    ):  #Count through all species, find final abundances (shown by -1), add to list.
        foo = xmf[-1][counter]
        xmf_list2.append(foo)

    largest2 = heapq.nlargest(
        n, xmf_list2)  #Rearrange xmf_list2 into descending order
    names2 = []  #Create empty list for names to fill in to.
    for item in largest2:  #Add relevant names to correct position in list.
        bar = xmf_list2.index(item)
        name = nuc_name[bar]
        names2.append(name)

    #Either print or return results.
    if print_values == True:
        for counter in np.arange(0, n):
            print "%s      %s      %s" % (counter + 1, names[counter],
                                          largest[counter], names2[counter],
                                          largest2[counter])

    else:
        return names, largest, names2, largest2
Esempio n. 8
0
def massfractionvtime(datafile,
                      end,
                      num_plots=1,
                      min_mf=.00000001,
                      time_spacing=.2,
                      h_ratio=[3, 1],
                      zz_wanted='None',
                      aa_wanted='None',
                      nuc_names_wanted='None'):
    '''
        Inputs: datafile = either an ev or a ts file
        end = k value at end of desired time
        num_plots = number of plots to be shown simultaneously, default to 1
        min_mf = cutoff point below which mass fraction does not appear on the graph, default to .00000001
        time_spacing = desired interval between x-axis ticks, default to .2
        h_ratio = height ratio (if plotting multiple plots), default to 3:1
        zz_wanted = list of atomic numbers of desired isotopes (if multiple isotopes of the same element are desired, their zz values must be added multiple times)
        aa_wanted = list of atomic masses of desired isotopes (used in conjunction with zz_wanted)
        nuc_names_wanted = list of desired species names, formatted as '$^{aa}$Symbol' (best option when plotting specific isotopes)
        
        Outputs: plot of mass fraction vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import find_file_type as fft
    import read_ev_file as ref
    import read_ts_file as rtf

    #Create plot space
    plt.figure(1)

    file_type = fft.find_file_type(datafile)

    #Set up grid layout
    total_height = h_ratio[0] + h_ratio[1]
    gs = gridspec.GridSpec(total_height, 1)

    if file_type == 'ev':
        #Read ev file, use variables.
        time, density, temperature, edot, timestep, species, data, datafile = ref.read_ev_file(
            datafile)

        #If there is only one plot, take up entire space, plot mf, and add a legend
        if num_plots == 1:
            ax1 = plt.subplot(1, 1, 1)
            for isotope in species:
                if data[isotope][end] <= min_mf:
                    plt.plot(time, data[isotope], label=isotope)
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)
                else:
                    plt.plot(time, data[isotope], label=isotope)
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)

        #Alternatively, follow given sizing guidelines, plot mf, and add a legend
        else:
            ax1 = plt.subplot(gs[:h_ratio[0], :])
            for isotope in species:
                if data[isotope][end] <= min_mf:
                    plt.plot(time, data[isotope], label=isotope)
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)

                else:
                    plt.plot(time, data[isotope], label=isotope)
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)

    elif file_type == 'ts':
        #Read ts file, use variables.
        zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
            datafile)
        print("File read.")
        element = rtf.build_element_symbol()
        nuc_name = rtf.build_isotope_symbol(zz, aa)
        num_species_total = np.shape(xmf)[1]

        #Assign each species a random color.
        colors_array = []
        for counter in np.arange(1, num_species_total + 1):
            item1 = np.random.rand(counter)[0]
            item2 = np.random.rand(counter)[0]
            item3 = np.random.rand(counter)[0]
            colors_array.append(item1)
            colors_array.append(item2)
            colors_array.append(item3)
        colors_array = np.asarray(colors_array)
        colors_array = colors_array.reshape((num_species_total, 3))
        print("Colors assigned.")

        #If there is only one plot, take up entire space, plot mf
        if num_plots == 1:
            ax1 = plt.subplot(1, 1, 1)
            num_species_total = np.shape(xmf)[1]
            for counter in np.arange(0, num_species_total):
                if zz_wanted != 'None':
                    if zz[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                        plt.plot(time,
                                 xmf[:, counter],
                                 label=nuc_name[counter],
                                 linestyle='--')
                        box = ax1.get_position()
                        ax1.set_position(
                            [box.x0, box.y0, box.width * 0.995, box.height])
                        ax1.legend(loc='center left',
                                   bbox_to_anchor=(1, 0.5),
                                   fontsize=10)
                    elif zz[counter] in zz_wanted and aa[
                            counter] in aa_wanted:  #Plot by atomic number and mass number.
                        plt.plot(time,
                                 xmf[:, counter],
                                 label=nuc_name[counter])
                        box = ax1.get_position()
                        ax1.set_position(
                            [box.x0, box.y0, box.width * 0.995, box.height])
                        ax1.legend(loc='center left',
                                   bbox_to_anchor=(1, 0.5),
                                   fontsize=10)
                        zz_wanted.remove(zz[counter])

                else:
                    if np.amax(
                            xmf[:, counter]
                    ) >= min_mf:  #Plot all species over specified threshold.
                        plt.plot(time, xmf[:, counter])

            if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
                for counter in np.arange(0, len(nuc_names_wanted)):
                    species_number = nuc_name.index(nuc_names_wanted[counter])
                    species_number = int(species_number)
                    plt.plot(time,
                             xmf[:, species_number],
                             color=colors[species_number],
                             label=nuc_name[species_number])
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)

            print("Data assigned to plot.")
        #Alternatively, follow given sizing guidelines, plot mf
        else:
            ax1 = plt.subplot(gs[:h_ratio[0], :])
            num_species_total = np.shape(xmf)[1]
            for counter in np.arange(0, num_species_total):
                if zz_wanted != 'None':  #If atomic numbers are specified
                    if zz[counter] in zz_wanted and aa[
                            counter] in aa_wanted:  #Plot by atomic number and mass number.
                        plt.plot(time,
                                 xmf[:, counter],
                                 label=nuc_name[counter])
                        box = ax1.get_position()
                        ax1.set_position(
                            [box.x0, box.y0, box.width * 0.995, box.height])
                        ax1.legend(loc='center left',
                                   bbox_to_anchor=(1, 0.5),
                                   fontsize=10)
                        zz_wanted.remove(zz[counter])
                    elif zz[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                        plt.plot(time,
                                 xmf[:, counter],
                                 label=nuc_name[counter])
                        box = ax1.get_position()
                        ax1.set_position(
                            [box.x0, box.y0, box.width * 0.995, box.height])
                        ax1.legend(loc='center left',
                                   bbox_to_anchor=(1, 0.5),
                                   fontsize=10)
                elif zz_wanted == 'None' and nuc_names_wanted == 'None':  #Plot all species above a specified threshold.
                    if np.amax(xmf[:, counter]) >= min_mf:
                        plt.plot(time, xmf[:, counter], color=colors_array)
                elif nuc_names_wanted != 'None':  #Listed nuclear names switch plotting mechanism.
                    break

            if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
                for counter in np.arange(0, len(nuc_names_wanted)):
                    species_number = nuc_name.index(nuc_names_wanted[counter])
                    species_number = int(species_number)
                    plt.plot(time,
                             xmf[:, species_number],
                             color=colors_array[species_number],
                             label=nuc_name[species_number])
                    box = ax1.get_position()
                    ax1.set_position(
                        [box.x0, box.y0, box.width * 0.995, box.height])
                    ax1.legend(loc='center left',
                               bbox_to_anchor=(1, 0.5),
                               fontsize=10)

            print("Data assigned to plot.")

    #Format and label axes
    plt.yscale('log')
    plt.ylim(min_mf, 1.5)
    plt.ylabel("Mass Fraction")

    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    print("Axes formatted.")

    #Add x ticks at specified intervals
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)

    print("Axes labeled.")

    #Remove superfluous ticks, show grid line instead
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)

    print("Grid line.")

    #Show graph
    plt.show()
    print("Plot shown.")
Esempio n. 9
0
def write_final_abundances_mass_shell(directory_files,
                                      propertiesfile,
                                      file_name="test.txt",
                                      appending=False,
                                      print_positions=False,
                                      last=False):
    '''
        Inputs: directory_files: the full String pathway to the desired files, suggested ending is /ts_final_*
                file_name = String that names the file created or designates which file to append data to
                appending: boolean where False writes a new file and True adds new data onto file_name, defaults to False
                print_positions: boolean where True prints file positions to screen (mostly for debug), defaults to False
                last : boolean where True skips to the end of the file to just read the final abundances, defaults to False
                print_positions and last are passed to read_ts_file
        Output: a new file, "file_name", or an expanded file, with final abundance data for each species and mass shell data from particle properties file
        '''
    import numpy as np
    import read_ts_file as rtf
    import glob as g

    #Open a new file, or open a previous one to add to.
    if appending == False:
        f = open(file_name, "w")

    else:
        f = open(file_name, "a")
        f.writelines("\n")

    #Initialize a counter to make the header print only once.
    counter = 1

    #Create a list of all desired files in the given directory.
    files = g.glob(directory_files)
    number_of_files = len(files)
    print(number_of_files)

    #Read in Properties File
    col_headers = ["Shell_Number", "Radius(cm)", "Mass_coord(M_sun)", "dm(g)"]
    properties = np.genfromtxt(propertiesfile, names=col_headers)

    non_ejecta = []
    for datafile in files:

        #Find file types of each file. Note that these if statements are used instead of find_file_type because file names in the NERSC directory
        #do not work well with the find_file_type tool, such as names having "ev" or "ts_307_png", and because the output message is unneccessary
        for item in np.arange(
                0, len(datafile)):  #count through letters in datafile
            if datafile[item] == 't' and datafile[
                    item + 1] == 'x' and datafile[item + 2] == 't':
                file_type = 'other'
                break

            elif datafile[item] == 't' and datafile[
                    item + 1] == 's' and datafile[
                        item +
                        2] == '_':  #if 't' and 's' and '_' appear consecutively, it's a ts file
                if datafile[-1] == 'g' and datafile[-2] == 'n':
                    file_type = 'other'
                else:
                    file_type = 'ts'
                    break

            else:
                file_type = 'other'

        if file_type == 'ts':
            print(datafile)
            #Add mass shell data from Properties File
            print("%s" % counter)
            mass_shell = datafile[-3] + datafile[-2] + datafile[-1]
            mass_shell_int = int(mass_shell)
            mass_shell_properties = properties[mass_shell_int - 2]

            #Read data file, use variable names.
            zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
                datafile, last=last, print_positions=print_positions)
            nuc_name = rtf.build_isotope_symbol(zz, aa)

            #Set certain parameters based on the size of the data.
            num_species_total = np.shape(xmf)[1]
            timesteps_total = np.shape(xmf)[0]

            #Write header with column headers and species names as a first line.
            if counter == 1:
                # set size of padding based on first filename
                padding = len(datafile) + 5
                line = "Shell_Number" + "   " + "Radius(cm)" + "   " + "Mass_coord(M_sun)" + "   " + "dm(g)" + "   " + "filename" + "   "
                for item in nuc_name:
                    line = line + item + "   "
                f.write(line + "\n")
                counter += 1

            if (not last) and (timesteps_total < 10):
                non_ejecta.append(datafile)
                counter += 1

            else:
                #Access the last mass fraction value in the array for each species, and make a list of them.
                xmf_list = []
                for counter2 in np.arange(0, num_species_total):
                    foo = xmf[-1][counter2]
                    xmf_list.append(foo)

                #Write mass shell properties, datafile name, each final abundance from xmf_list, and go to a new line at the end of the file.
                for item in mass_shell_properties:
                    line = str("%.5e" % item).ljust(14)
                    f.writelines(line)
                padding = len(datafile) + 3
                line = datafile.ljust(padding)

                for item in xmf_list:
                    line = line + str("%.5e" % item).ljust(14)
                f.writelines(line + "\n")

                #Makes the header print only once.
                counter += 1

    f.writelines("Non-ejecta: ")
    f.writelines("%s " % item for item in non_ejecta)

    #Tie up loose ends and close the file when finished.
    f.close()
Esempio n. 10
0
def massfractionvtime(datafile,
                      nuc_names_wanted='None',
                      ymin_max=[10e-10, 10e-3],
                      figurename='None',
                      time_spacing=10,
                      end='default'):
    '''
        Inputs: datafile = ts files, formatted as a list of strings
        nuc_names_wanted2 = list of desired species names from file, formatted as '$^{aa}$Symbol'
        ymin_max = y range of data to be plotted, formatted as a list
        figure_name = name of figure that plot is saved as, if "None", then plot is not saved
        time_spacing = desired interval between x-axis ticks, default to 10
        end = k value at end of desired time, default is number of timesteps of file with smallest number of timesteps
        
        Outputs: plot of mass fraction vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import read_ts_file as rtf

    #Create Figure
    plt.figure(1)

    #set up grid layout
    h_ratio = [3, 1]
    total_height = h_ratio[0] + h_ratio[1]
    gs = gridspec.GridSpec(total_height, 1)
    ax1 = plt.subplot(1, 1, 1)

    #Create list of file lengths to find xaxis maximum
    file_length_list = []

    #Loop through all files given in list of files
    for file in datafile:
        #Read ts file, use variables.
        zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
            file)
        print(file + ": File read.")

        #Build lis of elements
        element = rtf.build_element_symbol()
        nuc_name = rtf.build_isotope_symbol(zz, aa)
        num_species_total = np.shape(xmf)[1]
        file_length_list.append(len(time))

        #Loop through list of species to be plotted
        for counter in nuc_names_wanted:
            if counter not in nuc_name:
                counter += " "
            species_number = nuc_name.index(counter)
            species_number = int(species_number)
            #Plot Data
            if len(datafile) == 1:
                plt.plot(time,
                         xmf[:, species_number],
                         label=nuc_name[species_number])
            else:
                plt.plot(time,
                         xmf[:, species_number],
                         label=file + ": " + nuc_name[species_number])
            print(file + ": " + counter + ": Data assigned to plot.")

    #Format axes
    box = ax1.get_position()
    ax1.set_position([box.x0, box.y0, box.width * 0.995, box.height])

    #Create legend:
    ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=10)

    #Format and label axes
    plt.yscale('log')
    plt.ylim(ymin_max)
    plt.ylabel("Mass Fraction")

    if end == 'default':
        end = min(file_length_list) - 1
        print("end: " + str(end))

    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")
    print("Axes formatted.")

    #Add x ticks at specified intervals
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)
    print("Axes labeled.")

    #Remove superfluous ticks, show grid line instead
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)
    print("Grid line.")

    #Show graph
    if figurname == 'None':
        plt.show()
        print("Plot shown.")
    else:
        plt.savefig(figurename, bbox_inches="tight")
        print("plot saved.")
Esempio n. 11
0
def massfractionvtime2(datafile1,
                       datafile2,
                       end,
                       num_plots=1,
                       min_mf=.00000001,
                       time_spacing=.2,
                       h_ratio=[3, 1],
                       zz_wanted='None',
                       zz_wanted2='None',
                       aa_wanted='None',
                       nuc_names_wanted='None'):
    ''' Inputs: datafile = a ts file
        datafile2 = a second ts file to be plotted simultaneously
        end = k value at end of desired time
        num_plots = number of plots to be shown simultaneously, default to 1
        min_mf = cutoff point below which mass fraction does not appear on the graph, default to .00000001
        time_spacing = desired interval between x-axis ticks, default to .2
        h_ratio = height ratio (if plotting multiple plots), default to 3:1
        zz_wanted = list of atomic numbers of desired isotopes (if multiple isotopes of the same element are desired, their zz values must be added multiple times)
        zz_wanted2 = zz_wanted for the second datafile
        aa_wanted = list of atomic masses of desired isotopes (used in conjunction with zz_wanted)
        nuc_names_wanted = list of desired species names, formatted as '$^{aa}$Symbol' (best option when plotting specific isotopes)
        
        Outputs: plot of mass fraction vs time
        '''

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    import matplotlib.ticker as plticker
    import matplotlib.gridspec as gridspec
    import find_file_type as fft
    import read_ts_file as rtf
    import random

    #Create plot space
    plt.figure(1)

    #Read ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Create plot.
    ax1 = plt.subplot(1, 1, 1)

    #Set parameter based on data.
    num_species_total = np.shape(xmf)[1]

    #Assign each species a random color.
    colors_array = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors_array.append(item1)
        colors_array.append(item2)
        colors_array.append(item3)
    colors_array = np.asarray(colors_array)
    colors_array = colors_array.reshape((num_species_total, 3))

    colors = []
    for counter in np.arange(1, num_species_total + 1):
        item1 = np.random.rand(counter)[0]
        item2 = np.random.rand(counter)[0]
        item3 = np.random.rand(counter)[0]
        colors.append(item1)
        colors.append(item2)
        colors.append(item3)
    colors = np.asarray(colors)
    colors = colors.reshape((num_species_total, 3))

    #Plot mf, add a legend.
    for counter in np.arange(0, num_species_total):
        if zz_wanted != 'None':
            if zz[counter] in zz_wanted and aa_wanted == 'None':  #Plot all isotopes of an element.
                if zz[counter] == 1 and aa[
                        counter] == 1:  #Explicitly plots protons and hydrogen.
                    plt.plot(time,
                             xmf[:, counter],
                             color='r',
                             label=nuc_name[counter])
                elif zz[counter] == 1 and aa[counter] == 2:
                    plt.plot(time,
                             xmf[:, counter],
                             color='b',
                             label=nuc_name[counter])
                else:
                    plt.plot(time,
                             xmf[:, counter],
                             color=colors_array[counter],
                             label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
            elif zz[counter] in zz_wanted and aa[
                    counter] in aa_wanted:  #Plot by atomic number and mass number.
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         label=nuc_name[counter])
                box = ax1.get_position()
                ax1.set_position(
                    [box.x0, box.y0, box.width * 0.995, box.height])
                ax1.legend(loc='center left',
                           bbox_to_anchor=(1, 0.5),
                           fontsize=10)
                zz_wanted.remove(zz[counter])
        elif zz_wanted == 'None' and nuc_names_wanted == 'None':  #Plot all species above specified threshold.
            if np.amax(xmf[:, counter]) >= min_mf:
                plt.plot(time, xmf[:, counter], color=colors_array[counter])
        elif nuc_names_wanted != 'None':  #Listed nuclear names switches plotting mechanism.
            break

    if nuc_names_wanted != 'None':  #Sort through list to find mass fraction of named species, and plot.
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            species_number = int(species_number)
            plt.plot(time,
                     xmf[:, species_number],
                     color=colors_array[species_number],
                     label=nuc_name[species_number])
            box = ax1.get_position()
            ax1.set_position([box.x0, box.y0, box.width * 0.995, box.height])
            ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=10)

    #Start of datafile2.

    #Read second ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Set parameter based on data size.
    num_species_total = np.shape(xmf)[1]

    #Repeat plotting process above, using dashed lines and second set of provided information.
    for counter in np.arange(0, num_species_total):
        if zz_wanted2 != 'None':
            if zz[counter] in zz_wanted2 and aa_wanted == 'None':
                if zz[counter] == 1 and aa[counter] == 1:
                    plt.plot(time,
                             xmf[:, counter],
                             color='r',
                             label=nuc_name[counter],
                             linestyle='--')
                elif zz[counter] == 1 and aa[counter] == 2:
                    plt.plot(time,
                             xmf[:, counter],
                             color='b',
                             label=nuc_name[counter],
                             linestyle='--')
                else:
                    plt.plot(time,
                             xmf[:, counter],
                             color=colors_array[counter],
                             label=nuc_name[counter],
                             linestyle='--')
            elif zz[counter] in zz_wanted2 and aa[counter] in aa_wanted:
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         label=nuc_name[counter],
                         linestyle='--')
                zz_wanted2.remove(zz[counter])
                aa_wanted.remove(aa[counter])
        elif zz_wanted2 == 'None' and nuc_names_wanted == 'None':
            if np.amax(xmf[:, counter]) >= min_mf:
                plt.plot(time,
                         xmf[:, counter],
                         color=colors_array[counter],
                         linestyle='--')
        elif nuc_names_wanted != 'None':
            break

    if nuc_names_wanted != 'None':
        for counter in np.arange(0, len(nuc_names_wanted)):
            species_number = nuc_name.index(nuc_names_wanted[counter])
            plt.plot(time,
                     xmf[:, species_number],
                     color=colors_array[species_number],
                     label=nuc_name[species_number],
                     linestyle='--')

    #Format and label axes
    plt.yscale('log')
    plt.ylim(min_mf, 1.5)
    plt.ylabel("Mass Fraction")

    plt.xscale('linear')
    plt.xlim(time[0], time[end])
    plt.xlabel("Time (s)")

    #Add x ticks at specified intervals
    x_labels = []
    tick = time[0]

    while tick <= time[end]:
        tick = float("{0:.1f}".format(tick))
        x_labels.append(tick)
        tick += time_spacing

    loc = plticker.MultipleLocator(base=time_spacing)
    ax1.xaxis.set_major_locator(loc)
    plt.xticks(x_labels, x_labels)

    #Remove superfluous ticks, show grid line instead
    plt.tick_params(axis='both',
                    which='both',
                    bottom='on',
                    top='on',
                    labelbottom='on',
                    left='off',
                    right='off',
                    labelleft='on')
    plt.grid(True)
    plt.title("%s (solid) and %s (dashed)" % (datafile1, datafile2))

    #Show graph
    plt.show()
Esempio n. 12
0
def compare_final(datafile1, datafile2):
    '''A function to compare one datafile relative to another
    Inputs: datafile1 = ts file to be compared (reported errors are relative to this file)
            datafile2 = second ts file to be compared
    Output: rerr_sort = list of relative errors from smallest to largest
            names = list of nuclide names corresponding to items in rerr_sort
    '''

    import numpy as np
    import read_ts_file as rtf
    import heapq

    #Take in data from the first file, give it variable names.
    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = rtf.read_ts_file(
        datafile1)
    en1 = np.multiply(edot1, timestep1)
    enuc1 = np.cumsum(en1)

    #Set certain constraints based on the input data. (How many species, how many timesteps, etc)
    num_species_total = np.shape(xmf1)[1]
    num_timesteps = np.shape(xmf1)[0]

    #Take in data from the second file.
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = rtf.read_ts_file(
        datafile2)
    en2 = np.multiply(edot2, timestep2)
    enuc2 = np.cumsum(en2)

    #Make lists of elements and nuclear names for later use.
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz2, aa2)

    #Set certain constraints based on the new set of input data.
    num_species_total2 = np.shape(xmf2)[1]

    #Create lists for the differences
    aerr = np.abs(np.subtract(xmf2[-1][:], xmf1[-1][:]))
    rerr = np.divide(aerr, np.abs(xmf1[-1][:]))

    isort = np.argsort(rerr)
    aerr_sort = aerr[isort]
    rerr_sort = rerr[isort]
    xmf1_sort = xmf1[-1][isort]
    xmf2_sort = xmf2[-1][isort]
    name_sort = [nuc_name[i] for i in isort]

    print("%5s %5s\t%10s\t%16s\t%16s\t%16s\t%16s" %
          ('i', 'isort', 'name', 'X1', 'X2', '|dX|', '|dX| / |X1|'))

    fmt = "%5s %5s\t%10s\t%16.8e\t%16.8e\t%16.8e\t%16.8e"
    for i in np.arange(0, num_species_total):
        print(fmt % (i + 1, isort[i] + 1, name_sort[i], xmf1_sort[i],
                     xmf2_sort[i], aerr_sort[i], rerr_sort[i]))

    print("")

    fmt = "%5s %5s\t%10s\t%16s\t%16s\t%16.8e\t%16.8e"
    aerr_norm = np.linalg.norm(aerr, ord=2)
    rerr_norm = np.divide(aerr_norm, np.linalg.norm(xmf1[-1][:], ord=2))
    print(fmt % ('', '', '2-norm', '', '', aerr_norm, rerr_norm))

    fmt = "%5s %5s\t%10s\t%16.8e\t%16.8e\t%16.8e\t%16.8e"
    aerr = np.abs(np.subtract(temperature2[-1], temperature1[-1]))
    rerr = np.divide(aerr, np.abs(temperature1[-1]))
    print(fmt % ('', '', 'T', temperature1[-1], temperature2[-1], aerr, rerr))

    aerr = np.abs(np.subtract(enuc2[-1], enuc1[-1]))
    rerr = np.divide(aerr, np.abs(enuc1[-1]))
    print(fmt % ('', '', 'E_nuc', enuc1[-1], enuc2[-1], aerr, rerr))
Esempio n. 13
0
def per_diff(datafile1, datafile2):
    '''A function to find final percent difference between two data sets of mass fraction.
    Inputs: datafile1 = ts file to be compared
            datafile2 = second ts file to be compared
    Output: smallest = list of differences from smallest to largest
            names = list of nuclide names corresponding to items in largest
    '''

    import numpy as np
    import read_ts_file as rtf
    import heapq

    #Take in data from the first file, give it variable names.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)

    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Set certain constraints based on the input data. (How many species, how many timesteps, etc)
    num_species_total = np.shape(xmf1)[1]
    num_timesteps = np.shape(xmf1)[0]
    n = num_species_total

    #Take in data from the second file.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)

    #Make lists of elements and nuclear names for later use.
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Change variable names.
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Set certain constraints based on the new set of input data.
    num_species_total2 = np.shape(xmf2)[1]
    num_timesteps2 = np.shape(xmf2)[0]

    #Create an empty list for the maximum percentage differences.
    max_per_diff = []

    for counter in np.arange(
            0, num_species_total):  #count through each column (species)
        avg = (
            float((xmf1[-1][counter]) + float(xmf2[-1][counter])) / 2
        )  #take the average of each item, -1 as an index accesses the last entry, so it's end time
        if avg == 0.0:  #if average is zero, make it something calculable
            avg = 10E-20
        diff_list = []  #make empty list for differences
        diff = float(xmf1[-1][counter]) - float(
            xmf2[-1][counter])  #calculate differences and add to list
        diff = abs(diff)
        diff_list.append(diff)
        per_diff_list = []  #create list of percent differences
        for item in diff_list:  #calculate percent differences, add to list
            per_diff = item / avg
            per_diff_list.append(per_diff)
            max_per_diff.append(
                max(per_diff_list
                    ))  #find largest percentage differences and add to list

    smallest = heapq.nsmallest(
        n, max_per_diff
    )  #make list of smallest percentage differences (remember that n = num_species_total, so this is a list of all perdiffs in ascending order)
    names = []  #make empty list of names
    for item in smallest:  #assign relevant name to each percentage difference
        foo = max_per_diff.index(item)
        name = nuc_name[foo]
        names.append(name)

    for counter in np.arange(0, n):
        print("%s     %s     %s" %
              (counter + 1, names[counter], smallest[counter]))
Esempio n. 14
0
def find_max_difference(datafile1, datafile2):
    '''A function to find absolute differences between mass fraction in two datafiles.
       
       Inputs: datafile1 = ts file to be compared
               datafile2 = second ts file to be compared
       Output: largest = list of n largest differences
               names = list of nuclide names corresponding to items in largest
               times = list of times corresponding to items in largest (list of times where largest difference occurs
        '''

    import numpy as np
    import read_ts_file as rtf
    import plot_time_mf_2files as plt2
    import heapq

    #Read data file, change variable names.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile1)

    zz1, aa1, xmf1, time1, temperature1, density1, timestep1, edot1, flx_end1, flx1 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Set certain constraints based on the size and shape of the mass fraction array.
    num_species_total = np.shape(xmf1)[1]
    num_timesteps = np.shape(xmf1)[0]
    n = num_species_total

    #Read the second data file.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile2)

    #Make lists of elements and nuclear names for later use.
    element = rtf.build_element_symbol()
    nuc_name = rtf.build_isotope_symbol(zz, aa)

    #Change variable names.
    zz2, aa2, xmf2, time2, temperature2, density2, timestep2, edot2, flx_end2, flx2 = zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx

    #Make empty list for maximum differences.
    max_diff = []
    for counter in np.arange(
            0, num_species_total):  #Count through number of species.
        for counter2 in np.arange(
                0, num_timesteps):  #Count through number of timesteps.
            diff_list = []  #Make empty list for differences.
            diff = float(xmf1[counter2][counter]) - float(
                xmf2[counter2][counter])  #Find differences, add to list
            diff = abs(diff)
            diff_list.append(diff)
        max_diff.append(
            max(diff_list))  #Add largest difference to max_diff list

    largest = heapq.nlargest(
        n, max_diff
    )  #Make list of all maximum differences, from smallest to largest. (max_diff but sorted)
    names = []  #Make empty list for names to fill into
    times = []  #Make empty list for times to fill into
    for item in largest:  #Assign relevant name and time to each difference.
        foo = max_diff.index(item)
        name = nuc_name[foo]
        times.append(time[foo])
        names.append(name)

    #Print results.
    for counter in np.arange(0, n):
        print("%s     %s     %s     %s" %
              (counter + 1, names[counter], largest[counter], times[counter]))
Esempio n. 15
0
def write_final_abundances(directory_files, file_name="abundances.txt"):
    '''
        Inputs: directory_files: the full String pathway to the desired files
                file_name = String that names the file created or designates which file to append data to
        Output: a new file, "file_name", or an expanded file, with final abundance data for each species
        '''
    import numpy as np
    import read_ts_file as rtf
    import glob as g

    #Open a new file, or open a previous one to add to.
    f = open(file_name, "w")

    #Initialize a counter to make the header print only once.
    counter = 1

    #Create a list of all desired files in the given directory.
    files = g.glob(directory_files)
    number_of_files = len(files)

    non_ejecta = []

    print_counter = 1
    counter = 0

    for datafile in files:

        print(datafile)
        print("%s" % print_counter)

        #Read data file, use variable names.
        zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
            datafile, last=True)
        nuc_name = rtf.build_isotope_symbol(zz, aa)

        #Set certain parameters based on the size of the data.
        num_species_total = np.shape(xmf)[1]
        timesteps_total = np.shape(xmf)[0]

        #Write header with species names only as a first line.
        if counter == 0:
            f.writelines("%s " % item for item in nuc_name)
            f.writelines("\n")
            counter += 1

            #Create list for mass fractions.
            xmf_list = []

            #If time ends early, stop everything.
            for count in np.arange(0, num_species_total):
                foo = xmf[-1][count]
                if time[-1] <= 100:
                    non_ejecta.append(datafile)
                    print len(time)
                    break
                else:  #Otherwise, add to list.
                    xmf_list.append(foo)

    #If it isn't the first line, check time and add to xmf_list.
        else:
            xmf_list = []
            for count in np.arange(0, num_species_total):
                foo = xmf[-1][count]
                if time[-1] <= 100:
                    non_ejecta.append(datafile)
                    break
                else:
                    xmf_list.append(foo)

            #Write datafile name, each final abundance from xmf_list, and go to a new line at the end of the file.
            if datafile in non_ejecta:
                f.writelines("\n")
            else:
                f.writelines("%s " % datafile)
                f.writelines("%s " % item for item in xmf_list)
                f.writelines("\n")

        print_counter += 1

    #Write to file.
    f.writelines("Non-ejecta: ")
    f.writelines("%s " % item for item in non_ejecta)
    f.writelines("\n %s species" % len(non_ejecta))

    #Tie up loose ends and close the file when finished.
    f.close()