def region_select_callback(attr, old, new):
        new_lines = set(new) - set(old)
        old_lines = set(old) - set(new)

        for key in old_lines:
            lines[key].visible = False
            lines[f'{key}_prediction'].visible = False
            bands[key].visible = False

        for key in new_lines:
            if key in lines.keys():
                lines[key].visible = True
                lines[f'{key}_prediction'].visible = True
                bands[key].visible = True
            else:
                color = RGB(*hex_string_to_rgb(np.random.choice(Viridis256)))
                darkened_color = color.darken(.15)
                lightened_color = color.lighten(.15)

                draw_prediction_line(key, line_color=darkened_color)
                draw_prediction_band(key,
                                     conf_level=confidence_level,
                                     fill_color=lightened_color)
                draw_data_line(key, line_color=color)

                hover_tool.renderers = [
                    *hover_tool.renderers, lines[key],
                    lines[f'{key}_prediction']
                ]
Esempio n. 2
0
def show(plot, background=None):
    """Show a plot in a notebook.

    :param background: a fill colour for the plot background, hex string or RGB
        tuple.

    """
    children = all_children(plot)
    orig_colours = None
    if background is not None:
        if isinstance(background, tuple):
            background = RGB(*background)
        elif not (isinstance(background, str) and background.startswith('#')):
            raise TypeError(
                "`background` should be a RGB tuple or hex-colour string.")
        orig_colours = list()
        for child in children:
            orig_colours.append((
                child.background_fill_color,
                child.border_fill_color))
            child.background_fill_color = background
            child.border_fill_color = background
    bkio.output_notebook(hide_banner=True)
    bkio.show(plot)
    if background is not None:
        for colours, child in zip(orig_colours, children):
            child.background_fill_color = colours[0]
            child.border_fill_color = colours[1]
    def test_color(self):
        c = RGB(16, 32, 64)
        self.assertEqual(self.encoder.default(c), "rgb(16, 32, 64)")
        self.assertIsInstance(self.encoder.default(c), string_types)

        c = RGB(16, 32, 64, 0.1)
        self.assertEqual(self.encoder.default(c), "rgba(16, 32, 64, 0.1)")
        self.assertIsInstance(self.encoder.default(c), string_types)
Esempio n. 4
0
    def test_color(self):
        c = RGB(16, 32, 64)
        assert self.encoder.default(c) == "rgb(16, 32, 64)"
        assert isinstance(self.encoder.default(c), string_types)

        c = RGB(16, 32, 64, 0.1)
        assert self.encoder.default(c) == "rgba(16, 32, 64, 0.1)"
        assert isinstance(self.encoder.default(c), string_types)
Esempio n. 5
0
def get_color(agent):
    if agent.status == AgentStatus.DEAD:
        return RGB(113, 128, 147).lighten(agent.frailty).to_css()  # 718093
    elif agent.status == AgentStatus.IMMUNE:
        return RGB(68, 189, 50).lighten(agent.frailty).to_css()  # 44bd32
    elif agent.status == AgentStatus.INFECTIOUS:
        return RGB(232, 65, 24).lighten(agent.frailty).to_css()  # e84118
    elif agent.status == AgentStatus.SUSCEPTIBLE:
        return RGB(0, 168, 255).lighten(agent.frailty).to_css()  # 00a8ff
Esempio n. 6
0
def bokeh_plot(filepath, node):
    with h5.File(filepath) as hf:
        data = hf[node][()]
    if data.ndim == 0:        
        bokeh_tools = create_bokeh_tools()
        y=[data]
        x=[0]
        source = ColumnDataSource(data=dict(x=x, y=y))
        plot = figure(title=node.split('/')[-1], toolbar_location="above",
                    sizing_mode="scale_width", tools=bokeh_tools)
        plot.line('x', 'y', source=source, legend=node.split('/')[-1],
                line_width=3, line_alpha=0.6, line_color=RGB(0,158,234))
        plot.circle('x', 'y', source=source, fill_color="white", size=10)
        
        return [plot]        

    elif data.ndim == 1:        
        bokeh_tools = create_bokeh_tools()
        y = data
        x = np.arange(data.shape[0])

        source = ColumnDataSource(data=dict(x=x, y=y))
        
        plot = figure(title=node.split('/')[-1], toolbar_location="above",
                    sizing_mode="scale_width", tools=bokeh_tools)
        plot.line('x', 'y', source=source, legend=node.split('/')[-1],
                line_width=3, line_alpha=0.6, line_color=RGB(0,158,234))
        plot.circle('x', 'y', source=source, fill_color="white", size=10)

        return [plot]

    elif data.ndim == 2:                
        plots = []
        i = 0
        for p in data:
            bokeh_tools = create_bokeh_tools()
            y = p
            x = np.arange(p.shape[0])

            source = ColumnDataSource(data=dict(x=x, y=y))

            p = figure(title=node.split('/')[-1], toolbar_location="above",
                    sizing_mode="scale_width", tools=bokeh_tools)
            p.line('x', 'y', source=source, legend=node.split('/')[-1],
                line_width=3, line_alpha=0.6, line_color=RGB(0,158,234))
            p.circle('x', 'y', source=source, fill_color="white", size=10)
            plots.append(p)            
            i += 1
        
        return plots

    elif data.ndim == 3:
        pass
Esempio n. 7
0
def hist2d(p,
           x,
           y,
           weights=None,
           bins=[100, 100],
           colormap=None,
           density=False):
    H, xedges, yedges = np.histogram2d(x,
                                       y,
                                       bins=bins,
                                       weights=weights,
                                       density=density)
    H = H.T
    palette = [
        RGB(*tuple(rgb)).to_hex()
        for rgb in (255 * colormap(np.arange(256))).astype('int')
    ]
    color_mapper = LinearColorMapper(palette=palette, low=0.0, high=np.max(H))
    p.image(image=[H],
            x=min(xedges),
            y=min(yedges),
            dw=(max(xedges) - min(xedges)),
            dh=(max(yedges) - min(yedges)),
            color_mapper=color_mapper,
            level="image")
    # bokeh_pcolor(p,xedges,yedges,H,color_mapper)
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')
Esempio n. 8
0
    def test_from_rgb(self):
        c = RGB(255, 100, 0)
        c2 = bch.HSL.from_rgb(c)
        assert c2 is not c
        assert c2.a == 1
        assert c2.h == 24
        assert c2.s == 1.0
        assert c2.l == 0.5

        c = RGB(255, 100, 0, 0.1)
        c2 = bch.HSL.from_rgb(c)
        assert c2 is not c
        assert c2.a == 0.1
        assert c2.h == 24
        assert c2.s == 1.0
        assert c2.l == 0.5
Esempio n. 9
0
def bokeh_normalized_meta_scatter_plot(title,
                                       transcript_count_list_dict,
                                       color_dict,
                                       x_max,
                                       show_plot=False,
                                       png_dir=None,
                                       svg_dir=None):
    logging.getLogger(config.FIVEPSEQ_PLOT_LOGGER).info(
        "Plotting normalized full-length meta counts. ")
    output_file(title + ".html", mode="cdn")

    p = figure(
        title=title,
        x_axis_label=
        "normalized position within the transcript and surrounding span regions",
        y_axis_label="5'seq read counts")

    for key in transcript_count_list_dict.keys():
        count_vector_list = transcript_count_list_dict.get(key)
        # normalized_vector_list = [[]]*x_max
        normalized_count_sums = np.zeros(x_max)
        for index in range(0, len(count_vector_list)):
            count_vector = count_vector_list[index]
            stretch_vector = np.zeros(x_max * len(count_vector))
            for i in range(0, len(count_vector)):
                stretch_vector[(0 + i * x_max):((i + 1) *
                                                x_max)] = count_vector[i]
            normalized_vector = np.zeros(x_max)
            for i in range(0, x_max):
                normalized_vector[i] = np.mean(
                    stretch_vector[(i *
                                    len(count_vector)):((i + 1) *
                                                        len(count_vector))])
            # normalized_vector_list[index] = list(normalized_vector)
            normalized_count_sums = [
                sum(x) for x in zip(normalized_count_sums, normalized_vector)
            ]
        normalized_meta_counts = [
            c / float(len(count_vector_list)) for c in normalized_count_sums
        ]

        c = color_dict.get(key)

        if c is None:
            logging.getLogger(config.FIVEPSEQ_PLOT_LOGGER).warning(
                "Color not set for sample %s" % key)
            c = get_random_color()

        line = p.line(list(range(0, x_max)),
                      normalized_meta_counts,
                      legend=key,
                      line_color=RGB(c[0], c[1], c[2]))
        hover = HoverTool(tooltips=[('position', '@x'), ('count', '@y')],
                          renderers=[line])
        p.add_tools(hover)
    p.legend.click_policy = "hide"

    if show_plot:
        show(p)
    return p
 def __init__(self, x, y):
     self.x = x
     self.y = y
     self.c = (0, 0, 0)  # black   RGB color
     self.d = 1  # direction 1 = right, -1 = left
     self.cds = ColumnDataSource(
         data=dict(x=[self.x], y=[self.y],
                   color=[RGB(*self.c)]))  # ColumnDataSource to update plot
Esempio n. 11
0
 def test_transform(self) -> None:
     prop = bcpc.ColorHex()
     assert prop.transform('#ff0000') == "#ff0000"
     assert prop.transform((255, 0, 0)) == "#ff0000"
     assert prop.transform((255, 0, 0, 0.1)) == "#ff0000"
     assert prop.transform('red') == "#ff0000"
     assert prop.transform('RED') == "#ff0000"
     assert prop.transform('rgba(255, 0, 0, 0.1)') == "#ff0000"
     assert prop.transform('rgb(255, 0, 0)') == "#ff0000"
     assert prop.transform(RGB(255, 0, 0)) == "#ff0000"
Esempio n. 12
0
def bokeh_transcript_scatter_plot(title,
                                  transcript_count_list_dict,
                                  transcript_assembly,
                                  color_dict,
                                  align_to,
                                  span_size,
                                  index_filter,
                                  min_count=0,
                                  max_count=1000,
                                  save_plot=True):
    logging.getLogger(config.FIVEPSEQ_PLOT_LOGGER).info(
        "Plotting transcript specific counts. %d filtered transcript indices specified"
        % len(index_filter))
    output_file(title + "_minCount-" + str(min_count) + "_maxCount-" +
                str(max_count) + ".html",
                mode="cdn")

    p = figure(title=title,
               y_range=(0, 200),
               x_axis_label="position from %s" % align_to,
               y_axis_label="5'seq read counts")
    # try setting range limits - p = figure(x_range=[0, 10], y_range=(10, 20))

    for key in transcript_count_list_dict.keys():
        count_vector_list = transcript_count_list_dict.get(key)
        if index_filter is None:
            index_filter = range(0, len(count_vector_list))
        for index in index_filter:
            count_vector = count_vector_list[index]
            if min_count < sum(count_vector) < max_count:
                count_series = CountManager.count_vector_to_series(
                    count_vector, align_to, tail=span_size)
                transcript = transcript_assembly.ID[index].split(
                    "transcript:")[1]
                gene = transcript_assembly.gene[index].split("gene:")[1]

                c = color_dict.get(key)
                if c is None:
                    logging.getLogger(config.FIVEPSEQ_PLOT_LOGGER).warning(
                        "Color not set for sample %s" % key)
                    c = cl.scales['9']['qual']['Set3'][1]
                line = p.line(count_series.index,
                              count_series.values,
                              legend=key,
                              line_color=RGB(c[0], c[1], c[2]))

                p.add_tools(
                    HoverTool(tooltips=[('position', '@x'), ('count', '@y'),
                                        ['transcript', transcript],
                                        ['gene', gene]],
                              renderers=[line]))
    p.legend.click_policy = "hide"
    if save_plot:
        show(p)
    return p
Esempio n. 13
0
def scatter_hist2d(p,
                   x,
                   y,
                   bins=10,
                   range=None,
                   density=False,
                   weights=None,
                   colormap=mpl.cm.get_cmap('jet'),
                   dens_func=None,
                   is_radial_var=[False, False],
                   **kwargs):
    if (is_radial_var[0]):
        x = x * x
    if (is_radial_var[1]):
        y = y * y
    h, xe, ye = np.histogram2d(x,
                               y,
                               bins=bins,
                               range=range,
                               density=density,
                               weights=weights)
    dens = map_hist(x, y, h, bins=(xe, ye))
    if (is_radial_var[0]):
        x = np.sqrt(x)
        xe = np.sqrt(xe)
    if (is_radial_var[1]):
        y = np.sqrt(y)
        ye = np.sqrt(ye)
    if dens_func is not None:
        dens = dens_func(dens)
    iorder = slice(None)  # No ordering by default
    iorder = np.argsort(dens)
    x = x[iorder]
    y = y[iorder]
    dens = dens[iorder]

    colors = [
        "#%02x%02x%02x" % (int(r), int(g), int(b))
        for r, g, b, _ in 255 * colormap(mpl.colors.Normalize(vmin=0.0)(dens))
    ]
    p.scatter(x, y, line_color=None, fill_color=colors)

    palette = [
        RGB(*tuple(rgb)).to_hex()
        for rgb in (255 * colormap(np.arange(256))).astype('int')
    ]
    color_mapper = LinearColorMapper(palette=palette,
                                     low=0.0,
                                     high=np.max(dens))
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')
def _create_colours(light_colours=False) -> np.ndarray:
    saturation = 100
    luminance = 60
    if light_colours:
        saturation = 80
        luminance = 80
    colours = []
    for hue in range(360):
        r, g, b = hpluv_to_rgb((hue, saturation, luminance))
        colours.append(RGB(r * 256, g * 256, b * 256))
    return np.array(colours)
Esempio n. 15
0
def _get_colors(experiments):
    n = len(experiments)

    color_range_rgb = np.arange(1, 256)
    red = np.random.choice(color_range_rgb, size=n, replace=False)
    green = np.random.choice(color_range_rgb, size=n, replace=False)
    blue = np.random.choice(color_range_rgb, size=n, replace=False)

    colors = {}
    for i, (r, g, b) in enumerate(zip(red, green, blue)):
        colors[experiments[i]] = RGB(r, g, b)
    return colors
Esempio n. 16
0
    def color_by_self_citation(self):
        """
        if the citing article was written by the same authors
        as the original paper (self.first_authors_ids), color the node in red.
        """
        # define colors
        red = RGB(r=255, g=0, b=0)
        green = RGB(r=0, g=255, b=0)

        # red color for the self.first_authors_ids nodes in the authors graph
        for node in list(self.A):
            try:
                self.A.nodes[node]['color'] = red if self.A.nodes[node][
                    'authorId'] in self.first_authors_ids else green
            except KeyError:
                self.A.nodes[node]['color'] = green

        # color first node red
        self.G.nodes[self.first_doi]['color'] = red
        # color red nodes if the base autor also wrote the citing article
        for node in list(self.G):
            neighbors = self.G.neighbors(node)
            for neighbor in neighbors:
                if any(x in self.first_authors_ids
                       for x in self.G.nodes[neighbor]['authorIds']):
                    self.G.nodes[neighbor]['color'] = red
                else:
                    self.G.nodes[neighbor]['color'] = green

        # color the edges connecting the nodes with same authorIds as in the first paper
        for start_node, end_node, _ in self.G.edges(data=True):
            condition = (any(
                x in self.first_authors_ids
                for x in self.G.nodes[end_node]["authorIds"])) and (any(
                    x in self.first_authors_ids
                    for x in self.G.nodes[start_node]["authorIds"]))

            self.G.adj[start_node][end_node][0][
                'edge_color'] = red if condition else green
Esempio n. 17
0
def scatter_color(p,
                  pmd,
                  x,
                  y,
                  color_var='density',
                  bins=10,
                  weights=None,
                  colormap=None,
                  **kwargs):

    force_zero = False

    if (color_var == 'density'):
        h, xe, ye = np.histogram2d(x, y, bins=bins, weights=weights)
        c = map_hist(x, y, h, bins=(xe, ye))
        force_zero = True
        title_str = 'Density'
    else:
        q = pmd.weight
        (c, c_units, c_scale, avgc, avgc_units,
         avgc_scale) = scale_mean_and_get_units(
             getattr(pmd, color_var),
             pmd.units(color_var).unitSymbol,
             subtract_mean=True,
             weights=q)
        title_str = f'{color_var} ({c_units})'

    if (colormap is None):
        colormap = mpl.cm.get_cmap('jet')

    vmin = np.min(c)
    vmax = np.max(c)
    if (force_zero):
        vmin = 0.0

    colors = [
        "#%02x%02x%02x" % (int(r), int(g), int(b)) for r, g, b, _ in 255 *
        colormap(mpl.colors.Normalize(vmin=vmin, vmax=vmax)(c))
    ]
    p.scatter(x, y, line_color=None, fill_color=colors)

    palette = [
        RGB(*tuple(rgb)).to_hex()
        for rgb in (255 * colormap(np.arange(256))).astype('int')
    ]
    color_mapper = LinearColorMapper(palette=palette, low=vmin, high=vmax)
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')
def view_alignment(ids, seqs, chromPoints, side, fontsize="9pt", plot_width=800):
	"""Bokeh sequence alignment view"""
	text = [i for s in list(seqs) for i in s]
	clrs = {'T':RGB(153, 204, 153), 'A':RGB(255, 153, 153), 'G':RGB(255, 219, 153), 'C':RGB(153, 153, 255), '-':'white', 'N':'white', '*':'white'}
	colors = [clrs[i] for i in text]
	N = len(seqs[0])/2
	center = int(chromPoints[2])
	x = np.arange(center-N,center+N)
	y = np.arange(0,len(seqs),1)
	xx, yy = np.meshgrid(x, y)
	gx = xx.ravel()
	gy = yy.flatten()
	source = ColumnDataSource(dict(x=gx+0.5, y=gy, recty=gy+0.5, rectx1=gx, rectx2=gx+1, text=text, colors=colors))
	plot_height = len(seqs)*20+200
	view_range = (center-20, center+20)
	p1 = figure(title=' '.join(chromPoints), plot_width=plot_width, plot_height=plot_height,
				x_range=view_range, y_range=ids, tools="xpan,reset",
				min_border_bottom=100, min_border_top=100, toolbar_location='below')#, lod_factor=1)
	glyph = Text(x="x", y="y", text="text", text_align='center',text_color="black",
				 text_font="monospace",text_font_size=fontsize)
	p1.segment(x0='rectx1', y0='recty', x1='rectx2',
			   y1='recty', color="colors", line_width=14, source=source)
	p1.add_glyph(source, glyph)
	breakLine = Span(location=int(chromPoints[2]), dimension='height', line_color='red', line_width=2)
	p1.renderers.extend([breakLine])
	p1.grid.visible = False
	p1.add_layout(LinearAxis(formatter=BasicTickFormatter(use_scientific=False), major_label_orientation = pi/4), 'above')
	p1.xaxis.major_label_text_font_style = "bold"
	p1.yaxis.minor_tick_line_width = 0
	p1.yaxis.major_tick_line_width = 0
	p1.below[0].formatter.use_scientific = False
	p1.xaxis.major_label_orientation = pi/4
	if side == 'left': p1.name = 'pl'
	else:
		p1.name = 'pr'
		p1.min_border_left = 10
		p1.yaxis.visible=False
	return p1, source
Esempio n. 19
0
    def test_valid(self):
        prop = bcpc.Color()
        assert prop.is_valid(None)

        assert prop.is_valid((0, 127, 255))
        assert prop.is_valid((0, 127, 255, 1.0))

        assert prop.is_valid("#00aaff")
        assert prop.is_valid("#00AAFF")
        assert prop.is_valid("#00AaFf")

        assert prop.is_valid("blue")
        assert prop.is_valid("BLUE")

        assert prop.is_valid(RGB(10, 20, 30))
Esempio n. 20
0
def generate_mainDictionary(filename):
    results = read_pickle(filename)
    coordinates = getCoordinates()
    rating = getRatings()
    data = dict(lat=[], lon=[], color=[], name=[], rating=[])
    limit = 0
    for name in results:
        red, green, blue = results[name]['color'][0], results[name]['color'][
            1], results[name]['color'][2]
        data['lat'].append(coordinates[name]['location'][0])
        data['lon'].append(coordinates[name]['location'][1])
        data['color'].append(RGB(red, green, blue))
        data['name'].append(name)
        data['rating'].append(rating[name])
        limit += 1
    return data
Esempio n. 21
0
def bokeh_aa_pause_scatterplot(title, amino_acid_df):
    p = figure(title=title,
               x_axis_label="distance from amino acid",
               y_axis_label="5'seq read counts")

    for aa in amino_acid_df.index:
        c = codons.Codons.AMINO_ACID_COLORS.get(aa)
        line = p.line(amino_acid_df.columns,
                      amino_acid_df.loc(aa, ),
                      legend=aa,
                      line_color=RGB(c[0], c[1], c[2]))
        hover = HoverTool(tooltips=[('distance', '@x'), ('count', '@y')],
                          renderers=[line])
        p.add_tools(hover)

    p.legend.click_policy = "hide"
    return p
Esempio n. 22
0
    def test_valid(self) -> None:
        prop = bcpc.Color()

        assert prop.is_valid((0, 127, 255))
        assert prop.is_valid((0, 127, 255, 1.0))

        assert prop.is_valid("#00aaff")
        assert prop.is_valid("#00AAFF")
        assert prop.is_valid("#00AaFf")

        assert prop.is_valid("blue")
        assert prop.is_valid("BLUE")

        assert prop.is_valid('rgb(10, 20, 30)')
        assert prop.is_valid('rgba(10, 20, 30, 1)')
        assert prop.is_valid('rgba(10, 20, 30, 0.5)')

        assert prop.is_valid(RGB(10, 20, 30))
Esempio n. 23
0
def myColorBar(pw=75, ph=300, tt="colors"):
    from bokeh.models import CategoricalAxis
    corarr = [-1.0, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
    colors = [
        RGB(255 * (1 - x) / 2, 255 * (1 + x) / 2, 0, 0.7) for x in corarr
    ]
    colNames = ["color"]
    rownames = [str(x) for x in corarr]
    x = [c for r in rownames for c in colNames]
    y = [r for r in rownames for c in colNames]
    p = figure(title=tt,
               x_range=colNames,
               y_range=rownames,
               plot_width=pw,
               plot_height=ph,
               toolbar_location=None)
    p.rect(x, y, color=colors, width=1, height=1)
    p.xaxis.major_label_orientation = 3.14159 / 2
    return p
Esempio n. 24
0
def cm2palette(cmapName):
    """ Convert certain matplotlib colormap (cm) to bokeh palette.

    **Parameter**\n
    cmapName: str
        Name of the colormap/palette.

    **Return**\n
    palette: list
        List of colors in hex representation (a bokoeh palette).
    """

    if cmapName in bp.all_palettes.keys():
        palette = eval('bp.' + cmapName)

    else:
        mpl_cm_rgb = (255 * eval('cm.' + cmapName)(range(256))).astype('int')
        palette = [RGB(*tuple(rgb)).to_hex() for rgb in mpl_cm_rgb]

    return palette
Esempio n. 25
0
def myCorrelationPlot(df, pw=300, ph=300, tt="correlations"):
    colNames = df.columns.tolist()
    rownames = df.index.tolist()
    x = [c for r in rownames for c in colNames]
    y = [r for r in rownames for c in colNames]
    corarr = [df[c][r] for r in rownames for c in colNames]
    colors = [
        RGB(255 * (1 - x) / 2, 255 * (1 + x) / 2, 0, 0.7) for x in corarr
    ]
    p = figure(title=tt,
               x_range=colNames,
               y_range=rownames,
               plot_width=pw,
               plot_height=ph,
               toolbar_location="right")
    p.rect(x, y, color=colors, width=1, height=1)
    p.xaxis.major_label_orientation = 3.14159 / 2
    c = myColorBar(75, ph)
    output_file("correlation.html")
    show((row(p, c)))
    out.reset_output()
Esempio n. 26
0
def get_bokeh_palette(cmap):
    """Creates a color palette compatible with Bokeh
    from a matplotlib cmap name.

    Parameters
    ----------
    cmap : string
        Name of a matplotlib colormap

    Returns
    -------
    list
        A series of hex colour codes generated from
        the matplotlib colormap
    """
    from bokeh.colors import RGB
    from matplotlib import cm

    # Solution adapted from
    # https://stackoverflow.com/questions/31883097/elegant-way-to-match-a-string-to-a-random-color-matplotlib
    m_RGB = (255 * plt.get_cmap(cmap)(range(256))).astype("int")
    return [RGB(*tuple(rgb)).to_hex() for rgb in m_RGB]
Esempio n. 27
0
    def get_color_dash(self, did, cid):
        # First, check if we have the constructor in the csv
        if cid in constructor_colors.index.values and not self.driver_only_mode:
            color = constructor_colors.loc[cid]
            color = RGB(color["R"], color["G"], color["B"])
        else:
            if cid in self.constructor_color_map.keys():
                color = self.constructor_color_map[cid]
            else:
                color = self.colors.__next__()
                self.constructor_color_map[cid] = color

        # Now get the line dash
        if did is None:
            dash = "solid"
        elif did in self.driver_dashes_map.keys():
            dash = self.driver_dashes_map[did]
        else:
            dash = self.constructor_dashes_map[cid].__next__()
            self.driver_dashes_map[did] = dash

        return color, dash
Esempio n. 28
0
r_Greys256 = list(reversed(Greys256))

# The remote_jupyter_proxy_url function is required when running on a BinderHub instance.
# Use the set_default_jupyter_url function to set the hostname of your instance after it has
# started. The current value is the most frequent result when launching from mybinder.org.
# Change to another value if running Binder host is not this most common one:
# set_default_jupyter_url('https://datahub.berkeley.edu/')

# Or if you are running locally (on localhost), ignore the previous line and set
# `local_notebook` to True:
# local_notebook = False

output_notebook()

params = {
    'low_thresh_color': RGB(0, 0, 255, 0.25),
    'low_thresh_power': 6.0,
    'window_size': 5.0,
    'spslice_lastx': 0.0,
    'downsample_rate': 20000
}
snd = None
wavname = None
sgrams = []
spslice = None

# Info for loading/caching audio files
tempdirobj = TemporaryDirectory()
tempdir = tempdirobj.name
resource_url = 'https://linguistics.berkeley.edu/phonapps/resource/'
manifest_name = 'manifest.yaml'
Esempio n. 29
0
output_file('haiti_analysis.html')

x_scale = 14.1
y_scale = 10

# Suppose we have the points distributed in a square grid of size 'x', so
# there are 'x*x' elements in total
x = []
y = []
color = []

side = 7
for i in range(side**2):
    x.append((i // side) + 4)
    y.append((i % side) + 2)
    color.append(RGB(0, 0, 0))

# Create some random wind data for the points
wind = np.random.rand(side**2) * 100

source = ColumnDataSource(data=dict(x=x, y=y, color=color, wind=wind))

# To keep the image centered with its aspect ratio
y_offset = (x_scale - y_scale) / 2

# Create the figure
p = figure(x_range=(0, x_scale), y_range=(0 - y_offset, y_scale + y_offset))
p.title.text = 'Haiti case study'
p.toolbar.active_drag = None  # Disable dragging
p.toolbar.logo = None
p.toolbar_location = None
Esempio n. 30
0
from bokeh.io import output_file, show, curdoc
from bokeh.models import (GMapPlot, GMapOptions, ColumnDataSource, CustomJS,
                          Circle, Range1d, PanTool, WheelZoomTool,
                          BoxSelectTool)
from bokeh.layouts import widgetbox, column, row
from bokeh.models.widgets import RadioButtonGroup, Select, Button
from bokeh.models.callbacks import CustomJS
from bokeh.colors import RGB
from dataProcessing import *
from bokeh.models import HoverTool
from bokeh.plotting import figure, show, output_file
from bokeh.models import Legend

severity1 = generate_severityDictionary('1', RGB(255, 200, 0))
severity2 = generate_severityDictionary('2', RGB(255, 100, 0))
severity3 = generate_severityDictionary('3', RGB(255, 0, 0))
general = generate_mainDictionary(
    'processed_data/restaurant_violation_percentage.pickle')
Italian = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                      'Italian', RGB(51, 51, 255))
print('Italian Works')
Mexican = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                      'Mexican', RGB(100, 255, 0))
Chinese = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                      'Chinese', RGB(127, 0, 255))
Seafood = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                      'Seafood', RGB(255, 51, 51))
Sandwiches = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                         'Sandwiches', RGB(0, 153, 0))
Indian = generate_foodtypeDictionary('processed_data/foodtype.pickle',
                                     'Indian', RGB(255, 102, 178))