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]))
Esempio n. 3
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. 4
0
def draw_nz_mf(datafile,
               k,
               num_species,
               colors,
               flux,
               x_limit=40.0,
               y_limit=40.0,
               z_max=30,
               figurename='None'):
    '''
        1. Scatter plot color coded by mass fractions at a specified timestep.
        2. Draw vectors for the reaction flux on the NZ plane from reaction target
           to product colored by relative flux intensity.
        Inputs: datafile = must be a ts file
                k = desired time for thermodynamic and mass fraction data
                num_species = number of plotted species desired
                colors = turns colorbar on or off (mass fraction coloring)
                flux = if True, shows flux of nuclear reactions
                x_limit = maximum of xaxis (neutron number)
                y_limit = maximum of yaxis (proton number)
                z_max = atomic number of heaviest element to plot
                figurename = name of figure to be saved; if "None", the plot is not saved
        Outputs: scatterplot of number of neutrons vs number of protons, color coded for mass fraction
                 thermodynamic data at specific time, optionally shows flux of nuclear reactions, color coded

    '''
    import read_ts_file as rtf
    import numpy as numpy
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import matplotlib.ticker as plticker
    import matplotlib.colors

    #-------------------------------------------------------------------------------
    #   MASS FRACTION SCATTERPLOT

    #Create plot space.
    fig = plt.figure(1)

    #Read ts file and use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile)
    print('Data read')

    #Plot all species if 'all' is chosen
    num_species_total = numpy.shape(xmf)[1]
    if num_species == 'all':
        num_species = num_species_total

    #Create lists of variable to be plotted
    zz_plot = []
    nn_plot = []
    xmf_plot = []

    #Fill in lists with data from file
    for counter in numpy.arange(0, num_species):
        #If mass fraction is 0, skip data point, as colors.LogNorm requires values > 0
        if xmf[k, counter] > 0:
            zz_plot.append(zz[counter])
            nn_plot.append(aa[counter] - zz[counter])
            xmf_plot.append(xmf[k, counter])

    #Plot proton number vs neutron number and color code for mass fraction (log).
    if colors == True:
        s = plt.scatter(nn_plot,
                        zz_plot,
                        c=xmf_plot,
                        norm=matplotlib.colors.LogNorm(vmin=min(xmf_plot),
                                                       vmax=max(xmf_plot)),
                        cmap='YlOrBr',
                        marker='s')

    else:
        s = plt.scatter(nn_plot, zz_plot, s=5, c='w')
    print('Mass fraction plotted')

    #Make nn back to an array
    nn = aa - zz

    #Plot colorbar as legend.
    if colors == True:
        cb = plt.colorbar(s)
        cb.set_label('Log of Mass Fraction')

    #Print thermodynamic data.
    x_loc = 5
    y_loc = 37
    words = ('Time = %s sec') % time[k]
    plt.text(x_loc, y_loc, words)
    words = ('Temperature = %s GK') % temperature[k]
    plt.text(x_loc, y_loc - 2, words)
    words = (r'$\rho =$ %s g/$\mathregular{cm^3}$') % density[k]
    plt.text(x_loc, y_loc - 4, words)
    words = ('Timestep = %s') % k
    plt.text(x_loc, y_loc - 6, words)
    print('Thermodynamic data added')

    #Format x and y axes.
    plt.ylim(-1, y_limit)
    plt.ylabel('Z (Proton Number)')

    plt.xlim(-2, x_limit)
    plt.xlabel('N (Neutron Number)')

    #Set axis ticks
    special_elements = [2, 8, 15, 28]
    loc = plticker.FixedLocator(special_elements)
    plt.xticks(special_elements, special_elements)
    plt.yticks(special_elements, special_elements)
    print('Axes formatted')

    #Label elements and mass numbers
    z_min = min(zz)
    n_max = max(nn)
    n_min = min(nn)
    leftn = numpy.empty([
        0,
    ])
    rightn = numpy.empty([
        0,
    ])
    alabel = numpy.empty([
        0,
    ])

    #Loop over all elements, including neutrons (z=0)
    z_max = int(z_max) + 1  #33
    for i in range(z_max):  #[0,1,2,...,31,32]
        zint = numpy.arange(z_max)  #[0 1 2 ... 31 32]
        zint[i] = i
        iz = numpy.where(zz == i)[0]

        #Find the lightest and heaviest isotope
        if not iz.size == 0:
            # returns True if the condition is considered False
            # if proton no. array is not empty
            nn = nn.astype(int)
            leftn = numpy.append(leftn, min(nn[iz]))
            leftn = leftn.astype(int)
            rightn = numpy.append(rightn, max(nn[iz]))
            rightn = rightn.astype(int)
            alabel = numpy.append(alabel, rightn[i] + zint[i])
            alabel = alabel.astype(int)
            # max neutron no. + i in range(z_max)

    #Load element names
    element = rtf.build_element_symbol()
    element = numpy.asarray(element, dtype=object)

    for i in range(0, 113):
        if i in zint:
            #Label elements to the left
            plt.text(leftn[i] - 1.25,
                     zint[i],
                     element[i],
                     fontsize=4,
                     horizontalalignment='left')

            #Label mass numbers to the right
            plt.text(rightn[i] + 1.25,
                     zint[i] - 1.25,
                     alabel[i],
                     fontsize=4,
                     horizontalalignment='right',
                     rotation=-45)
    print('Species labels added')

    #-------------------------------------------------------------------------------
    #   FLUX VECTORS

    if flux == True:
        #Identify starting and ending points for all fluxes
        zt = zz[flx_end[:, 0] - 1]
        zp = zz[flx_end[:, 1] - 1]
        nt = nn[flx_end[:, 0] - 1]
        np = nn[flx_end[:, 1] - 1]

        #Choose cycle(timestep) to plot
        flx_write = flx[k, :]

        #Choose maximum flux for calculating bin ranges
        flx_max = max(abs(flx_write))

        #Calculate vector origin and lengths
        aflx = abs(flx_write)
        zo = zt  # vector origin
        no = nt  # vector origin
        zv = zp - zt  # vector length (z-component)
        nv = np - nt  # vector length (n-component)

        #Reverse arrows for negative flux
        ineg = numpy.where(flx_write < 0.0)[0]
        zo[ineg] = zp[ineg]
        no[ineg] = np[ineg]
        zv[ineg] = -zv[ineg]
        nv[ineg] = -nv[ineg]

        #set number of colors/levels
        color_bins = numpy.array([1e-1, 1e-2, 1e-3])

        #set number of arrays
        colors = numpy.array(['k', 'r', 'g', 'b', 'c'])
        ncolors = len(color_bins)
        bin_upper = numpy.array([1])
        bin_upper = numpy.append(bin_upper, color_bins[0:4])
        bin_lower = color_bins

        #Build Legend array
        legend_array = numpy.array(range(ncolors), dtype=object)

        #Reverse ncolors so that for loop runs through color_bins backwards
        ncolors = range(ncolors)
        #rev_ncolors = ncolors.reverse()
        ncolors = numpy.asarray(ncolors)
        # ultimately, heavier flux vectors will be plotted on top because
        # they are calculated later than lighter fluxes

        #Loop over colors
        for i in ncolors:

            #Plot Vectors
            flx_top = flx_max * bin_upper[i]  #scalar multiplication
            flx_bot = flx_max * bin_lower[i]
            ii = numpy.where((aflx <= flx_top) & (aflx > flx_bot))[0]
            scale = 0.0  #prevents autoscaling
            if i == 0:
                lwidth = 0.002
            elif i == 1:
                lwidth = 0.0015
            else:
                lwidth = 0.001

            #Assemble handles of legend
            bin_lower[i] = str(bin_lower[i])
            label = [' > ', '{:.1e}'.format(bin_lower[i]),
                     ' of max']  #prints bin_lower[i] in scientific notation
            label = ''.join(
                map(str, label)
            )  #joins string elements of a sequence(i.e. label is a list)
            legend_array[i] = label

            #Draw vectors
            h = fig.add_subplot(111)
            h.quiver(no[ii],
                     zo[ii],
                     nv[ii],
                     zv[ii],
                     width=lwidth,
                     color=colors[i],
                     angles='xy',
                     scale_units='xy',
                     scale=1,
                     label=legend_array[i])
            plt.grid()
            plt.draw()

        print('Flux plotted')

        #Plot legend
        plt.legend(loc=4, title='Reaction Fluxes')
        # automatically pulls in label from quiver plot
        # and label=legend_array[i]

#-------------------------------------------------------------------------------
#   FINALIZE PLOT

#Add grid lines.
    plt.grid(True)

    #Add title.
    plt.title(datafile)

    #Show plot.
    if figurename == 'None':
        plt.show()
        print('Plot shown')
    else:
        plt.savefig(figurename, bbox_inches="tight")
        print('Plot saved')
Esempio n. 5
0
    plt.text(x_loc, y_loc - 1.5, words) #Writes temperature just below time.
    words = (r'$\rho =$ %s g/$\mathregular{cm^3}$') % density[k] #Generates the density at the specified timestep
    plt.text(x_loc, y_loc - 3.75, words) #Writes density just before temperature
    
    #Format x and y axes.
    plt.ylim(-1, 40) #Y axis will range from -1 to 40, and so will the x axis. They're labeled accordingly.
    plt.ylabel('Z (Proton Number)')
    plt.xlim(-2, 40)
    plt.xlabel('N (Neutron Number)')

    #Set axis ticks.
    special_elements = [2, 8, 20, 28] #List of values where I want ticks
    loc = plticker.FixedLocator(special_elements) #Says that I want fixed, specified locations for the ticks
    plt.xticks(special_elements, special_elements) #Labels axes with the numerical values of the ticks at those positions (prints each item in the list at the value of that item)
    plt.yticks(special_elements, special_elements)

    #Add labels for each element.
    element = rtf.build_element_symbol() #build_element_symbol returns a list of each element name, which you're using here
    for item in range(0, 118): #counts through all elements, and if their proton numbers are in the list of proton numbers plotted, their name appears along the y axis.
        if item in zz:
            plt.text(-1.5, item - .25, element[item], fontsize = 7)

    #Add grid lines,
    plt.grid(True)

    #Add title, just the name of the datafile input.
    plt.title(datafile)

    #Show plot, which makes the plot appear.
    plt.show()
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 draw_nz_mf(datafile, datafile2, k, num_species, colors=False):
    '''
        Colorbar is currently not working. 
        Inputs: datafile = must be a ts file
                datafile2 = second datafile
                k = desired timestep for thermodynamic and mass fraction data
                num_species = number of plotted species desired
                colors = turn colorbar on or off, defaults to False
        Outputs: scatterplot of number of neutrons vs number of protons, color coded for mass fraction
                 thermodynamic data at specific time
    '''
    import read_ts_file as rtf
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import matplotlib.ticker as plticker
    import matplotlib.colors

    fig = plt.figure(1)

    #Read ts file, use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile)

    #For each species, determine neutron number by subtracting proton number from mass number, and plot neutron number by proton number. Apply a colormap, and normalize the data on a log scale.
    ax1 = plt.subplot2grid((1, 2), (0, 0))
    for counter in np.arange(0, num_species):
        nn = aa[counter] - zz[counter]
        nn = int(round(nn))
        if colors:
            s = ax1.scatter(nn,
                            zz[counter],
                            s=60,
                            c=xmf[k, counter],
                            cmap='YlGnBu_r',
                            norm=matplotlib.colors.LogNorm(vmin=xmf[k].min(),
                                                           vmax=xmf[k].max()),
                            marker='s')
        else:
            s = ax1.scatter(nn, zz[counter], s=60, marker='s')

    #Configure and label axes, placing ticks at helium, oxygen, calcium, and nickel.
    plt.ylim(-1, 40)
    plt.ylabel('Z (Proton Number)')
    plt.xlim(-2, 40)
    plt.xlabel('N (Neutron Number)')

    special_elements = [2, 8, 20, 28]
    loc = plticker.FixedLocator(special_elements)
    plt.xticks(special_elements, special_elements)
    plt.yticks(special_elements, special_elements)

    #Add labels for each element.
    element = rtf.build_element_symbol()
    for item in range(0, 113):
        if item in zz:
            plt.text(-1.5, item - .25, element[item], fontsize=7)

    #Set up grid structure for adding second plot.
    plt.grid(True)

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

    #Repeat plotting process from above, with data from the second ts file.
    ax2 = plt.subplot2grid((1, 2),
                           (0, 1))  #positions the second plot on the grid
    for counter in np.arange(0, num_species):
        nn = aa[counter] - zz[counter]
        nn = int(round(nn))
        if colors:
            s = ax2.scatter(nn,
                            zz[counter],
                            s=60,
                            c=xmf[k, counter],
                            cmap='YlGnBu_r',
                            norm=matplotlib.colors.LogNorm(vmin=xmf[k].min(),
                                                           vmax=xmf[k].max()),
                            marker='s')
        else:
            s = ax2.scatter(nn, zz[counter], s=60, marker='s')

    #Set space between the two plots.
    fig.subplots_adjust(wspace=0.1)

    #Print thermodynamic data.
    words = ('Time = %s sec') % time[k]
    x_loc = 5
    y_loc = 37
    plt.text(x_loc, y_loc, words)
    words = ('Temperature = %s GK') % temperature[k]
    plt.text(x_loc, y_loc - 1.5, words)
    words = (r'$\rho =$ %s g/$\mathregular{cm^3}$') % density[k]
    plt.text(x_loc, y_loc - 3.75, words)

    #Configure and label axes, placing ticks at helium, oxygen, calcium, and nickel.
    plt.ylim(-1, 40)
    plt.xlim(-2, 40)

    special_elements = [2, 8, 20, 28]
    loc = plticker.FixedLocator(special_elements)
    plt.xticks(special_elements, special_elements)
    plt.yticks(special_elements, special_elements)

    #Add labels for each element.
    element = rtf.build_element_symbol()
    for item in range(0, 113):
        if item in zz:
            plt.text(-1.5, item - .25, element[item], fontsize=7)

    plt.grid(True)

    #Show colorbar as legend.
    if colors:
        cb = plt.colorbar(s)
        cb.set_label('Log of Mass Fraction')

    plt.show()
Esempio n. 8
0
def draw_nz_mf(datafile, k, num_species, colors=False):
    '''
        Colorbar is currently not working.
        Inputs: datafile = must be a ts file, formatted as 'datafile'
                k = desired timestep for thermodynamic and mass fraction data
                num_species = number of plotted species desired
                colors = turns colorbar on or off, defaults to False
        Outputs: scatterplot of number of neutrons vs number of protons, color coded for mass fraction
                 thermodynamic data at specific time
    '''
    import read_ts_file as rtf  #module to read ts file
    import numpy as np  #module to provide calculation support
    import matplotlib.pyplot as plt  #plotting module
    import matplotlib.cm as cm  #colormap module
    import matplotlib.ticker as plticker  #module to make and assign tick marks on axes
    import matplotlib.colors  #colors module

    #Create plot space.
    fig = plt.figure(1)

    #Read ts file and use variables.
    zz, aa, xmf, time, temperature, density, timestep, edot, flx_end, flx = rtf.read_ts_file(
        datafile
    )  #Each of these variables is returned by the function read_ts_file in the module rtf, so you just assign them to the same names here

    #Plot proton number vs neutron number and color code for mass fraction (log).
    for counter in np.arange(
            0, num_species
    ):  #generates a counter that goes from 0 to the number of species
        nn = aa[counter] - zz[
            counter]  #Determine number of neutrons for each species. aa is atomic weight, and zz is proton number.
        nn = int(
            round(nn)
        )  #Round the number of neutrons, and cast it to an integer so that it can be used for plotting
        #If colors has been set as true, plot a scatterplot of nn vs zz.
        #the first two terms are the x and y of your plot
        #nn = neutron number
        #zz[counter] = proton number, counted through for every species
        #s = a size determiner, not all that important
        #marker = lets you choose the point shape, 's' means square. It should default to round.
        #c = sets color. Here, I have it do a gradient based on mass fraction.
        #cmap = lets you choose colormap (there's a list of them on the matplotlib website)
        #norm = normalizes the data to fit between 0 and 1, here I use a log scale with largest and smallest mass fractions at timestep as parameters
        if colors == True:
            s = plt.scatter(nn,
                            zz[counter],
                            s=50,
                            c=xmf[k, counter],
                            cmap='YlOrBr',
                            norm=matplotlib.colors.LogNorm(vmin=xmf[k].min(),
                                                           vmax=xmf[k].max()),
                            marker='s')
        else:
            s = plt.scatter(nn, zz[counter], s=50, marker='s')

    if colors == True:
        cb = plt.colorbar(s)  #Plot colorbar as legend.
        cb.set_label('Log of Mass Fraction')

    #Print thermodynamic data.
    words = ('Time = %s sec'
             ) % time[k]  #Generates the time at the specified timestep
    x_loc = 5  #Arbitrary x and y coordinates
    y_loc = 37
    plt.text(x_loc, y_loc, words)  #Writes the time at specified x and y.
    words = ('Temperature = %s GK') % temperature[
        k]  #Generates the temperature at the specified timestep
    plt.text(x_loc, y_loc - 1.5, words)  #Writes temperature just below time.
    words = (r'$\rho =$ %s g/$\mathregular{cm^3}$'
             ) % density[k]  #Generates the density at the specified timestep
    plt.text(x_loc, y_loc - 3.75,
             words)  #Writes density just before temperature

    #Format x and y axes.
    plt.ylim(
        -1, 40
    )  #Y axis will range from -1 to 40, and so will the x axis. They're labeled accordingly.
    plt.ylabel('Z (Proton Number)')
    plt.xlim(-2, 40)
    plt.xlabel('N (Neutron Number)')

    #Set axis ticks.
    special_elements = [2, 8, 20, 28]  #List of values where I want ticks
    loc = plticker.FixedLocator(
        special_elements
    )  #Says that I want fixed, specified locations for the ticks
    plt.xticks(
        special_elements, special_elements
    )  #Labels axes with the numerical values of the ticks at those positions (prints each item in the list at the value of that item)
    plt.yticks(special_elements, special_elements)

    #Add labels for each element.
    element = rtf.build_element_symbol(
    )  #build_element_symbol returns a list of each element name, which you're using here
    for item in range(
            0, 118
    ):  #counts through all elements, and if their proton numbers are in the list of proton numbers plotted, their name appears along the y axis.
        if item in zz:
            plt.text(-1.5, item - .25, element[item], fontsize=7)

    #Add grid lines,
    plt.grid(True)

    #Add title, just the name of the datafile input.
    plt.title(datafile)

    #Show plot, which makes the plot appear.
    plt.show()
Esempio n. 9
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. 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]))