Esempio n. 1
0
def color_by_data(data):
    norm = matplotlib.colors.Normalize(vmin=data.min, vmax=data.max)
    colors = []
    for i, d in enumerate(data.vals):
        rgb = [x for x in data.palette(norm(d))[0:3]]
        colors.append(rgb)
    return colors
def smart_colormap(clevs, name='jet', extend='both', minval=0.0, maxval=1.0):
    '''
    Automatically grabs the colors to extend the colorbar from the colormap.
    '''
    
    # Define number of colors
    if extend == 'both':
        nrColors = len(clevs)+1
    elif (extend == 'min') | (extend == 'max'):
        nrColors = len(clevs)
    elif (extend == 'neither'):
        nrColors = len(clevs)-1
    else:
        nrColors = len(clevs)-1
        extend = 'neither'
    
    # Get colormap
    cmap = get_cmap(name, nrColors)
    
    # Truncate colormap if asked
    if (minval != 0.0) or (maxval != 1.0):
        cmap = truncate_colormap(cmap, minval=minval, maxval=maxval, n=nrColors/2)
    
    # Get the list of colors
    colors = []
    for i in range(0, nrColors):
        colors.append(cmap(i/(nrColors-1)))
    
    # Use utility function to get cmap and norm at the same time
    cmap, norm = from_levels_and_colors(clevs, colors, extend=extend)

    return(cmap, norm)
Esempio n. 3
0
def get_colormap_reds_blues(n):
    n = n // 2
    reds = ['#ffebc0', '#f84627', '#950026']
    blues = ['#0a2a6a', '#437aea', '#c8d9fd']
    colors = blues[:n]
    colors.append(reds[:n])
    return colors
Esempio n. 4
0
def pie_plot_percent_mentions(mentions_percent, save_to = None):
    '''
    Inputs:
        Dictionary with keys as pairs, values as percent of mentions
    '''

    other = mentions_percent.pop("Other")
    swapped = {v:k for k, v in mentions_percent.items()}

    sizes = sorted(swapped)
    sizes.reverse()
    labels = [swapped[current_percent] for current_percent in sizes]

    sizes.append(other)
    labels.append("Other")
    N = len(labels)

    color_map = get_colormap(N-1)
    colors = []
    for i in range(N-1):
        col = color_map(i)
        colors.append(col)
    colors.append("white")
    print(colors)

    plt.pie(sizes, labels=labels, colors=colors,
        autopct='%1.1f%%', startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')

    fig = plt.figure()
    ax = fig.gca()

    plt.show()
Esempio n. 5
0
    def update_data(self, change=None):
        ylist = []
        colors = []
        selection_was_list, [selections
                             ] = vaex.utils.listify(self.model.selection)
        if self.dimension_groups == 'slice':
            y0 = self.model.grid
            if selection_was_list:
                y0 = y0[0]
            ylist.append(y0)
            colors.append(C0)
            if self.model.grid_sliced is not None:
                y1 = self.model.grid_sliced
                if selection_was_list:
                    y1 = y1[0]
                ylist.append(y1)
                colors.append(C1)
        elif self.dimension_groups == 'selections':
            ylist = self.model.grid
            if selection_was_list:
                colors = colors_default[:len(ylist)]
            else:
                colors = [colors_default[0]]
        else:
            raise ValueError(
                f'Unknown action {self.dimension_groups} for dimension_groups')

        if self.normalize:
            ylist = [y / np.sum(y) for y in ylist]
        x = self.model.x.bin_centers
        self.plot.x_min = self.model.x.min
        self.plot.x_max = self.model.x.max
        self.plot.update_data(x, np.array(ylist), colors)
def smart_colormap(clevs, name='jet', extend='both', minval=0.0, maxval=1.0):
    '''
    Automatically grabs the colors to extend the colorbar from the colormap.
    '''

    # Define number of colors
    if extend == 'both':
        nrColors = len(clevs) + 1
    elif (extend == 'min') | (extend == 'max'):
        nrColors = len(clevs)
    elif (extend == 'neither'):
        nrColors = len(clevs) - 1
    else:
        nrColors = len(clevs) - 1
        extend = 'neither'

    # Get colormap
    cmap = get_cmap(name, nrColors)

    # Truncate colormap if asked
    if (minval != 0.0) or (maxval != 1.0):
        cmap = truncate_colormap(cmap,
                                 minval=minval,
                                 maxval=maxval,
                                 n=nrColors / 2)

    # Get the list of colors
    colors = []
    for i in range(0, nrColors):
        colors.append(cmap(i / (nrColors - 1)))

    # Use utility function to get cmap and norm at the same time
    cmap, norm = from_levels_and_colors(clevs, colors, extend=extend)

    return (cmap, norm)
    def _highlight_allen_ids(self, allen_ids):
        weights = np.ones(
            (len(self.labels), ), dtype=np.float32) * self.off_weight
        # Background
        weights[0] = 0.0
        for allen_id in allen_ids:
            labels_for_id = labels_for_allen_id(allen_id)
            weights[labels_for_id] = self.on_weight

        if not allen_ids:
            return

        surfaces = [structure_mesh(allen_id) for allen_id in allen_ids]
        self.itk_viewer.geometries = self.swc_geometries + surfaces
        self.itk_viewer.geometry_opacities = [1.0,]*len(self.swc_geometries) + \
            [0.5,]*len(surfaces)
        colors = list(
            self.itk_viewer.geometry_colors)[:len(self.swc_geometries)]
        for allen_id in allen_ids:
            hex_color = '#' + allen_id_to_tree_node[allen_id].color_hex_triplet
            colors.append(matplotlib.colors.to_rgb(hex_color))
        self.itk_viewer.geometry_colors = np.array(colors, dtype=np.float32)

        self.itk_viewer.label_image_weights = weights

        self.itk_viewer.ui_collapsed = True
def plot_peak_mobility_gate_voltage(analyzed_data, position="any"):
    """
    This function plots the gate voltage at which peak mobility is achieved.
    """
    exclude_ids = ()
    c = {(None, 'H2O'): 'tab:red', ('tma', 'H2O'): 'tab:orange', ('tma', 'O3'): 'tab:olive', ('plasma', 'H2O'): 'tab:blue', ('plasma', 'O3'): 'tab:green'}
    m = {(None, 'H2O'): 'x', ('tma', 'H2O'): '^', ('tma', 'O3'): 'v', ('plasma', 'H2O'): 'd', ('plasma', 'O3'): 'o'}
    # Extract a list of peak mobilities and voltages
    colors = []
    markers = []
    voltages = []
    mobilities = []
    for sid, sample in analyzed_data.items():
        if sid in exclude_ids:
            continue
        if position != "any":
            if sample.position != position:
                continue
        # Get the measured values from the measurements for this sample
        for measurement in sample.measurements:
            colors.append(c[(sample.treatment, sample.ald["oxidiser"])])
            markers.append(m[(sample.treatment, sample.ald["oxidiser"])])
            voltages.append(measurement.vg_at_peak)
            mobilities.append(measurement.mob_at_peak)

    fig, ax = plt.subplots()
    for volt, mob, col, mark in zip(voltages, mobilities, colors, markers):
        ax.scatter(x=volt, y=mob, c=col, marker=mark, alpha=1)
    ax.set_xlabel(r"Gate Voltage at Peak Mobility $\left(\si{\volt}\right)$")
    ax.set_ylabel(r"Peak Mobility $\left(\si[per-mode=fraction]{\square\centi\meter\per\volt\per\second}\right)$")
    ax.set_ylim(15000, 50000)
    fig.tight_layout()
    plt.show()
Esempio n. 9
0
def plot_structure(type):
    for m in [100, 75, 50, 40, 30, 20, 10]:
        plt.close('all')
        rel_chunks = df.loc[df['length_of_chunk'] == m]
        colors = []
        if type == "essays":
            all_docs = all_essays
        else:
            all_docs = all_summaries
        for c, thesis in enumerate(all_docs[0:13]):
            this_doc_len_m = rel_chunks.loc[rel_chunks['document'] == thesis]
            if this_doc_len_m.empty == True:
                continue
            ints = []
            max_number_of_this_chunk = np.max(
                this_doc_len_m['number_of_chunk'])
            for i in this_doc_len_m['number_of_chunk']:
                # transform the chunk number into a percentage of how far in the document this chunk is
                ints.append(100 * int(i) / max_number_of_this_chunk)
            # have to apend color as well?!
            for i in range(len(ints)):
                colors.append(colors_list[c])
            plt.plot(ints, this_doc_len_m['GFI'], '-o', color=colors_list[c])

        # when the lines of all theses are there, we can combine them in one plot and store it
        plt.gcf().set_size_inches(14, 7)
        plt.ylabel('GFI')
        plt.xlabel("document's percentage of the chunk's end")
        #plt.suptitle('GFI for the chunks of size ' + str(m) + ' of document', fontsize=14)
        plt.savefig('Plots/German/assignments/' + type + '/structure/all' +
                    str(m) + '_long_indicesOverNumberOfChunk.svg',
                    bbox_inches='tight')
Esempio n. 10
0
    def plot_single_piechart(self, cluster_no, labels, pdf):
       cluster_label_dict = {}

       for label in labels:
           if label not in cluster_label_dict:
               cluster_label_dict[label] = 1
           else:
               cluster_label_dict[label] += 1
       distinct_labels = []
       label_counts = []
       colors = []
       cmap = self.get_cmap(30)
       i = 0
       for label,value in cluster_label_dict.iteritems():
           colors.append(cmap(i))
           distinct_labels.append(label)
           label_counts.append(value)
           i = i+1
       matplotlib.rcParams['font.size'] = 5

       plt.figure(figsize=(8,8))
       plt.pie(label_counts, explode=None, labels=distinct_labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90)
       # Set aspect ratio to be equal so that pie is drawn as a circle.
       plt.axis('equal')
       plt.suptitle("Cluster no " + str(cluster_no) + "\nNumber of docs in cluster: " + str(len(labels)),fontsize=10)
       pdf.savefig()
       plt.close()
Esempio n. 11
0
def compute_color_histograms(cloud, using_hsv=False):

    # Convert each cloud point's color in float format to a three channel format
    # point format: [x, y, z, color_in_float]

    colors = []
    cloud_points = pc2.read_points(cloud, skip_nans=True)

    for point in cloud_points:

        rgb_color = float_to_rgb(point[3])

        if using_hsv:
            colors.append(rgb_to_hsv(rgb_color) * 255)
        else:
            colors.append(rgb_color)

    # Put each color channel in their own list
    ch1, ch2, ch3 = separate_channels(colors)

    # Concatenate each histogram and normalize the results
    features = get_normalized_feature_set(ch1,
                                          ch2,
                                          ch3,
                                          n_bins=64,
                                          range_bins=(0, 256))
    return features
Esempio n. 12
0
def make_image(neuron, A, scale_depth, index_neuron):
    normal_vectors = A[0:2,:]
    orthogonal_vector = A[2,:]
    depth = depth_points(neuron.location, orthogonal_vector)
    p = project_points(neuron.location, normal_vectors)
    m = min(depth)
    M = max(depth)
    depth =  scale_depth * ((depth - m)/(M-m))
    colors = []
    lines = []
    for i in range(len(neuron.nodes_list)):
        colors.append((depth[i],depth[i],depth[i],1))
        j = neuron.parent_index[i]
        lines.append([(p[0,i],p[1,i]),(p[0,j],p[1,j])])
    lc = mc.LineCollection(lines, colors=colors, linewidths=2)
    fig, ax = pl.subplots()
    ax.add_collection(lc)
    pl.axis('off')
    pl.xlim((min(p[0,:]),max(p[0,:])))
    pl.ylim((min(p[1,:]),max(p[1,:])))
    Name = "neuron" + str(index_neuron[0]+1) + "resample" + str(index_neuron[1]+1) + "angle" + str(index_neuron[2]+1) + ".png"
    fig.savefig(Name,figsize=(6, 6), dpi=80)
    img = Image.open(Name)
    img.load()
    data = np.asarray( img, dtype="int32" )
    data = data[:,:,0]
    return data
Esempio n. 13
0
def draw_trajectories(demos):
    all_thresholds = np.arange(len(demos))
    envs = np.load("valid_environments.npy")[0]
    envs[0, 0] = 0
    for i in range(len(demos)):
        temp_envs = np.array(envs)
        temp_demos = demos[0:i + 1]
        latest_demo = demos[i]
        goal = latest_demo[len(latest_demo) - 1, 0]
        start = latest_demo[0, 0]
        temp_envs[goal, 0] = 1
        plt.figure(i, figsize=(24, 13.5), dpi=80)
        p1 = plt.subplot(1, 1, 1)
        colors = []
        for c in range(0, i):
            colors.append('darkgrey')
        colors.append('yellow')
        #['blue','green','red','cyan','magenta','yellow','black','white','blue']
        DrawTrajectory.draw_traj(p1,
                                 env=temp_envs,
                                 trajectories=temp_demos,
                                 grid_size=5,
                                 arrow_colors=colors,
                                 threshold_plt=False,
                                 temp_threshold=all_thresholds,
                                 width=0.015,
                                 legend_plot=True,
                                 start_state=start)
        plt.savefig("demo_plots/demos_" + str(i) + ".png")
    plt.close("all")
    pic_to_gif.convert_to_gif(len(demos))
Esempio n. 14
0
def get_palette(groups):
    indexT, indexS = 0, 0
    colors = []
    for group in groups:
        color, indexT, indexS = get_color(group, indexT, indexS)
        colors.append(color)

    return colors
Esempio n. 15
0
 def _get_colors(num_colors):
     colors=[]
     for i in np.arange(0., 360., 360. / num_colors):
         hue = i/360.
         lightness = (50 + np.random.rand() * 10)/100.
         saturation = (90 + np.random.rand() * 10)/100.
         colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
     return colors
Esempio n. 16
0
def basic_FCA(G, kappa, its = int(pow(2,32)-1), verbose=True, timesec=0, tree=False, no_edges=0):
    
    # initial conditions
    blink = floor((kappa-1)/2) # blink color and lower bound on post-blink     
    colors = []
    init_col = G.get_colors()
    colors.append(init_col)
    if tree:
        parentlist = [None] * G.num_nodes()
        values = np.random.rand(G.num_nodes())
    # local helper function
    def new_color(vertex):
        neighblist = G.get_neighbor_colors(vertex)  

        if(G.get_color(vertex) > blink and \
           any(np.array(neighblist) == blink)):
             return G.get_color(vertex)
        return (G.get_color(vertex) + 1) % kappa
    
    # initial coloring and start time
    current_col = G.get_colors()
    width_compute(current_col, kappa)
    s = time.time()
    for i in range(1, its+1):
        # perform updates for each vertex
        current_col = list(map(new_color, range(0, G.num_nodes())))

        # check synchronization -> break and return final list and iterations
        width = width_compute(current_col,kappa)
        if(width < floor(kappa/2)):
            if verbose: print("Iterations: ",i)
            if no_edges:
                    
                return np.array([-1, init_col, 1, colors, i])

            return np.array([G.edges, init_col, 1, colors, i])

        if timesec and time.time()-s > timesec:
            if verbose:
                print("Iterations: ",i)
                print("Time has been reached: ", timesec,"sec.")
            if no_edges:
                return np.array([-1, init_col, 0, colors, i])
            return np.array([G.edges, init_col, 0, colors, i])
        # update to new colors
        G.set_colors(current_col)
        colors.append(np.array(G.get_colors()))
        if tree:
            values, parentlist = tree_iter(G, values, parentlist)
            tree = not (len(G.edges) == G.num_nodes()-1)
            if (len(G.edges)<G.num_nodes()-1):
                print("deleted too many edges")

    if verbose: 
        print("Max iterations reached: ", its)
    if no_edges:
        return np.array([-1, init_col, 0, colors, i])
    return np.array([G.edges, init_col, 0, colors, i])
Esempio n. 17
0
def transformColorList(colorList,alpha):
 colors = []
 for rgb in colorList:
  rd = int(rgb.split()[0])
  gn = int(rgb.split()[1])
  bl = int(rgb.split()[2])
  rgb_tuple = (rd/255.,gn/255.,bl/255.,alpha)
  colors.append(rgb_tuple)
 return colors
def show_colorchecker_swatches():
    colors = []
    fig,axs = plt.subplots(4,6)
    for i in range(len(refRGB)):
        colors.append(np.full((10,10,3),refRGB[i],dtype = np.uint8) / 255.0)
        m = i + 1
        plt.subplot(4,6,m)
        plt.imshow(colors[i])
    plt.show()
Esempio n. 19
0
def float_list_type(mystring):
    """Convert string-form list of doubles into list of doubles."""
    colors = []
    for f in mystring.strip("(").strip(")").strip("[").strip("]").split(","):
        try:
            colors.append(float(f))
        except:
            colors.append(f)
    return colors
def show_color_swatches(colorMatrix):
    colors = []
    fig,axs = plt.subplots(4,6)
    for i in range(len(colorMatrix)):
        colors.append(np.full((10,10,3),colorMatrix[i],dtype = np.uint8) / 255.0)
        m = i + 1
        plt.subplot(4,6,m)
        plt.imshow(colors[i])
    plt.show()
Esempio n. 21
0
def float_list_type(mystring):
    """Convert string-form list of doubles into list of doubles."""
    colors = []
    for f in mystring.strip("(").strip(")").strip("[").strip("]").split(","):
        try:
            colors.append(float(f))
        except:
            colors.append(f)
    return colors
Esempio n. 22
0
def getColorMap( rgbFile = "medspiration.rgb" ):
    colors = []
    rgbFile = os.path.join(os.path.dirname(__file__), rgbFile )
    nbCol=0
    for line in open( rgbFile ):
        r,g,b = [int(c) for c in line.split()]
        colors.append( [r/255.,g/255.,b/255.] )
        nbCol += 1
    return( matplotlib.colors.ListedColormap(colors, name="custom", N=nbCol) )
Esempio n. 23
0
def getColorMap(rgbFile="medspiration.rgb"):
    colors = []
    rgbFile = os.path.join(os.path.dirname(__file__), rgbFile)
    nbCol = 0
    for line in open(rgbFile):
        r, g, b = [int(c) for c in line.split()]
        colors.append([r / 255., g / 255., b / 255.])
        nbCol += 1
    return (matplotlib.colors.ListedColormap(colors, name="custom", N=nbCol))
Esempio n. 24
0
 def _generate_colors(self):
     colors = [
         'blue', 'green', 'red', 'magenta', 'orange', 'black', 'brown',
         'grey', 'olive'
     ]  # strong colors
     for color in matplotlib.colors.cnames.keys():
         if color not in colors and 'light' not in color:
             colors.append(color)
     return colors
Esempio n. 25
0
def spiderweb_colormesh2d(data,
                          axis,
                          title='',
                          fill_scheme='viridis',
                          grid=False,
                          norm=None,
                          *args,
                          **kwargs):
    """Prepare bar plot for 2D data visualization.

     matplotlib.pyplot.pcolormesh  is used.

     Args:
        data(ndarray): 2D array of data.
        axis(axis): corresponding tomomak axis
        title(str, optional): Plot title. default: ''.
        fill_scheme(pyplot colormap, optional): pyplot colormap to be used in the plot. default: 'viridis'.
        grid(bool, optional): if True, grid is shown. default: False.
        *args, **kwargs: arguments will be passed to matplotlib.pyplot.pcolormesh

     Returns:
         plot: matplotlib pcolormesh .
         ax(axes.Axes ): axes.Axes object or array of Axes objects.
             See matplotlib Axes class
         fig(matplotlib.figure): The figure module.
         cb(matplotlib.pyplot.colorbar): colorbar on the right of the axis.
     """

    x = axis.cell_edges2d()
    cmap = plt.get_cmap(fill_scheme)
    fig, ax = plt.subplots()

    colors = []
    for i in range(len(x)):
        colors.append(data[i])

    patches = []
    for i in range(len(x)):
        polygon = Polygon(x[i])
        patches.append(polygon)

    p = PatchCollection(patches, cmap=cmap, alpha=1.0)
    p.set_array(np.array(colors))

    plot = ax.add_collection(p)

    cb = fig.colorbar(plot, ax=ax)
    ax.set_title(title)

    xlabel = "{}, {}".format(axis.name, axis.units)
    ylabel = "{}, {}".format(axis.name, axis.units)
    ax.set(xlabel=xlabel, ylabel=ylabel)

    if grid:
        ax.grid()
    return plot, ax, fig, cb
Esempio n. 26
0
def get_n_colors2(num_colors):
    """http://stackoverflow.com/questions/470690/
    how-to-automatically-generate-n-distinct-colors"""
    colors = []
    for i in np.arange(0., 360., 360. / num_colors):
        hue = i / 360.
        lightness = (50 + np.random.rand() * 10) / 100.
        saturation = (90 + np.random.rand() * 10) / 100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
    return colors
def make_IDLCB37():
    #-- create a colors map -----------
    CB37 = np.load(dir + '/IDLCB37.npz')
    R = CB37['R37']
    G = CB37['G37']
    B = CB37['B37']
    colors = [(R[0], G[0], B[0])]
    for i in range(1, 256, 1):
        colors.append((R[i], G[i], B[i]))
    cmap = make_cmap(colors, bit=True)
    return cmap
Esempio n. 28
0
def stackplot_percent_mentions_per_time(mentions_percent, candidate_list, title, save_to = None):
    '''
    Generates and saves a stackplot with the percent mentions over time 
    
    Inputs:
        mentions: Dictionary with keys as candidates, 
            values as percent or number of mentions
        candidate_list : candidates to include
        title: string
        save_to: Directory as a string

    Returns:
        A saved file if save_to is not None.
    '''


    num_candidates = len(candidate_list)
    all_ys = [0]*num_candidates
    
    for i, candidate in enumerate(candidate_list):
        times = mentions_percent[candidate]
        xs = sorted(times)
        ys = []
        for x in xs:
            y = times[x]
            ys.append(y)
        all_ys[(num_candidates - 1) - i] = ys
            #num_candidates - 1 to account for lists starting at index = 0

    stacked_ys = np.row_stack(tuple(all_ys))

    color_map = get_colormap(num_candidates-1)
    colors = []
    for i in range(num_candidates-1):
        col = color_map(i)
        colors.append(col)
    colors.append("white")
    print(colors)
    legend_colors = [mpatches.Patch(edgecolor = 'black', facecolor = color) for color in colors[::-1]]

    params = {'legend.fontsize': 8,'legend.linewidth': 2}
    plt.rcParams.update(params)
    fig, ax = plt.subplots()
    ax.stackplot(xs, stacked_ys, colors = colors)
    plt.xticks(fontsize = 8)
    plt.legend(legend_colors, candidate_list)
    plt.xlabel("Time (mins)")
    plt.ylabel("Percent of Tweets")
    plt.title(title)
    
    if save_to is None:
        plt.show()
    else:
        fig.savefig(save_to) #directory and filename
Esempio n. 29
0
def get_rand_color(val):
    h,s,v = random()*6, 0.5, 243.2
    colors = []
    for i in range(val):
        h += 3.75#3.708
        tmp = ((v, v-v*s*abs(1-h%2), v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]
        colors.append('#' + '%02x' *3%tmp)
        if i%5/4:
            s += 0.1
            v -= 51.2
    return colors
Esempio n. 30
0
def vibrant_colors(n, is_int=False):
    colors = []
    for i in np.arange(0., 360., 360. / n):
        hue = i / 360.
        lightness = (50 + np.random.rand() * 10) / 100.
        saturation = (90 + np.random.rand() * 10) / 100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))

    if is_int:
        colors = np.multiply(colors, 255).astype(np.int)
    return colors
Esempio n. 31
0
def get_colors(n_colors,
               exclude_colors=None,
               return_excluded=False,
               pastel_factor=0,
               n_attempts=1000,
               colorblind_type=None):
    """
    Generate a list of n visually distinct colours.

    :param n_colors: How many colours to generate

    :param exclude_colors: A pre-existing list of (r,g,b) colours that new colours should be distinct from.
    If exclude_colours=None then exclude_colours will be set to avoid white and black
    (exclude_colours=[(0,0,0), (1,1,1)]).
    (r,g,b) values should be floats between 0 and 1.

    :param return_excluded: If return_excluded=True then exclude_colors will be included in the returned color list.
    Otherwise only the newly generated colors are returned (default).

    :param pastel_factor: float between 0 and 1. If pastel_factor>0 paler colours will be generated.

    :param n_attempts: number of random colours to generated to find most distinct colour.

    :param colorblind_type: generate colours that are distinct with given type of colourblindness. Can be:
        'Normal': Normal vision
        'Protanopia': Red-green colorblindness (1% males)
        'Protanomaly': Red-green colorblindness (1% males, 0.01% females)
        'Deuteranopia': Red-green colorblindness (1% males)
        'Deuteranomaly': Red-green colorblindness (most common type: 6% males, 0.4% females)
        'Tritanopia': Blue-yellow colourblindness (<1% males and females)
        'Tritanomaly' Blue-yellow colourblindness (0.01% males and females)
        'Achromatopsia': Total colourblindness
        'Achromatomaly': Total colourblindness

    :return: colors - A list of (r,g,b) colors that are visually distinct to each other
     and to the colours in exclude_colors. (r,g,b) values are floats between 0 and 1.
    """

    if exclude_colors is None:
        exclude_colors = [WHITE, BLACK]

    colors = exclude_colors.copy()

    for i in range(n_colors):
        colors.append(
            distinct_color(colors,
                           pastel_factor=pastel_factor,
                           n_attempts=n_attempts,
                           colorblind_type=colorblind_type))

    if return_excluded:
        return colors
    else:
        return colors[len(exclude_colors):]
Esempio n. 32
0
    def get_grid_patch_collection(self, zpts, plotarray, **kwargs):
        """
        Get a PatchCollection of plotarray in unmasked cells

        Parameters
        ----------
        zpts : numpy.ndarray
            array of z elevations that correspond to the x, y, and horizontal
            distance along the cross-section (self.xpts). Constructed using
            plotutil.cell_value_points().
        plotarray : numpy.ndarray
            Three-dimensional array to attach to the Patch Collection.
        **kwargs : dictionary
            keyword arguments passed to matplotlib.collections.PatchCollection

        Returns
        -------
        patches : matplotlib.collections.PatchCollection

        """
        from matplotlib.patches import Polygon
        from matplotlib.collections import PatchCollection
        rectcol = []

        v = []
        
        colors = []
        for k in range(zpts.shape[0]-1):
            for idx in range(0, len(self.xpts)-1, 2):
                try:
                    ll = ((self.xpts[idx][2], zpts[k+1, idx]))
                    try:
                        dx = self.xpts[idx+2][2] - self.xpts[idx][2]
                    except:
                        dx = self.xpts[idx+1][2] - self.xpts[idx][2]
                    dz = zpts[k, idx] - zpts[k+1, idx]
                    pts = (ll, 
                          (ll[0], ll[1]+dz), (ll[0]+dx, ll[1]+dz),
                          (ll[0]+dx, ll[1])) #, ll) 
                    if np.isnan(plotarray[k, idx]):
                        continue
                    if plotarray[k, idx] is np.ma.masked:
                        continue
                    rectcol.append(Polygon(pts, closed=True))
                    colors.append(plotarray[k, idx])
                except:
                    pass

        if len(rectcol) > 0:
            patches = PatchCollection(rectcol, **kwargs)
            patches.set_array(np.array(colors))
        else:
            patches = None
        return patches
def make_redblue(min, max):
    #-- create a colors map -----------
    colors = [(255, 255, 255)]
    for i in range(1, 256, 1):
        colors.append((255, 255, 255))
    #print(colors)
    #----------------------------------
    #  find the position of zero
    if min * max > 0:
        print('min*max >=0')
        print('Please check your setting !')
        print('Program STOP at make_redblue')
        exit()
    if min > max:
        print('min > max ?')
        print('Please check your setting !')
        print('Program STOP at make_redblue')
        exit()
    num_zero = int(256 * abs(min) / (max + abs(min)))
    num_zero1 = num_zero + 1
    #  color map for > 0
    iR = 255
    iG = 255
    iB = 255
    for i in range(num_zero1 + 1, 256, 1):
        #print(i)
        iG = iG - 6
        if iG >= 0:
            colors[i] = (255, iG, 255)
        else:
            iB = iB - 6
            if iB >= 0:
                colors[i] = (255, 0, iB)
            else:
                iR = iR - 1
                colors[i] = (iR, 0, 0)
    #  color map for < 0
    iR = 255
    iG = 255
    iB = 255
    for i in range(num_zero - 1, -1, -1):
        #print(i)
        iR = iR - 6
        if iR >= 0:
            colors[i] = (iR, 255, 255)
        else:
            iG = iG - 6
            if iG >= 0:
                colors[i] = (0, iG, 255)
            else:
                iB = iB - 1
                colors[i] = (0, 0, iB)
    cmap = make_cmap(colors, bit=True)
    return cmap
Esempio n. 34
0
    def update_node_status(self, *args):
        colors = []
        for i, module in enumerate(self.data_model.modules):
            if (i in self.data_model.input_nodes) and (len(
                    module['config']['filelist']) == 0):
                colors.append('red')
            else:
                colors.append('green')

        #update plot
        with self.data_view.graph.batch_update():
            self.data_view.node_status.marker.color = colors
Esempio n. 35
0
def gen_circular_cmap(colors: List[str]):
    colors = list(colors)

    # `colors` has 12 distinct entries.
    # LinearSegmentedColormap(colors) takes a real number `x` between 0 and 1,
    # and maps x=0 to colors[0] and x=1 to colors[-1].
    # pitch_cmap should be periodic, so `colors[0]` should appear at both x=0 and x=1.
    colors.append(colors[0])

    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
        "12-tone spectrum", colors, N=256, gamma=1.0)
    return cmap
Esempio n. 36
0
def list_by_values(*args):
    """
    Returns a list of colors matching up with the range of numerical values provided
    refer to https://github.com/tomerburg/metlib/blob/master/colors/color_list.py
    
    Examples:
        This is the call to the list_by_values function. Input parameters are as many ranges
        as desired. In this example, there are 3 ranges, one starting from #00FFFF for a value
        of 25 and going to #0000FF for a value of 29.

        colors = list_by_values(
            [['#00FFFF',25.0],['#0000FF',29.0],1.0], [['#0000FF',29.0],['#0000AA',32.0],1.0],
            [['#0000AA',32.0],['#FF00FF',38.0],1.0])
        print(colors)
    """

    #Initialize an empty color list
    colors = []

    #Loop through the passed lists
    #The format for each argument is: [['#00FFFF',25.0],['#0000FF',29.0],1.0]
    #['#00FFFF',25.0] = [start hex value, start value]
    #['#0000FF',29.0] = [end hex value, end value]
    #1.0 = interval of requested range between start & end values
    for arg in args:

        #Retrieve arguments
        start_hex = arg[1][0].lstrip('#')
        end_hex = arg[0][0].lstrip('#')
        start_value = arg[0][1]
        end_value = arg[1][1]
        interval = arg[2]

        #Calculate start and end RGB tuples
        start_rgb = tuple(int(start_hex[i:i + 2], 16) for i in (0, 2, 4))
        end_rgb = tuple(int(end_hex[i:i + 2], 16) for i in (0, 2, 4))

        #Loop through the number of colors to add into the list
        start_loop = start_value
        end_loop = end_value + interval if arg == args[-1] else end_value
        for x in np.arange(start_loop, end_loop, interval):

            #Get hex value for the color at this point in the range
            nrange_color = (end_value - start_value)
            idx = x - start_value
            hex_val = getColor(idx, nrange_color, start_rgb, end_rgb)

            #Append to list if this is different than the last color
            if len(colors) == 0 or colors[-1] != hex_val:
                colors.append(hex_val)

    #Return the list of colors
    return colors
Esempio n. 37
0
def get_rand_color(val):
    h, s, v = random() * 6, 0.5, 243.2
    colors = []
    for i in range(val):
        h += 3.75  #3.708
        tmp = ((v, v - v * s * abs(1 - h % 2), v - v * s) *
               3)[5**int(h) / 3 % 3::int(h) % 2 + 1][:3]
        colors.append('#' + '%02x' * 3 % tmp)
        if i % 5 / 4:
            s += 0.1
            v -= 51.2
    return colors
Esempio n. 38
0
def plot_spikes(nodes, spikes_file, save_file=None):
    import h5py

    spikes_h5 = h5py.File(spikes_file, 'r')
    spike_gids = np.array(spikes_h5['/spikes/gids'], dtype=np.uint)
    spike_times = np.array(spikes_h5['/spikes/timestamps'], dtype=np.float)

    spikes = np.rot90(np.vstack(
        (spike_gids,
         spike_times)))  # Make array [[gid spiketime],[gid2 spiketime2]]

    #spikes = spikes[spikes[:,0].argsort()] # Sort by cell number
    """
    Author: Tyler Banks
    Loop through all spike files, create a list of when each cell spikes, plot.
    """

    cell_types = ['EC', 'CA3e', 'CA3o', 'CA3b', 'DGg', 'DGh', 'DGb']
    cell_nums = [30, 63, 8, 8, 384, 32, 32]
    d = [[] for _ in range(sum(cell_nums))]

    color_picker = [
        'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black'
    ]
    colors = []
    offset = 0

    for i, row in enumerate(spikes):
        d[int(row[0]) + offset].append(row[1])

    for i, n in enumerate(cell_nums):
        for _ in range(n):
            colors.append(color_picker[i])

    fig, axs = plt.subplots(1, 1)
    axs.eventplot(d, colors=colors)
    axs.set_title('Hipp BMTK')
    axs.set_ylabel('Cell Number')
    axs.set_xlabel('Time (ms)')
    axs.legend(cell_types[::-1])

    leg = axs.get_legend()
    for i, c in enumerate(color_picker):
        leg.legendHandles[-i - 1].set_color(c)

    #splt.savefig('raster3_after_pycvode_fixes.png')
    if save_file:
        plt.savefig(save_file)

    plt.draw()

    return
Esempio n. 39
0
def convert_to_heatmap(weights, cm="Reds"):
    # 把权重转化为热力图,可是根据可视化需要选择colormap
    # https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
    cmap = matplotlib.cm.get_cmap(cm)
    colors = []
    for i in range(cmap.N):
        rgb = cmap(i)[:3]
        colors.append(matplotlib.colors.rgb2hex(rgb))
    colors = np.array(colors)

    weights = np.uint8(255 * weights)
    heatmap = colors[weights]
    return heatmap
Esempio n. 40
0
def add_edge(i, j,edge_points,edges,pointsTest,imgCirc,colors):
    """Add a line between the i-th and j-th points, if not in the list already"""
    
    if (i, j) in edges or (j, i) in edges:
        # already added
        colors.append(colorChoice(imgCirc[pointsTest[i,0],pointsTest[i,1]],
                                  imgCirc[pointsTest[j,0],pointsTest[j,1]]))
        return edge_points,edges,colors
    
    edges.add( (i, j) )
    edge_points.append(pointsTest[[i, j]])
    colors.append(colorChoice(imgCirc[pointsTest[i,0],pointsTest[i,1]],
                              imgCirc[pointsTest[j,0],pointsTest[j,1]]))

    return edge_points,edges,colors
Esempio n. 41
0
def stackplot_percent_mentions_per_time(mentions_percent, candidate_list, title):

    num_candidates = len(candidate_list)
    all_ys = [0]*num_candidates
    
    for i, candidate in enumerate(candidate_list):
        times = mentions_percent[candidate]
        xs = sorted(times)
        ys = []
        for x in xs:
            y = times[x]
            ys.append(y)
        all_ys[(num_candidates - 1) - i] = ys
            #num_candidates - 1 to account for lists starting at index = 0

    stacked_ys = np.row_stack(tuple(all_ys))

    color_map = get_colormap(num_candidates-1)
    colors = []
    for i in range(num_candidates-1):
        col = color_map(i)
        colors.append(col)
    colors.append("white")
    print(colors)
    legend_colors = [mpatches.Patch(edgecolor = 'black', facecolor = color) for color in colors[::-1]]

    params = {'legend.fontsize': 8,'legend.linewidth': 2}
    plt.rcParams.update(params)
    fig, ax = plt.subplots()
    ax.stackplot(xs, stacked_ys, colors = colors)
    #ax.set_xticks(pos + (bar_width/2))
    plt.xticks(fontsize = 8)
    ax.set_xticklabels(x_labels, rotation = 60)
    plt.legend(legend_colors, candidate_list)
    plt.xlabel("Time (mins)")
    plt.ylabel("Percent of Tweets")
    plt.title(title)
    plt.show()





################################################


#Donald Trump, Carly Fiorina, Jeb Bush, Ben Carson, Ted Cruz, Rand Paul, and Marco Rubio
Esempio n. 42
0
    def deposit_cells(self):
        """ Deposit cells in a plane """
        
        #coords = self.lattice.coordinates()
        #shape = coords.shape

        rho = numpy.mean(self.lattice.get_mesh_size())
        print "Mean mesh size", rho
        nx = 40
        x0 = 0.5-rho*nx/2.0
        z0 = 0.5-rho*nx/2.0
        print x0
        y0 = 0.1
        
        x = x0+numpy.linspace(0,nx*rho,nx)
        z = z0+numpy.linspace(0,nx*rho,nx)
        
        import itertools
        space = itertools.product(x,z)
        #cols = [5 10 15 20]
        coords = self.lattice.coordinates()
        shape = coords.shape
        
        Ncols = 50
        # Select Ncols random points:
        idx = range(nx*nx)
        color_idx = random.sample(idx, Ncols)
        colors = []
        color_map=get_cmap(len(color_idx))
        for i in range(Ncols):
            colors.append(color_map(i)[0:3])
        
        j=0
        for i,p in enumerate(space):
            point = [p[0],y0,p[1]]
            reppoint = numpy.tile(point, (shape[0], 1))
            dist = numpy.sqrt(numpy.sum((coords-reppoint)**2, axis=1))
            ix = numpy.argmin(dist)
            cell=Cell(color="white",index=ix, time_to_division=self.cell_division_time(),time_to_migration=self.sample_migration_time())
        
            if i in color_idx:
                cell.color=htmlcolor(colors[j])
                j =j+1
            if not self.state[ix]:
                heapq.heappush(self.cells,cell)
                self.state[ix]=cell
Esempio n. 43
0
def pie_plot_percent_mentions(mentions_percent, save_to = None):
    '''
    Generates and saves a pie plot with the percentage of mentions
    
    Inputs:
        mentions_percent: Dictionary with keys as candidates, 
            values as percent of mentions
        save_to: Directory as a string

    Returns:
        A saved file if save_to is not None.
    '''

    other = mentions_percent.pop("Other")
    swapped = {v:k for k, v in mentions_percent.items()}

    sizes = sorted(swapped)
    sizes.reverse()
    labels = [swapped[current_percent] for current_percent in sizes]

    sizes.append(other)
    labels.append("Other")
    N = len(labels)

    color_map = get_colormap(N-1)
    colors = []
    for i in range(N-1):
        col = color_map(i)
        colors.append(col)
    colors.append("white")
    print(colors)

    plt.pie(sizes, labels=labels, colors=colors,
        autopct='%1.1f%%', startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')

    fig = plt.figure()
    ax = fig.gca()

    if save_to is None:
        plt.show()
    else:
        fig.savefig(save_to) #directory and filename
Esempio n. 44
0
    def plot_cluster(self):
        self.scale_data()
        print "finished scale"
        cmap = self.get_cmap(100)
        colors = []
        for i in range(0, self.n_clusters):
            colors.append(cmap(i))
        fig = plt.figure(figsize=(1,1))
        #fig.subplots_adjust(left=0.02, right=0.98, bottom=0.05, top=0.9)
        ax = fig.add_subplot(1, 2, 1)

        for k, col in zip(range(self.n_clusters), colors):
            my_members = self.k_means_labels == k
            cluster_center = self.k_means_cluster_centers[k]
            ax.plot(self.X_scaled[my_members, 0], self.X_scaled[my_members, 1], 'w',
                    markerfacecolor=col, marker='.')
            #fig.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
            #        markeredgecolor='k', markersize=6)
        plt.show()
Esempio n. 45
0
    def colorTableList(num_colors):
        colors = []

        # Transparent for the zero label
        colors.append((0,0,0,0))

        rgb_color_values = list(nanshe.util.iters.splitting_xrange(num_colors))
        converter = matplotlib.colors.ColorConverter()

        for _ in rgb_color_values:
            a_rgb_color = tuple()
            for __ in converter.to_rgba(matplotlib.cm.gist_rainbow(_)):
                 a_rgb_color += ( int(round(255*__)), )

            colors.append(a_rgb_color)

        colors = numpy.asarray(colors, dtype=numpy.uint8)

        return(colors)
 def readClrColorRamp(self,path):
     f = open(path, 'r')
     colors = []
     levels = None
     processtype = 0
     for line in f:
         if 'colors' in line :
             processtype = 1
             continue
         elif 'levels' in line :
             processtype = 2
             continue
         if processtype == 1:
             colors.append([float(elem) for elem in line.split(';')])
             #print 'col ' + str(colors)
         if processtype == 2:
             levels = ([float(elem) for elem in line.split(';')])
     f.close()
     if colors and levels:
         return (self.arrayStepRGBAToCmap(colors),levels)
     else:
         return (None, None)
Esempio n. 47
0
def version_balance(trials, ax=None, figsize=None):
    if ax is None:
        pyplot.figure(figsize=figsize)
        ax = pyplot.axes()

    counts = trials.program_name.value_counts().sort_index()

    # Assign colors by base
    colors = []
    last_base = None
    color_i = -1
    for n in counts.index:
        base = n.split("_")[0]
        if base != last_base:
            color_i += 1
            last_base = base
        colors.append(kelly_colors[color_i])

    counts.plot(kind="bar", ax=ax, color=colors)
    ax.set_title("Version Balance ({0} trials)".format(len(trials)))

    return ax
Esempio n. 48
0
def fit_coefficients_version(fit, ax=None, figsize=None, intercept=True):
    if ax is None:
        pyplot.figure(figsize=figsize)
        ax = pyplot.axes()

    names = [get_fit_name(n) for n in fit.model.exog_names]
    means = fit.conf_int().apply(lambda x: np.mean(x), axis=1)
    err = fit.conf_int().apply(lambda x: (x[1] - x[0]) / 2.0, axis=1)

    # Assuming p-values come in the same order as confidence intervals
    for i, p_val in enumerate(fit.pvalues.values):
        if np.isclose(p_val, 1.0):
            err[i] = 0.0

    if not intercept:
        means, err = means[1:], err[1:]
        names = names[1:]

    # Assign colors by base
    colors = []
    last_base = None
    color_i = -1
    for n in names:
        base = n.split("_")[0]
        if base != last_base:
            color_i += 1
            last_base = base
        colors.append(kelly_colors[color_i])

    # Plot bars
    ax = means.plot(kind="bar", yerr=err, error_kw={"ecolor": "black"}, color=colors)
    ax.set_title("Coefficients by Program/Version")
    ax.set_ylabel("Coefficients (95% CI)")
    ax.set_xlabel("Program Base/Version")
    ax.set_xticklabels(names)

    return ax
Esempio n. 49
0
def fancy_dendrogram(*args, **kwargs):
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)
    ddata = dendrogram(*args, **kwargs)
    colors = []
    color_elements = ["FF", "00", "33", "66", "99", "AA", "DD"]
    color = ["00", "00", "00"]
    num = 0
    if not kwargs.get('no_plot', False):
        plt.title('Dendrogram of hierarchical clustering', fontsize=28)
        plt.tick_params(labelsize=22)
        plt.xlabel('Genes', fontsize=24, color="black")
        plt.ylabel('Distance', fontsize=24, color="black")
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            color_index = random.randint(0, 6)
            if num % 3 == 0:
                color = color[:2] + [color_elements[color_index]]
            elif num % 3 == 1:
                color = [color_elements[color_index]] + color[1:]
            elif num % 3 == 2:
                color = [color[0]] + [color_elements[color_index]] + [color[-1]]
            if ("".join(color) != "FFFFFF") and \
               (color not in colors):
                c = '#' + "".join(color)
                colors.append(color)
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, color=c)
            num += 1
        if max_d:
            plt.axhline(y=max_d, linewidth=3, color='orange')
            
    return ddata
Esempio n. 50
0
def get_colors():
  colors=[]
  colors.append( 'blue' )
  colors.append( 'green' )
  colors.append( 'red' )
  colors.append( 'cyan' )
  colors.append( 'magenta' )
  colors.append( 'yellow' )
  return colors
Esempio n. 51
0
 def _generate_colors(self):
     colors = ['blue', 'green', 'red', 'magenta', 'orange', 'black', 'brown', 'grey', 'olive']  # strong colors
     for color in matplotlib.colors.cnames.keys():
         if color not in colors and 'light' not in color:
             colors.append(color)
     return colors
Esempio n. 52
0
def partiview(root="./", align="align/align_d_rms_t", poly="polyfit_d/fit"):
    s = getOrbitStars(orbitFile="orbits_movie.dat", root=root, align=align, poly=poly)

    # Determine the mass assuming a distance of 8.46 kpc
    star0orb = s.stars[0].orbit
    dist = 8460.0  # in parsec
    axis = (star0orb.a / 1000.0) * dist  # in au
    mass = (axis) ** 3 / star0orb.p ** 2
    print "Mass = %.2e Msun    Dist = %4d pc" % (mass, dist)

    names = s.getArray("name")

    ## Three sets of stars
    ##    -- constrains Ro today
    ##    -- constrains Ro/extended mass in future (radial velocities)
    ##    -- constrains extended mass in future (no radial velocities)
    # Assume the stars are in increasing order by name
    stars1 = ["S0-2", "S0-16", "S0-19", "S0-1", "S0-20"]
    stars2 = []
    stars3 = []

    yngstars = ["S0-1", "S0-2", "S0-3", "S0-4", "S0-5", "S0-7", "S0-8", "S0-16", "S0-19", "S0-20", "S0-26"]
    oldstars = ["S0-6", "S0-18"]

    # All stars3 come after S0-26
    foundS026 = False
    for name in names:
        try:
            idx = stars1.index(name)
            continue
        except ValueError:
            if foundS026 == False:
                stars2.append(name)
                if name == "S0-26":
                    foundS026 = True
            else:
                stars3.append(name)

    # Duration of the animation (30 years)
    t = na.arange(1995.5, 1995.5 + 300.0, 0.1, type=na.Float)

    xpos = na.zeros((len(s.stars), len(t)), type=na.Float)
    ypos = na.zeros((len(s.stars), len(t)), type=na.Float)
    zpos = na.zeros((len(s.stars), len(t)), type=na.Float)
    colors = []

    for ii in range(len(s.stars)):
        star = s.stars[ii]
        orb = star.orbit
        print "Working on ", star.name

        # Determine time steps
        x = star.getArrayAllEpochs("x")
        y = star.getArrayAllEpochs("y")

        (r, v, a) = orb.kep2xyz(t, mass=mass, dist=dist)

        xpos[ii] = r[:, 0]
        ypos[ii] = r[:, 1]
        zpos[ii] = r[:, 2]

        # Determine color
        if star.name in yngstars:
            colors.append("b")
        elif star.name in oldstars:
            colors.append("r")
        else:
            colors.append("y")

    _out = open("plots/partiview/partiview.dat", "w")
    for ti in range(len(t)):
        _out.write("%9.4f %d\n" % (t[ti], ti))
        for si in range(len(s.stars)):
            _out.write("%7.3f %7.3f %7.3f %s\n" % (xpos[si, ti], ypos[si, ti], zpos[si, ti], colors[si]))

    _out.close()
Esempio n. 53
0
for name_stepsize, group in grouped_stepsize:
    fig, ax = plt.subplots(ncols=3, nrows=4, sharex=True, sharey=True, figsize=(8., 6.))
    grouped_clearborder_method = group.groupby(['clearborder', 'method'])
    ax[0, 0].set_ylim([0,0.65])
    for name_clearborder_method, group2 in grouped_clearborder_method:
        x_clearborder, y_method = name_clearborder_method
        x, y = axes_clearborder[x_clearborder], axes_method[y_method]
        table = group2.groupby(['lambda']).mean()
        table = table.sort_index()
        AJI = table['AJI']
        lambda_val = [i for i in table.index]
        colors = []
        cmap = cm.get_cmap("gist_earth", len(lambda_val)+1)    # PiYG
        for i in range(cmap.N - 1):
            rgb = cmap(i)[:3] # will return rgba, we take only first 3 so we get rgb
            colors.append(matplotlib.colors.rgb2hex(rgb))
        width = 1,
        ax[x, y].bar(lambda_val, list(AJI), color=colors, alpha=1., width=width)
        ax[x, y].axhline(y=np.max(AJI),xmin=0,xmax=3,c="black",ls="--",linewidth=0.5,zorder=0)
        ax[x, y].text(7.5, np.max(AJI) + 0.01, "{0:.3}".format(np.max(AJI)), rotation=0)
    for a, col in zip(ax[0], cols): 
        a.annotate(col, xy=(0.5, 1), xytext=(0, pad),
                    xycoords='axes fraction', textcoords='offset points',
                    ha='center', va='baseline')

    for a, row in zip(ax[:,0], rows):
        a.annotate(row, xy=(0, 0.5), xytext=(-a.yaxis.labelpad - pad, 0),
                    xycoords=a.yaxis.label, textcoords='offset points',
                    ha='right', va='center', rotation="vertical")
    ax[0,-1].set_xticks(ticks=lambda_val)
    ax[-2,1].set_xticks(ticks=lambda_val)
Esempio n. 54
0
def prepare_lines(lines, scalars=None, do_connections=False, other=None):
    """Concatenate and standardize a list of lines

    Args:
        lines (list): Must be a list of 3xN or 4xN ndarrays of xyz(s)
            data for N points along the line. N need not be the same
            for all lines. Can alse be 6xN such that lines[:][3:, :]
            are interpreted as rgb colors
        scalars (sequence): can be one of::

              - single hex color (ex, `#FD7400`)
              - sequence of Nlines hex colors
              - single rgb(a) tuple
              - sequence of Nlines rgb(a) sequences
              - sequence of N values that go with each vertex and will
                be mapped with a colormap
              - sequence of Nlines values that go each line and will
                be mapped with a colormap
              - Field. If `np.prod(fld.shape) in (N, nlines)` then the
                field is interpreted as a simple sequence of values
                (ie, the topology result from calc_streamlines for
                coloring each line). Otherwise, the field is
                interpolated onto each vertex.

        do_connections (bool): Whether or not to make connections array
        other (dict): a dictionary of other arrays that should be
            reshaped and the like the same way scalars is

    Returns:
        (vertices, scalars, connections, other)

        * vertices (ndarray): 3xN array of N xyz points. N is the sum
            of the lengths of all the lines
        * scalars (ndarray): N array of scalars, 3xN array of uint8
            rgb values, 4xN array of uint8 rgba values, or None
        * connections (ndarray): Nx2 array of ints (indices along
            axis 1 of vertices) describing the forward and backward
            connectedness of the lines, or None
        * other (dict): a dict of N length arrays

    Raises:
        ValueError: If rgb data is not in a valid range or the shape
            of scalars is not understood
    """
    nlines = len(lines)
    npts = [line.shape[1] for line in lines]
    N = np.sum(npts)
    first_idx = np.cumsum([0] + npts[:-1])
    vertices = [np.asarray(line) for line in lines]
    vertices = np.concatenate(lines, axis=1)
    if vertices.dtype.kind not in 'fc':
        vertices = np.asarray(vertices, dtype='f')

    if vertices.shape[0] > 3:
        if scalars is not None:
            viscid.logger.warning("Overriding line scalars with scalars kwarg")
        else:
            scalars = vertices[3:, :]
        vertices = vertices[:3, :]

    if scalars is not None:
        scalars_are_strings = False

        if isinstance(scalars, viscid.field.Field):
            if np.prod(scalars.shape) in (nlines, N):
                scalars = np.asarray(scalars).reshape(-1)
            else:
                scalars = viscid.interp_trilin(scalars, vertices)
                if scalars.size != N:
                    raise ValueError("Scalars was not a scalar field")
        elif isinstance(scalars, (list, tuple, viscid.string_types, np.ndarray)):
            # string types need some extra massaging
            if any(isinstance(s, viscid.string_types) for s in scalars):
                assert all(isinstance(s, viscid.string_types) for s in scalars)

                scalars_are_strings = True
                scalars = _string_colors_as_hex(scalars)
            elif isinstance(scalars, np.ndarray):
                scalars = scalars
            else:
                for i, si in enumerate(scalars):
                    if not isinstance(si, np.ndarray):
                        scalars[i] = np.asarray(si)
                    scalars[i] = np.atleast_2d(scalars[i])
                try:
                    scalars = np.concatenate(scalars, axis=0)
                except ValueError:
                    scalars = np.concatenate(scalars, axis=1)

        scalars = np.atleast_2d(scalars)

        if scalars.dtype == np.dtype('object'):
            raise RuntimeError("Scalars must be numbers, tuples of numbers "
                               "that indicate rgb(a), or hex strings - they "
                               "must not be python objects")

        if scalars.shape == (1, 1):
            scalars = scalars.repeat(N, axis=1)
        elif scalars.shape == (1, nlines) or scalars.shape == (nlines, 1):
            # one scalar for each line, so broadcast it
            scalars = scalars.reshape(nlines, 1)
            scalars = [scalars[i].repeat(ni) for i, ni in enumerate(npts)]
            scalars = np.concatenate(scalars, axis=0).reshape(1, N)
        elif scalars.shape == (N, 1) or scalars.shape == (1, N):
            # catch these so they're not interpreted as colors if
            # nlines == 1 and N == 3; ie. 1 line with 3 points
            scalars = scalars.reshape(1, N)
        elif scalars.shape in [(3, nlines), (nlines, 3), (4, nlines), (nlines, 4)]:
            # one rgb(a) color for each line, so broadcast it
            if (scalars.shape in [(3, nlines), (4, nlines)] and
                scalars.shape not in [(3, 3), (4, 4)]):
                # the guard against shapes (3, 3) and (4, 4) mean that
                # these square shapes are assumed Nlines x {3,4}
                scalars = scalars.T
            nccomps = scalars.shape[1]  # 3 for rgb, 4 for rgba
            colors = []
            for i, ni in enumerate(npts):
                c = scalars[i].reshape(nccomps, 1).repeat(ni, axis=1)
                colors.append(c)
            scalars = np.concatenate(colors, axis=1)
        elif scalars.shape in [(3, N), (N, 3), (4, N), (N, 4)]:
            # one rgb(a) color for each vertex
            if (scalars.shape in [(3, N), (4, N)] and
                scalars.shape not in [(3, 3), (4, 4)]):
                # the guard against shapes (3, 3) and (4, 4) mean that
                # these square shapes are assumed N x {3,4}
                scalars = scalars.T
        elif scalars.shape in [(1, 3), (3, 1), (1, 4), (4, 1)]:
            # interpret a single rgb(a) color, and repeat/broadcast it
            scalars = scalars.reshape([-1, 1]).repeat(N, axis=1)
        else:
            scalars = scalars.reshape(-1, N)

        # scalars now has shape (1, N), (3, N), or (4, N)

        if scalars_are_strings:
            # translate hex colors (#ff00ff) into rgb(a) values
            scalars = np.char.lstrip(scalars, '#')
            strlens = np.char.str_len(scalars)
            min_strlen, max_strlen = np.min(strlens), np.max(strlens)

            if min_strlen == max_strlen == 8:
                # 32-bit rgba  (two hex chars per channel)
                scalars = _hexchar2int(scalars.astype('S8')).reshape(-1, 4).T
            elif min_strlen == max_strlen == 6:
                # 24-bit rgb (two hex chars per channel)
                scalars = _hexchar2int(scalars.astype('S6')).reshape(-1, 3).T
            else:
                raise NotImplementedError("This should never happen as "
                                          "scalars as colors should already "
                                          "be preprocessed appropriately")
        elif scalars.shape[0] == 1:
            # normal scalars, cast them down to a single dimension
            scalars = scalars.reshape(-1)
        elif scalars.shape[0] in (3, 4):
            # The scalars encode rgb data, standardize the result to a
            # 3xN or 4xN ndarray of 1 byte unsigned ints [0..255]
            if np.all(scalars >= 0) and np.all(scalars <= 1):
                scalars = (255 * scalars).round().astype('u1')
            elif np.all(scalars >= 0) and np.all(scalars < 256):
                scalars = scalars.round().astype('u1')
            else:
                raise ValueError("Rgb data should be in range [0, 1] or "
                                 "[0, 255], range given is [{0}, {1}]"
                                 "".format(np.min(scalars), np.max(scalars)))
        else:
            raise ValueError("Scalars should either be a number, or set of "
                             "rgb values, shape is {0}".format(scalars.shape))

        # scalars should now have shape (N, ) or be a uint8 array with shape
        # (3, N) or (4, N) encoding an rgb(a) color for each point [0..255]
        # ... done with scalars...

    # broadcast / reshape additional arrays given in other
    if other:
        for key, arr in other.items():
            if arr is None:
                pass
            elif arr.shape == (1, nlines) or arr.shape == (nlines, 1):
                arr = arr.reshape(nlines, 1)
                arr = [arr[i].repeat(ni) for i, ni in enumerate(npts)]
                other[key] = np.concatenate(arr, axis=0).reshape(1, N)
            else:
                try:
                    other[key] = arr.reshape(-1, N)
                except ValueError:
                    viscid.logger.warning("Unknown dimension, dropping array {0}"
                                          "".format(key))

    if do_connections:
        connections = [None] * nlines
        for i, ni in enumerate(npts):
            # i0 is the index of the first point of the i'th line in lines
            i0 = first_idx[i]
            connections[i] = np.vstack([np.arange(i0, i0 + ni - 1.5),
                                        np.arange(i0 + 1, i0 + ni - 0.5)]).T
        connections = np.concatenate(connections, axis=0).astype('i')
    else:
        connections = None

    return vertices, scalars, connections, other
Esempio n. 55
0
def partiview(root='./', align='align/align_d_rms_t', poly='polyfit_d/fit'):
    s = getOrbitStars(orbitFile='orbits_movie.dat',
                      root=root, align=align, poly=poly)

    # Determine the mass assuming a distance of 8.46 kpc
    star0orb = s.stars[0].orbit
    dist = 8460.0 # in parsec
    axis = (star0orb.a / 1000.0) * dist # in au
    mass = (axis)**3 / star0orb.p**2
    print 'Mass = %.2e Msun    Dist = %4d pc' % (mass, dist)

    names = s.getArray('name')

    ## Three sets of stars
    ##    -- constrains Ro today
    ##    -- constrains Ro/extended mass in future (radial velocities)
    ##    -- constrains extended mass in future (no radial velocities)
    # Assume the stars are in increasing order by name
    stars1 = ['S0-2', 'S0-16', 'S0-19', 'S0-1', 'S0-20']
    stars2 = []
    stars3 = []

    yngstars = ['S0-1', 'S0-2', 'S0-3', 'S0-4', 'S0-5', 'S0-7', 'S0-8', 
		'S0-16', 'S0-19', 'S0-20', 'S0-26']
    oldstars = ['S0-6', 'S0-18']

    # All stars3 come after S0-26
    foundS026 = False
    for name in names:
        try:
            idx = stars1.index(name)
            continue
        except ValueError:
            if foundS026 == False:
                stars2.append(name)
                if name == 'S0-26':
                    foundS026 = True
            else:
                stars3.append(name)

    # Duration of the animation (30 years)
    t = na.arange(1995.5, 1995.5 + 300.0, 0.1, type=na.Float)

    xpos = na.zeros((len(s.stars), len(t)), type=na.Float)
    ypos = na.zeros((len(s.stars), len(t)), type=na.Float)
    zpos = na.zeros((len(s.stars), len(t)), type=na.Float)
    colors = []

    for ii in range(len(s.stars)):
        star = s.stars[ii]
        orb = star.orbit
        print 'Working on ', star.name
        
        # Determine time steps
        x = star.getArrayAllEpochs('x')
        y = star.getArrayAllEpochs('y')

        (r, v, a) = orb.kep2xyz(t, mass=mass, dist=dist)

        xpos[ii] = r[:,0]
        ypos[ii] = r[:,1]
        zpos[ii] = r[:,2]                  

	# Determine color
	if (star.name in yngstars):
	    colors.append('b')
	elif (star.name in oldstars):
	    colors.append('r')
	else:
	    colors.append('y')
	    
    _out = open('plots/partiview/partiview.dat', 'w')
    for ti in range(len(t)):
        _out.write('%9.4f %d\n' % (t[ti], ti))
        for si in range(len(s.stars)):
            _out.write('%7.3f %7.3f %7.3f %s\n' %
                       (xpos[si,ti], ypos[si,ti], zpos[si,ti], colors[si]))
            

    _out.close()
                         txtFilterSize = 'No. '
                     elif filterSize > 0 and filterSize < 10:
                         txtFilterSize = str(filterSize) + '  . '
                     else:
                         txtFilterSize = str(filterSize) + '. '
                     
                     txtLegend = 'Zeros = ' + (fmt1 % zerosDBZ) + ' dBZ, filter = ' +  txtFilterSize \
                     + r'$\beta_1$ = ' + (fmt2 % beta1) + r', $\beta_2$ = ' + (fmt2 % beta2) \
                     + ', break at ' + str(scalingBreak_best) + ' km'
                 
                     # Draw spectrum
                     ax1.plot(10*np.log10(freq),10*np.log10(psd1d), color=colorLine, linestyle = lineStyle, label=txtLegend)
                 else:
                     print('You can only plot the 1d spectrum with this script...')
                     sys.exit(1)
                 colors.append(colorLine)
             colorLine = np.array(colorLine) + 1/len(zerosDBZlist)
             
     # Set colorbar stochastic realizations
     fig_noise.subplots_adjust(right=0.8)
     cbar_ax = fig_noise.add_axes([0.85, 0.15, 0.05, 0.7])
     fig_noise.colorbar(im_noise, cax=cbar_ax)
     
     # Generate legend for spectra
     legend = ax1.legend(loc='lower left', fontsize=9, labelspacing=0.1)
     # for text in legend.get_texts():
         # text.set_color("red")
     for color,text in zip(colors,legend.get_texts()):
         text.set_color(color)
 
     # Write betas and correlations
                elif clusterAlgLabel == 'AffinityPropagation':   
                    original_shape = som.codebook.shape
                    som.codebook.shape = (som._n_columns*som._n_rows, som.n_dim)
                    init = -np.max(distance.pdist(som.codebook, 'euclidean'))      
                    som.codebook.shape = original_shape        
                    algorithm = clusterAlgs.AffinityPropagation(preference = init,damping = 0.9)
                elif clusterAlgLabel == 'KMeans8':
                    algorithm = None

                print('Clustering algorithm employed: %s' %clusterAlgLabel)
                som.cluster(algorithm=algorithm)
                '''----------------------------------------------------'''

                colors = []
                for bm in som.bmus:
                    colors.append(som.clusters[bm[1], bm[0]])
                areas = [200]*len(som.bmus)

                xDimension, yDimension = [], []
                for x in som.bmus:
                    xDimension.append(x[0])
                    yDimension.append(x[1])

                if not os.path.exists(figWritePath+'/'+clusterAlgLabel+'Clusters/'+SOMdimensionsString):
                    os.makedirs(figWritePath+'/'+clusterAlgLabel+'Clusters/'+SOMdimensionsString)
                fig, ax = plt.subplots()
                colMap = 'Spectral_r'
                plt.imshow(som.umatrix,cmap = colMap, aspect = 'auto')
                ax.scatter(xDimension,yDimension,c=colors,s=areas)
                doneLabs = set([''])
                for label, x, y in zip(labels, xDimension, yDimension):
        for i in range(0,nB):
            name += 'B'
        gap = 0
        for dct in con.select(comb_A=comb_A, comb_B=comb_B, sequence=name):
            gap = dct.gllbsc_gamma_gap
        vect.append(gap)
        gaps.append(gap)
    vect.append(gap)
    matrix.append(np.array(vect))
matrix.append(np.array(vect))

colors = []
for i in gaps:
    c = cm.jet(int(float(i)/float(max(gaps))*255))
    for j in range(6):
        colors.append([c[0],c[1],c[2]])

x = np.array(range(1, 7), float)
y = x.copy()
xpos, ypos = np.meshgrid(x, y)
z = np.array(matrix)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros_like(xpos)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = z.flatten()
fig = plt.figure()
ax = Axes3D(fig)
plt.xlabel('nB, B = '+comb_B)
plt.ylabel('nA, A = '+comb_A)