Ejemplo n.º 1
0
def plot_color_circle(colors, ret=False, input_space='hsv', **kwargs):
    """
    Draws a color circle from provided colors ordered by color hue.
    Colors align from 0 degree red and are then added to form a circle.
    Therefore the plotted angle doesn't correspond to hue angle!
    
    Parameters:
    -----------
    colors: numpy array (...[,...],3) in either hsv or rgb color model.
    
    ax: axis to plot on
    
    input_space: valid values: 'hsv' or 'rgb'
    
    """
    color_df = pd.DataFrame(colors.reshape(-1, 3))
    color_df = color_df.drop_duplicates()
    colors = color_df.as_matrix().reshape(1, -1, 3)
    uniq = colors.copy()

    if colors.dtype == 'uint8':
        colors = util.img_as_float(colors)
    if input_space == 'rgb':
        colors = skimage_color.rgb2hsv(colors).reshape(-1, 3)
    else:
        colors = colors.reshape(-1, 3)

    color_df = pd.DataFrame(colors)
    color_df = color_df.sort_values(0)
    colors = color_df.as_matrix()
    color_list = skimage_color.hsv2rgb(colors.reshape(1, -1,
                                                      3)).reshape(-1,
                                                                  3).tolist()

    if 'ax' in kwargs:
        angle = 360 / len(color_list)

        for idx, color in enumerate(color_list):
            w = Wedge((0.5, 0.5),
                      0.5, (idx + 0.5) * angle, (idx + 1.5) * angle,
                      width=0.250,
                      linewidth=0,
                      color=color_list[idx])
            kwargs['ax'].add_patch(w)

        kwargs['ax'].set_axis_off()

    if ret:
        return color_list
Ejemplo n.º 2
0
def run_net(net, size_x=128, size_y=128):
    x = np.arange(0, size_x, 1)
    y = np.arange(0, size_y, 1)
    colors = np.zeros((size_x, size_y, 2))
    for i in x:
        for j in y:
            colors[i][j] = np.array(
                [float(i) / size_y - 0.5,
                 float(j) / size_x - 0.5])
    colors = colors.reshape(size_x * size_y, 2)
    img = net(torch.tensor(colors).type(torch.FloatTensor)).detach().numpy()
    return img.reshape(size_x, size_y, 3)
Ejemplo n.º 3
0
def plot_triangle_normals(normals: np.ndarray, normals2: np.ndarray):
    f, (ax1, ax2) = plt.subplots(1, 2)
    colors = ((normals * 0.5 + 0.5) * 255).astype(np.uint8)
    im = colors.reshape((249, 249, 2, 3))
    im = im[:, :, 1, :]

    colors2 = ((normals2 * 0.5 + 0.5) * 255).astype(np.uint8)
    im2 = colors2.reshape((249, 249, 2, 3))
    im2 = im2[:, :, 1, :]

    ax1.imshow(im, origin='upper')
    ax2.imshow(im2, origin='upper')
    plt.show()
Ejemplo 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()
Ejemplo n.º 5
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()