Ejemplo n.º 1
0
    def __init__(self):
        self.StrCapabilityPlot = figure(plot_width=580, plot_height=595,
                                     tools='', title="Storage capability curve")

        self.StrCapabilityPlot.xaxis.axis_label = 'Q [p.u]'
        self.StrCapabilityPlot.yaxis.axis_label = 'P [p.u]'
        self.StrCapabilityPlot.toolbar.logo = None
        self.StrCapabilityPlot.toolbar_location = None
        self.StrCapabilityPlot.y_range = Range1d(*(-1.15, 1.15))
        self.StrCapabilityPlot.x_range = Range1d(*(-1.15, 1.15))
        self.StrCapabilityPlot.circle(x=[0], y=[0], radius=1.00, line_color ="navy", fill_color=None, size= 1)
        self.StrCapabilityPlot.add_layout(Arrow(end=VeeHead(size=10), line_color="black",
                                                x_start=0.0, y_start=-1.1, x_end=0, y_end=1.1))
        self.StrCapabilityPlot.add_layout(Arrow(end=VeeHead(size=10), line_color="black",
                                                x_start=-1.1, y_start=0, x_end=1.1, y_end=0))

        self.StoragecurveDatasource  = ColumnDataSource(data=dict(x0=[], x1=[], x2=[], y0=[], y1=[], y2=[]))

        self.StrCapabilityPlot.line('x0', 'y0', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")
        self.StrCapabilityPlot.line('x1', 'y1', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")
        self.StrCapabilityPlot.line('x2', 'y2', source=self.StoragecurveDatasource, line_width=1, line_alpha=1.0,
                                    line_color="red")

        Storagewidgetbox = self.createStoragewidgetbox()

        PVsettingsLayout = column(self.StrCapabilityPlot, Storagewidgetbox, width=800)
        self.final_layout = PVsettingsLayout

        for w in [self.kWratingSlider, self.PFslider]:
            w.on_change('value', self.updateStoragecurves)

        return
Ejemplo n.º 2
0
def generate(data, incoming_arrow_data, outgoing_arrow_data):
    plot = figure(title="", x_axis_label='', y_axis_label='', sizing_mode="scale_height")
    plot.xgrid.grid_line_color            = None
    plot.ygrid.grid_line_color            = None
    plot.xaxis.major_tick_line_color      = None
    plot.xaxis.minor_tick_line_color      = None
    plot.xaxis.major_label_text_color     = '#ffffff'
    plot.xaxis.major_label_text_font_size = '0px'
    plot.xaxis.axis_line_color            = "#ffffff"
    plot.yaxis.major_tick_line_color      = None
    plot.yaxis.minor_tick_line_color      = None
    plot.yaxis.major_label_text_color     = '#ffffff'
    plot.yaxis.major_label_text_font_size = '0px'
    plot.yaxis.axis_line_color            = "#ffffff"
    plot.toolbar.logo                     = None
    plot.toolbar_location                 = None

    source = ColumnDataSource(data)
    mapper = LinearColorMapper(palette=colors_hex, low=0, high=len(colors_hex))
    labels = LabelSet(x="x", y="y", text="value", text_align="center", text_font="helvetica", text_font_size="16pt", x_offset=0, y_offset=-12, source=source, render_mode='canvas')
    plot.rect(x="x", y="y", width=1, height=1, source=source, fill_color={'field': 'value', 'transform': mapper}, line_color="#000000", line_alpha=0)
    plot.add_layout(labels)
    
    if incoming_arrow_data:
        incoming_arrow_source = ColumnDataSource(incoming_arrow_data)
        incoming_arrows = Arrow(end=VeeHead(fill_color="gray"), source=incoming_arrow_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color="gray")
        plot.add_layout(incoming_arrows)

    if outgoing_arrow_data:
        outgoing_arrow_source = ColumnDataSource(outgoing_arrow_data)
        outgoing_arrows = Arrow(end=VeeHead(fill_color="black"), source=outgoing_arrow_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color="black")
        plot.add_layout(outgoing_arrows)

    return plot
Ejemplo n.º 3
0
    def _setup_graph_renderer(self, circle_size):
        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(
            list(self.graph.vertices.keys()), "index")
        graph_renderer.node_renderer.data_source.add(self._get_random_colors(),
                                                     "color")
        graph_renderer.node_renderer.glyph = Circle(size=circle_size,
                                                    fill_color="color")
        graph_renderer.edge_renderer.data_source.data = self._get_edge_indexes(
        )
        self.randomize()
        for i in range(
                len(graph_renderer.edge_renderer.data_source.data["start"])):
            self.plot.add_layout(
                Arrow(
                    end=VeeHead(size=20, fill_color="black"),
                    x_start=self.pos[graph_renderer.edge_renderer.data_source.
                                     data["start"][i]][0],
                    y_start=self.pos[graph_renderer.edge_renderer.data_source.
                                     data["start"][i]][1],
                    x_end=self.pos[graph_renderer.edge_renderer.data_source.
                                   data["end"][i]][0],
                    y_end=self.pos[graph_renderer.edge_renderer.data_source.
                                   data["end"][i]][1],
                ))

        graph_renderer.layout_provider = StaticLayoutProvider(
            graph_layout=self.pos)
        self.plot.renderers.append(graph_renderer)
        self._get_labels()
Ejemplo n.º 4
0
def test_arrow(output_file_url, selenium, screenshot):

    # Have to specify x/y range as labels aren't included in the plot area solver
    plot = figure(height=HEIGHT, width=WIDTH, x_range=(0,10), y_range=(0,10), tools='')

    arrow1 = Arrow(x_start=1, y_start=3, x_end=6, y_end=8,
                   line_color='green', line_alpha=0.7,
                   line_dash='8 4', line_width=5, end=OpenHead()
                   )
    arrow1.end.line_width=8

    arrow2 = Arrow(x_start=2, y_start=2, x_end=7, y_end=7,
                   start=NormalHead(), end=VeeHead()
                   )
    arrow2.start.fill_color = 'indigo'
    arrow2.end.fill_color = 'orange'
    arrow2.end.size = 50

    plot.add_layout(arrow1)
    plot.add_layout(arrow2)

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)

    # Take screenshot
    assert screenshot.is_valid()
Ejemplo n.º 5
0
def arrows(pos_i=None, pos_f=None, p=None, names=None, color='black'):

    if pos_i is None:
        pos_i = np.zeros_like(pos_f)

    for i, (x0, y0, xf, yf) in enumerate(np.hstack((pos_i, pos_f))):
        p.add_layout(
            Arrow(end=VeeHead(fill_color=color, line_color=color, size=10),
                  x_start=x0,
                  y_start=y0,
                  x_end=xf,
                  y_end=yf))

        if names is not None:
            vec_norm = np.sqrt((xf - x0)**2 + (yf - y0)**2)

            labels = Label(x=xf,
                           y=yf,
                           text=names[i],
                           text_color=color,
                           x_offset=vec_norm * 0.2,
                           y_offset=vec_norm * 0.2)

            p.add_layout(labels)

    return p
Ejemplo n.º 6
0
def notebook_bokeh(stcs):
    patch_xs = parse_s_region(stcs)['ra']
    patch_ys = parse_s_region(stcs)['dec']

    p = figure(plot_width=700,
               x_axis_label="RA (deg)",
               y_axis_label="Dec (deg)")

    data = {'x': [patch_xs], 'y': [patch_ys]}
    p.patches('x',
              'y',
              source=data,
              fill_alpha=0.1,
              line_color="black",
              line_width=0.5)

    p.add_layout(
        Arrow(end=VeeHead(line_color="black", line_width=1),
              line_width=2,
              x_start=patch_xs[0],
              y_start=patch_ys[0],
              x_end=patch_xs[1],
              y_end=patch_ys[1]))

    p.y_range.flipped = True

    output_notebook()
    show(p)
Ejemplo n.º 7
0
def setup_timeline_backend_parts(plot: figure,
                                 desc_label_source: ColumnDataSource) -> None:
    """

    :param plot:
    :param desc_label_source:
    :return:
    """
    start_date, end_date = plot.x_range.start, plot.x_range.end
    arrow_x = start_date + datetime.timedelta(days=180)

    # 補助線を引く
    plot.line([start_date, end_date], [1, 1], line_width=3, line_color='pink')
    plot.line([start_date, end_date], [0.5, 0.5],
              line_width=3,
              line_dash='dotted',
              line_color='pink')
    plot.line([start_date, end_date], [1.5, 1.5],
              line_width=3,
              line_dash='dotted',
              line_color='pink')

    # 矢印を表示する
    plot.add_layout(
        Arrow(end=VeeHead(size=15),
              line_color='black',
              x_start=arrow_x,
              y_start=1.4,
              x_end=arrow_x,
              y_end=1.1))
    plot.add_layout(
        Arrow(end=VeeHead(size=15),
              line_color='black',
              x_start=arrow_x,
              y_start=0.9,
              x_end=arrow_x,
              y_end=0.6))

    plot.text(source=desc_label_source,
              x='x',
              y='y',
              text='text',
              text_font_size='size',
              text_alpha=0.8)
def add_arrows(canvas, branch, color, pf_threshold=0, dist_threshold=0, n=1):
    """Add addorws for powerflow to figure.

    :param bokeh.plotting.figure.Figure canvas: canvas to plot arrows onto.
    :param pandas.DataFrame branch: data frame containing:
        'pf', 'dist', 'arrow_size', 'from_x', 'from_y', 'to_x', 'to_y'.
        x/y coordinates for to/from can be obtained from lat/lon coordinates
        using :func:`postreise.plot.projection_helpers.project_branch`.
    :param str color: arrow line color.
    :param int/float pf_threshold: minimum power flow for a branch to get arrow(s).
    :param int/float pf_threshold: minimum distance for a branch to get arrow(s).
    :param int n: number of arrows to plot along each branch.
    """
    positive_arrows = branch.loc[(branch.pf > pf_threshold)
                                 & (branch.dist > dist_threshold)]
    negative_arrows = branch.loc[(branch.pf < -1 * pf_threshold)
                                 & (branch.dist > dist_threshold)]
    # Swap direction of negative arrows
    negative_arrows = negative_arrows.rename(columns={
        "from_x": "to_x",
        "to_x": "from_x",
        "to_y": "from_y",
        "from_y": "to_y"
    })
    # Finally, plot arrows
    arrows = pd.concat([positive_arrows, negative_arrows])
    for i in range(n):
        start_fraction = i / n
        end_fraction = (i + 1) / n
        arrows.apply(
            lambda a: canvas.add_layout(
                Arrow(
                    end=VeeHead(
                        line_color="black",
                        fill_color="gray",
                        line_width=2,
                        fill_alpha=0.5,
                        line_alpha=0.5,
                        size=a["arrow_size"],
                    ),
                    x_start=(a["from_x"] +
                             (a["to_x"] - a["from_x"]) * start_fraction),
                    y_start=(a["from_y"] +
                             (a["to_y"] - a["from_y"]) * start_fraction),
                    x_end=(a["from_x"] +
                           (a["to_x"] - a["from_x"]) * end_fraction),
                    y_end=(a["from_y"] +
                           (a["to_y"] - a["from_y"]) * end_fraction),
                    line_color=color,
                    line_alpha=0.7,
                )),
            axis=1,
        )
Ejemplo n.º 9
0
def update() -> None:
    if toggles['pause'].active:
        return

    ds_now = data_sources['now'].data
    ds_history = data_sources['history'].data

    if ds_now['epoch'][0] + 1 > sliders['max_epoch'].value:
        return

    batches_x, batches_y = create_batches()

    for batch_x, batch_y in zip(batches_x, batches_y):
        weight_previous = tensors['weight_model']
        weight_updated = gradient_descent(batch_y, batch_x, weight_previous)

        arrow_head = VeeHead(size=5,
                             fill_color='darkgrey',
                             line_color='darkgrey')
        arrow = Arrow(end=arrow_head,
                      line_color='darkgrey',
                      x_start=ds_history['weight_0'][-1],
                      y_start=ds_history['weight_1'][-1],
                      x_end=weight_updated.numpy()[0, 0],
                      y_end=weight_updated.numpy()[1, 0])
        fig.add_layout(arrow)

        loss = loss_function(tensors['y_true'],
                             pass_neuron(tensors['X'],
                                         weight_updated)).numpy()[0]

        ds_history['weight_0'] += [weight_updated.numpy()[0, 0]]
        ds_history['weight_1'] += [weight_updated.numpy()[1, 0]]

        ds_now['loss'] = [loss]
        ds_now['weight_0'] = [weight_updated.numpy()[0, 0]]
        ds_now['weight_1'] = [weight_updated.numpy()[1, 0]]

        tensors['weight_model'] = weight_updated

    ds_now['epoch'] = [ds_now['epoch'][0] + 1]

    for arrow in fig.center[2:-sliders['num_samples'].value]:
        arrow.line_color = 'lightgrey'
        arrow.end.fill_color = 'lightgrey'
        arrow.end.line_color = 'lightgrey'

    return
Ejemplo n.º 10
0
 def create_plot(self):
     super().create_plot()
     self.plot.renderers[0].edge_renderer.data_source.data[
         'edge_data'] = self.y
     G = nx.convert_node_labels_to_integers(self.G)
     layout_coords = pd.DataFrame(
         [[
             self.layout[x1][0], self.layout[x1][1], self.layout[x2][0],
             self.layout[x2][1]
         ] for (x1, x2) in G.edges()],
         columns=['x_start', 'y_start', 'x_end', 'y_end'])
     layout_coords['x_end'] = (
         layout_coords['x_end'] -
         layout_coords['x_start']) / 2 + layout_coords['x_start']
     layout_coords['y_end'] = (
         layout_coords['y_end'] -
         layout_coords['y_start']) / 2 + layout_coords['y_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'x_start'] = layout_coords['x_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'y_start'] = layout_coords['y_start']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'x_end'] = layout_coords['x_end']
     self.plot.renderers[0].edge_renderer.data_source.data[
         'y_end'] = layout_coords['y_end']
     self.plot.renderers[0].edge_renderer.glyph = MultiLine(
         line_color=linear_cmap('edge_data', self.palette, self.lo,
                                self.hi),
         line_width=5)
     if self.show_bar:
         cbar = ColorBar(color_mapper=LinearColorMapper(
             palette=self.palette, low=self.lo, high=self.hi),
                         ticker=BasicTicker(),
                         title=self.desc)
         self.plot.add_layout(cbar, 'right')
     arrows = Arrow(end=VeeHead(size=8),
                    x_start='x_start',
                    y_start='y_start',
                    x_end='x_end',
                    y_end='y_end',
                    line_width=0,
                    source=self.plot.renderers[0].edge_renderer.data_source)
     self.plot.add_layout(arrows)
     # self.plot.tooltips.append((self.desc, '@edge_data'))
     return self.plot
Ejemplo n.º 11
0
    def _setup_graph_renderer(self, circle_size):
        # define function to render graph
        graph_renderer = GraphRenderer()

        graph_renderer.node_renderer.data_source.add(
            list(self.graph.vertices.keys()), "index"
        )
        # adds color randomizer
        graph_renderer.node_renderer.data_source.add(self._get_random_colors(), "color")
        # gives each node the shape of a circle with it's specified size and random color
        graph_renderer.node_renderer.glyph = Circle(
            size=circle_size, fill_color="color"
        )
        # adds function to get edge indexes
        graph_renderer.edge_renderer.data_source.data = self._get_edge_indexes()
        # randomize each new graph
        self.randomize()

        for i in range(len(graph_renderer.edge_renderer.data_source.data["start"])):
            # add arrows from starting node to end node
            self.plot.add_layout(
                Arrow(
                    # Arrow head size and color
                    end=VeeHead(size=20, fill_color="black"),
                    # arrow start at x, y pos of vertex
                    x_start=self.pos[
                        graph_renderer.edge_renderer.data_source.data["start"][i]
                    ][0],
                    y_start=self.pos[
                        graph_renderer.edge_renderer.data_source.data["start"][i]
                    ][1],
                    x_end=self.pos[
                        graph_renderer.edge_renderer.data_source.data["end"][i]
                    ][0],
                    y_end=self.pos[
                        graph_renderer.edge_renderer.data_source.data["end"][i]
                    ][1],
                )
            )

        graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=self.pos)
        self.plot.renderers.append(graph_renderer)
        self._get_labels()
Ejemplo n.º 12
0
from bokeh.plotting import figure, output_file, show
from bokeh.models import Arrow, OpenHead, NormalHead, VeeHead

output_file("arrow.html", title="arrow.py example")

p = figure(plot_width=600,
           plot_height=600,
           x_range=(-0.1, 1.1),
           y_range=(-0.1, 0.8))

p.circle(x=[0, 1, 0.5],
         y=[0, 0, 0.7],
         radius=0.1,
         color=["navy", "yellow", "red"],
         fill_alpha=0.1)

p.add_layout(Arrow(end=OpenHead(), x_start=0, y_start=0, x_end=1, y_end=0))
p.add_layout(
    Arrow(end=NormalHead(), x_start=1, y_start=0, x_end=0.5, y_end=0.7))
p.add_layout(Arrow(end=VeeHead(), x_start=0.5, y_start=0.7, x_end=0, y_end=0))

show(p)
Ejemplo n.º 13
0
 def plot(self):
     lifemap = figure(plot_width=750,
                      plot_height=570,
                      toolbar_location='below')
     lifemap.xgrid.visible = False
     lifemap.ygrid.visible = False
     lifemap.xaxis.visible = False
     lifemap.yaxis.visible = False
     self.network_reach.network.plot(lifemap)
     reachids = list(np.array(self.reach_history).T[2])
     pointx, pointy = list(
         np.array([
             self.network_reach.network.reach_with_id(id).midpoint
             for id in reachids
         ]).T)
     source = ColumnDataSource({
         'xs': pointx,
         'ys': pointy,
         'reach_id': reachids
     })
     lifemap.scatter('xs',
                     'ys',
                     source=source,
                     name='scatterplot',
                     marker='circle',
                     size=10,
                     line_color='#cb7723',
                     fill_color='#fcb001',
                     alpha=1.0)
     hover_tooltips = [('reach', '@reach_id')]
     lifemap.add_tools(
         HoverTool(tooltips=hover_tooltips, names=['scatterplot']))
     lifemap.add_layout(
         Label(x=30,
               y=700,
               x_units='screen',
               y_units='screen',
               text="Fish ID {0}".format(self.unique_id)))
     title, lifetext, lifesource = self.activity_descriptors()
     lifemap.title.text = title
     lifemap.title.text_font_size = "10px"
     lifemap.toolbar.logo = None
     for i in range(1, len(pointx)):
         lifemap.add_layout(
             Arrow(end=VeeHead(size=10,
                               line_color='#cb7723',
                               fill_color='#fcb001'),
                   line_color='#fcb001',
                   x_start=pointx[i - 1],
                   y_start=pointy[i - 1],
                   x_end=pointx[i],
                   y_end=pointy[i]))
     columns = [
         TableColumn(field="age_weeks", title="Week", width=40),
         TableColumn(field="age_years", title="Age", width=45),
         TableColumn(field="life_event", title="Life Event", width=315)
     ]
     data_table = DataTable(source=lifesource,
                            columns=columns,
                            row_headers=False,
                            width=400,
                            height=600)
     lyt = row([
         data_table, lifemap,
         column([self.plot_growth(),
                 self.plot_temperature()])
     ],
               sizing_mode='fixed')
     return lyt
Ejemplo n.º 14
0
                     size=3 * s, angle=0, fill_alpha=0.9, line_color=None, color='firebrick')

    # arrow

    if parameters["windQuad"][case] == -3:
        lw = 0
        la = 0.1
    elif parameters["windQuad"][case] == -2:
        lw = 4
        la = 1
    else:
        lw = 10
        la = 1
    # print 'le is',lw
    if addArrow:
        fig.add_layout(Arrow(end=VeeHead(size=20), line_color="red", line_alpha=la,

                             x_start=xs, y_start=ys, line_width=lw,
                             x_end=xs + r * np.cos(np.deg2rad(theta)), y_end=ys + r * np.sin(np.deg2rad(theta))))


    return fig


def bokehQuadPlot(df=None,  parameters=None, fig=None,
              TOOLS="pan,crosshair,wheel_zoom\
              ,box_zoom,reset,box_select,lasso_select,undo,redo,save",
              x_range=(506, 526), y_range=(506, 526),
              output_backend="webgl", plot_width=500, plot_height=500,
              s=4, title=None, addOdour=True,
              addSmallTit=True, addStart=True, addArrow=True,
Ejemplo n.º 15
0
def makehtml_model(html_model_template, event, models, datasets, trange=None, crossrefs=None):
    """Create individual model of individual event html page"""
    
    # set I/O shell display
    tcol, tun, tend, tit = "\033[0m\033[35m", "\033[0m\033[1m\033[35m", "\033[0m", "\033[0m\033[3m"
    
    # generate one page per individual model
    mc = MagnificationCurve()
    lc = LightCurve(datasets, trange=trange, dmag=None)
    plt_width = 800
    
    for i in range(len(models)):
        
        model = models[i]
        
        # html page name
        printi(tcol + "Creating " + tit + "'" + event + '/' + event + '_' + str(i + 1) + '.html' + "'" + tcol + " web page" + tend)

        # fit light curve using best-fit parameters
        mc.create(model)
        lc.fit(mc, 'central', '+', init=None)
    
        # ligth curve plot template (bind x-axis on light curve plot, with automatic t-range)
        plc = bplt.figure(width=plt_width, plot_height=500, title='Light curve', tools=["pan", "wheel_zoom", "box_zoom", "undo", "redo", "reset", "save"], active_drag="pan", active_scroll="wheel_zoom")
        
        if trange:
            tmin = lc.params['t0'] - 1.5 * lc.params['tE']
            tmax = lc.params['t0'] + 1.5 * lc.params['tE']
            plc.x_range = Range1d(tmin, tmax)

        # residuals plot template
        pres = bplt.figure(width=plt_width, plot_height=200, title='Residuals', x_range=plc.x_range, y_range=(-0.1, 0.1), tools=["pan", "wheel_zoom", "reset", "save"], active_drag="pan", active_scroll="wheel_zoom")

        # caustics plot template
        plt_height = 400
        pcc = bplt.figure(width=plt_width, plot_height=plt_height, title='Source trajectory', tools=["pan", "wheel_zoom", "box_zoom", "undo", "redo", "reset", "save"], active_drag="pan", active_scroll="wheel_zoom", match_aspect=True, x_range=(- float(plt_width)/plt_height, float(plt_width)/plt_height), y_range=(-1, 1))

        # plot caustics
        cc = Caustics(mc.params['s'], mc.params['q'], N=256, cusp=True)
        z = np.ravel(cc.zetac)
        pcc.circle(np.real(z), np.imag(z), size=1, alpha=1., color='red')
   
        # plot trajectory
        traj = lambda t: (-lc.params['u0'] * np.sin(lc.params['alpha']) + np.cos(lc.params['alpha']) * t, lc.params['u0'] * np.cos(lc.params['alpha']) + np.sin(lc.params['alpha']) * t)

        pcc.line(traj(np.array([-10., 10.]))[0], traj(np.array([-10., 10.]))[1], color='firebrick', line_width=1)
   
        pcc.add_layout(Arrow(line_width=1, line_color='firebrick', end=VeeHead(size=10, line_color='firebrick'), x_start=traj((tmin - lc.params['t0'])/lc.params['tE'])[0], y_start=traj((tmin - lc.params['t0'])/lc.params['tE'])[1], x_end=traj((tmax - lc.params['t0'])/lc.params['tE'])[0], y_end=traj((tmax - lc.params['t0'])/lc.params['tE'])[1]))

        # compute blended flux
        flux = lc._mu * lc.params['Fs'][0] + lc.params['Fb'][0]
        t = lc._t * lc.params['tE'] + lc.params['t0']

        # remove points with negative flux and NaN
        arg = np.logical_not(np.isnan(flux)) & (flux > 0.)
        flux = flux[arg]
        t = t[arg]

        # invert light curve y-axis
        plc.y_range = Range1d(1.02 * np.max(-2.5 * np.log10(flux)), 0.98 * np.min(-2.5 * np.log10(flux)))

        # theoretical ligth curve
        plc.line(t, -2.5 * np.log10(flux), color='firebrick')

        # add data on plot
        atel = iter(color_tel)
        for k in range(len(lc._datalist)):
            dat = lc._datalist[k]
            # color and legend
            _ , datai = split(dat[6])
            tel = datai[0]
            if tel not in color_tel:
                tel = atel.next()
            color = color_tel[tel]
 
            # deblending
            magnif = (np.power(10., - dat[2] / 2.5) - lc.params['Fb'][k]) / lc.params['Fs'][k]
            flux = magnif * lc.params['Fs'][0] + lc.params['Fb'][0]
            
            # remove points with negative flux and NaN, and compute mag
            date = dat[1]
            errbar = dat[3]
            arg = np.logical_not(np.isnan(flux)) & (flux > 0.)
            flux = flux[arg]
            date = date[arg]
            errbar = errbar[arg]
            mag = - 2.5 * np.log10(flux)

            mu = lc.content['mc']((date - lc.params['t0']) / lc.params['tE'])
            res = - 2.5 * np.log10(mu * lc.params['Fs'][0] + lc.params['Fb'][0]) - mag

            # plot light curve with error bars
            plc.circle(date, mag, size=4, alpha=1., color=color, legend=tel)

            y_err_x, y_err_y = [], []
            for px, py, err in zip(date, mag, errbar):
                y_err_x.append((px, px))
                y_err_y.append((py - err, py + err))
            plc.multi_line(y_err_x, y_err_y, color=color, alpha=0.4)
           
            # plot residuals with error bars
            pres.line((0., 1e6), (0., 0.), color='black', line_width=0.2)
            
            pres.circle(date, res, size=4, alpha=1., color=color)
            
            y_err_x, y_err_y = [], []
            for px, py, err in zip(date, res, errbar):
                y_err_x.append((px, px))
                y_err_y.append((py - err, py + err))
            pres.multi_line(y_err_x, y_err_y, color=color, alpha=0.4)
            
            # color points at data dates on trajectory
            pcc.circle(traj((date - lc.params['t0'])/lc.params['tE'])[0], traj((date - lc.params['t0'])/lc.params['tE'])[1], size=4, alpha=1., color=color)

        # group plots in one column and generate best-fits html code
        p = column([plc, pres, pcc])
        script, divini = components(p)
        div = '<div align="center">' + divini + '</div>'

        # create search map html code
        wsmap = '<img class="imageStyle" alt="' + event + '" src="./' + event + '.png' + '" width="800" />'

        # label version
        version = str(version_info).replace(', ', '.').replace('(', '(version ')

        # list of best fit paramters to download
        fitrank = event + '_rank.txt'
        
        # date and time of event's update
        if os.path.isfile(event + '/lastupdate.txt'):
            with open(event + '/lastupdate.txt', 'r') as f:
                fittime = f.read()
                f.close()
        else:
            fittime = ''
        
        # get multiple references of event
        if crossrefs:
            evname = getcrossrefs(crossrefs, event)
        else:
            evname = event
    
        # write parameters
        eventdet = 'Microlensing event ' + evname + ' : details of binary-lens model ' + str(i + 1)

        lpar = '<i>Model paramaters</i>'

        lpar += '<p align="left" style="color:#B22222">$s$={0:<.8f}<BR>$q$={1:<.8f}<BR>$u_0$={2:<.8f}<BR>$\\alpha$={3:<.5f}<BR>$t_E$={4:<.3f}<BR>$t_0$={5:<.6f}<BR>$\\rho$={6:<.8f}<BR>'.format(lc.params['s'], lc.params['q'], lc.params['u0'], lc.params['alpha'], lc.params['tE'], lc.params['t0'], lc.params['rho'])
        if 'piEN' in lc.params.keys():
            lpar += '$\\pi_{E, N}$={6:<.8f}<BR>'
        if 'piEE' in lc.params.keys():
            lpar += '$\\pi_{E, E}$={6:<.8f}<BR>'
        if 'ds' in lc.params.keys():
            lpar += '$ds/dt$={6:<.8f}<BR>'
        if 'dalpha' in lc.params.keys():
            lpar += '$d\\alpha/dt$={6:<.8f}<BR>'
        lpar += '</p><BR>'

        lpar += '<i>Light curve, residuals, source trajectory and caustics</i>'
    
        # create model selection list
        selmod = '<select name="display" onchange="location=this.value;">'
        selmod += '<option value="/miiriads/MiSMap/Events/' + event + '.html">Overview</option>'
        for j in range(len(models)):
            if j == i:
                selmod += '<option value="/miiriads/MiSMap/Events/' + event + '_' + str(j + 1) + '.html" selected>Model ' + str(j + 1) + '</option>'
            else:
                selmod += '<option value="/miiriads/MiSMap/Events/' + event + '_' + str(j + 1) + '.html">Model ' + str(j + 1) + '</option>'
        selmod += '</select>'

        # fill template html page
        fill_webpage(html_model_template, event + '/' + event + '_' + str(i + 1) + '.html', [('_LASTUPDATE_', fittime), ('_VERSION_', version), ('_EVENT_', evname), ('_EVENTDET_', eventdet), ('_MODEL_', div), ('_PARAMS_', lpar), ('_SELECT_', selmod), ('_RANK_', fitrank), ('<!-- _SCRIPT_ -->', script)])
Ejemplo n.º 16
0
def drawGasPlot(combinedData, chemical, time, numToDateHashMap):
    p = figure(title="Gas Measure of " + chemical,
               x_axis_location=None,
               y_axis_location=None,
               x_axis_label='Map',
               y_axis_label='Map',
               tools="pan,wheel_zoom,reset,hover,save")

    # p.circle(x = facs['x'], y = facs['y'], color = 'blue', size = 15)

    sensor_measurements = findRanksBasedOnChemicalMeasurement(
        combinedData, chemical, time)
    rankSize = 10
    print('wind direction is')
    print(combinedData[time][-1][1])
    angle = combinedData[time][-1][1]
    print('sin shift {} and cos shift {}'.format(math.sin(math.radians(angle)),
                                                 math.cos(
                                                     math.radians(angle))))
    print("date is ", numToDateHashMap[time])
    for pair in sensor_measurements:
        if pair[0] == 1.0:
            p.circle(61,
                     21,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 2.0:
            p.circle(66,
                     35,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 3.0:
            p.circle(76,
                     41,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 4.0:
            p.circle(88,
                     45,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 5.0:
            p.circle(103,
                     43,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 6.0:
            p.circle(102,
                     22,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 7.0:
            p.circle(89,
                     3,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 8.0:
            p.circle(74,
                     7,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)
        elif pair[0] == 9.0:
            p.circle(119,
                     42,
                     size=pair[1] * 50,
                     line_color="green",
                     fill_color="green",
                     fill_alpha=0.5)

        rankSize += 10

    #show(p)
    p.circle(x=50, y=0, fill_alpha=0, size=1)
    p.circle(x=110, y=60, fill_alpha=0, size=1)
    p.add_layout(
        Arrow(end=VeeHead(size=35, fill_color='red'),
              line_color="red",
              x_start=65,
              y_start=53,
              x_end=65 - math.sin(math.radians(angle)),
              y_end=53 - math.cos(math.radians(angle))))
    speed = Label(x=65,
                  y=56,
                  background_fill_color='white',
                  text='wind speed: ' + str(combinedData[time][-1][3]))
    p.add_layout(speed)
    p.image_url(url=['https://i.imgur.com/Lz7D8KN.jpg'],
                x=46,
                y=65,
                w=82,
                h=70,
                global_alpha=.5)

    return p
# create a reference circle
p.circle(x=[0],
         y=[0],
         radius=circle_radius,
         fill_alpha=0.0,
         line_alpha=1.0,
         color='black')

# create the arrows and hovertool layout ontop of multiline
cat10_palette = bokeh.palettes.Category10[10]
arrow_line_palette = [cat10_palette[3], cat10_palette[2]]  # red and green
arrow_mapper = CategoricalColorMapper(palette=arrow_line_palette,
                                      factors=['neg', 'pos'])
p.add_layout(
    Arrow(end=VeeHead(size=10,
                      fill_alpha=0.50,
                      line_alpha=0.50,
                      fill_color=cat10_palette[7]),
          source=source_arrows,
          x_start='x_from',
          y_start='y_from',
          x_end='x_to',
          y_end='y_to',
          line_alpha=0.50,
          line_color={
              'field': 'Sentiment',
              'transform': arrow_mapper
          }))
p.multi_line(
    source=source_arrows,
    xs='xs',
    ys='ys',
Ejemplo n.º 18
0
def figure_scatter_values(df_chisq):
    df_chisq["casema07_diff07"] = df_chisq.case_ma07.diff(periods=1)
    df_chisq["testsma07_diff07"] = df_chisq.tests_ma07.diff(periods=1)
    df_chisq["casedet_diff07"] = df_chisq.case_detrended.diff(periods=1)
    df_chisq["casedetpct_diff07"] = df_chisq.caseDet_pct.diff(periods=1)
    df_chisq[
        "angle"] = df_chisq.testsma07_diff07 / df_chisq.casema07_diff07 * 3.14
    df_chisq["casema07_start"] = df_chisq.case_ma07 - df_chisq.casema07_diff07
    df_chisq[
        "testsma07_start"] = df_chisq.tests_ma07 - df_chisq.testsma07_diff07
    df_chisq[
        "casedet_start"] = df_chisq.case_detrended - df_chisq.casedet_diff07
    df_chisq[
        "casedetpct_start"] = df_chisq.caseDet_pct - df_chisq.casedetpct_diff07
    df_chisq["dt_str"] = df_chisq.Date.dt.strftime("%Y-%m-%d")

    # FIXME

    # df_chisq.set_index(["CountryProv","Date"]).tail()[['case_ma07', 'tests_ma07',  'casema07_diff07', 'testsma07_diff07', 'casema07_start', 'testsma07_start']]

    print("gathering moving 14-day windows")
    #df_sub = df_chisq[df_chisq.Date >= "2020-04-28"]
    df_sub = df_chisq
    df_latest = []
    dtmax_n = df_sub.Date.unique().max()
    dtmin_n = df_sub.Date.unique().min()
    import datetime as dt
    #dt_range = df_sub.Date.unique()
    dt_range = np.arange(dtmax_n, dtmin_n, dt.timedelta(days=-14))
    #dtmax_s = str(dtmax_n)[:10] # http://stackoverflow.com/questions/28327101/ddg#28327650
    for dt_i in dt_range:
        dt_delta = (dt_i - dtmin_n).astype('timedelta64[D]').astype(int)
        if dt_delta < 14: continue
        print(dt_i, dt_delta)

        df_i = df_sub[df_sub.Date <= dt_i]
        df_i = df_i.groupby("CountryProv").apply(
            lambda g: g.tail(14)).reset_index(drop=True)
        df_i["color"] = "#73b2ff"
        df_i["dtLast"] = dt_i
        df_latest.append(df_i)

    if len(df_latest) == 0: raise Exception("No data in moving window")
    df_latest = pd.concat(df_latest, axis=0)
    df_latest["display_cpcode"] = df_latest.apply(
        lambda g: "" if g.dtLast != g.Date else g.cp_code, axis=1)
    print("done")

    #source_hist = ColumnDataSource(df_chisq)
    #source_latest = ColumnDataSource(df_latest)

    # since cannot use View iwth LabelSet, creating a different source per continent
    # Couldn't figure out how to filter the datasource in add_layout or Arrow,
    # so just grouping on both continent and dtLast
    srcLatest_continent = df_latest.groupby(
        ["Continent", "dtLast"]).apply(lambda g: ColumnDataSource(g))
    srcLatest_continent = srcLatest_continent.reset_index().rename(
        columns={0: "src"})

    plot_size_and_tools = {
        'plot_height': 300,
        'plot_width': 600,
        'tools': ['box_select', 'reset', 'help', 'box_zoom'],
        'x_axis_type': 'datetime'
    }

    # general-use lines
    slope_y0 = Slope(gradient=0,
                     y_intercept=0,
                     line_color='orange',
                     line_width=50)
    slope_x0 = Slope(gradient=np.Inf,
                     y_intercept=0,
                     line_color='orange',
                     line_width=50)

    # scatter plot
    TOOLTIPS = [
        ("Country/Region", "@CountryProv"),
        ("Date", "@dt_str"),
    ]
    # first set for case vs tests, then second set for case diff vs test diff
    params = (
        #('values', 'tests_ma07', 'case_ma07', 'testsma07_start',  'casema07_start', 'ma07(Tests)', 'ma07(Cases)'),
        #('diffs', 'casema07_diff07', 'testsma07_diff07', 'diff07(ma07(Cases))', 'diff07(ma07(Tests))'),
        ('values', 'case_detrended', 'case_ma07', 'casedet_start',
         'casema07_start', 'detrended(cases)', 'ma07(Cases)'),
        #('values', 'caseDet_pct', 'case_ma07', 'casedetpct_start',  'casema07_start', 'detrended(ma07(cases))/cases*100', 'ma07(Cases)'),
    )
    p_all = {'values': [], 'diffs': []}
    from bokeh.models import Arrow, NormalHead, OpenHead, VeeHead
    for k, fdxv, fdyv, fdxs, fdys, labx, laby in params:
        p_cont = []
        for srcCont_i in srcLatest_continent.iterrows():
            srcCont_i = srcCont_i[1]
            print("Adding plot for %s, %s" %
                  (srcCont_i.Continent, srcCont_i.dtLast))

            #init_group=dtmax_s
            #gf = GroupFilter(column_name='dtLast', group=init_group)
            #view1 = CDSView(source=srcCont_i.src, filters=[gf])

            p_d1 = figure(plot_width=600,
                          plot_height=400,
                          tooltips=TOOLTIPS,
                          title="%s %s" %
                          (srcCont_i.Continent, srcCont_i.dtLast))

            #p_d1.triangle(fdxv, fdyv, source=srcCont_i.src, size=12, color='blue', angle="angle")
            #p_d1.scatter(fdxs, fdys, source=srcCont_i.src, size=3, color='red') #, view=view1)
            p_d1.scatter(fdxv, fdyv, source=srcCont_i.src, size=3, color='red')
            p_d1.add_layout(
                Arrow(end=VeeHead(size=6),
                      x_start=fdxs,
                      y_start=fdys,
                      x_end=fdxv,
                      y_end=fdyv,
                      line_color='blue',
                      source=srcCont_i.src
                      #view=view1 # srcCont_i.src
                      )  #,
                #view=view1 # not supported
            )

            p_d1.xaxis.axis_label = labx
            p_d1.yaxis.axis_label = laby
            from bokeh.models import LabelSet
            labels = LabelSet(x=fdxv,
                              y=fdyv,
                              text='display_cpcode',
                              level='glyph',
                              x_offset=5,
                              y_offset=5,
                              source=srcCont_i.src,
                              render_mode='canvas')
            p_d1.add_layout(labels)
            p_d1.add_layout(slope_y0)
            p_d1.add_layout(slope_x0)
            p_cont.append(p_d1)

        p_all[k] = p_cont

    # group plots into 3 per row
    # https://stackoverflow.com/a/1625013/4126114
    from itertools import zip_longest
    for k in ['values', 'diffs']:
        p_cont = p_all[k]
        p_cont = list(zip_longest(*(iter(p_cont), ) * 3))
        p_cont = [[e for e in t if e != None] for t in p_cont]
        p_all[k] = p_cont

    g = gridplot(p_all['values'] + p_all['diffs'])
    layout = column(g)

    return layout
Ejemplo n.º 19
0
p.circle(x=[0, 1, 0.5],
         y=[0, 0, 0.7],
         radius=0.1,
         color=["navy", "yellow", "red"],
         fill_alpha=0.1)

p.add_layout(
    Arrow(end=OpenHead(line_color="firebrick", line_width=4),
          x_start=0,
          y_start=0,
          x_end=1,
          y_end=0))

p.add_layout(
    Arrow(end=NormalHead(fill_color="orange"),
          x_start=1,
          y_start=0,
          x_end=0.5,
          y_end=0.7))

p.add_layout(
    Arrow(end=VeeHead(size=35),
          line_color="red",
          x_start=0.5,
          y_start=0.7,
          x_end=0,
          y_end=0))

show(p)
Ejemplo n.º 20
0
    def draw_network_graph_given(self, edges, nodes, probsa, vdata, eOnly):
        # probs = dict key: nodename, value: dict(probname:probval)

        probs = dict()
        if not eOnly:
            for nam in nodes:
                if not nam in probsa: cond = "[]"
                else: cond = probsa[nam]
                probs[nam] = dict()
                try:
                    cur_dist = vdata[nam]["cprob"][cond]
                    #print("No cprob given.")
                except:
                    pass

                for i in range(len(vdata[nam]["vals"])):
                    try:
                        probs[nam][vdata[nam]["vals"][i]] = cur_dist[i]
                    except:
                        pass

        G = nx.DiGraph()
        if not nodes:
            nodes = []
            for e in edges:
                if e[0] not in nodes:
                    nodes.append(e[0])
                if e[1] not in nodes:
                    nodes.append(e[1])
        if eOnly:
            edges_new = []
            for e in edges:
                if e[0] in nodes and e[1] in nodes:
                    edges_new.append(e)
            edges = edges_new

        G.add_edges_from(edges, weight="")
        #edge_labels=dict([((u,v,),d['weight'])
        #                 for u,v,d in G.edges(data=True)])
        #edge_colors = len(G.edges())*['black']
        #pos=nx.shell_layout(G) # circular_layout    random_layout       shell_layout    spring_layout    spectral_layout
        #nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
        #nx.draw(G,pos, node_size=3000,edge_color=edge_colors)
        #labels ={}
        #for n in nodes:
        #    labels[n] = n
        #nx.draw_networkx_labels(G, pos, labels, font_size=10)

        # PLOT
        plot = Plot(plot_width=1300,
                    plot_height=800,
                    x_range=Range1d(-1.1, 1.1),
                    y_range=Range1d(-1.1, 1.1))
        plot.title.text = "Temporal Dependency Bayesian Network"
        hover = HoverTool(tooltips=[
            ("desc", "@desc"),
        ])
        plot.add_tools(hover, TapTool(), BoxSelectTool())
        plot.add_tools(WheelZoomTool())
        plot.add_tools(PanTool())

        graph_renderer = from_networkx(G,
                                       nx.spring_layout,
                                       scale=1,
                                       center=(0, 0))

        desc_probs = []
        for n in nodes:
            try:
                nodeCur = probs[n]
                pr = ""
                for k in nodeCur.keys():
                    pr += "\nP(" + str(k) + ")=" + str(nodeCur[k]) + ""
                desc_probs += [pr]
            except:
                desc_probs += [""]
        node_source = ColumnDataSource(data=dict(index=nodes, desc=desc_probs))
        graph_renderer.node_renderer.data_source.data = node_source.data

        graph_renderer.node_renderer.glyph = Circle(size=15,
                                                    fill_color=Spectral4[0])
        graph_renderer.node_renderer.selection_glyph = Circle(
            size=15, fill_color=Spectral4[2])
        graph_renderer.node_renderer.hover_glyph = Circle(
            size=15, fill_color=Spectral4[1])
        graph_renderer.edge_renderer.glyph = MultiLine(line_color="firebrick",
                                                       line_alpha=0.8,
                                                       line_width=1.1)
        graph_renderer.edge_renderer.selection_glyph = MultiLine(
            line_color=Spectral4[2], line_width=5)
        graph_renderer.edge_renderer.hover_glyph = MultiLine(
            line_color=Spectral4[1], line_width=5)
        plot.renderers.append(graph_renderer)
        graph_renderer.selection_policy = NodesAndLinkedEdges()
        #graph_renderer.inspection_policy = EdgesAndLinkedNodes()

        # PLOT ARROWS FOR EDGES
        pos_dict = graph_renderer.layout_provider.graph_layout
        done = []
        for e in edges:
            plot.add_layout(
                Arrow(end=VeeHead(line_width=2, size=4),
                      x_start=pos_dict[e[0]][0],
                      y_start=pos_dict[e[0]][1],
                      x_end=pos_dict[e[1]][0],
                      y_end=pos_dict[e[1]][1]))

            font_size = "8pt"
            if not str(e[0]) in done:
                done += [str(e[0])]
                plot.add_layout(
                    Label(x=pos_dict[e[0]][0],
                          y=pos_dict[e[0]][1] + 0.01,
                          text=str(e[0]),
                          text_font_size=font_size,
                          render_mode='css',
                          background_fill_alpha=1.0))
            if not str(e[1]) in done:
                done += [str(e[1])]
                plot.add_layout(
                    Label(x=pos_dict[e[1]][0],
                          y=pos_dict[e[1]][1] + 0.01,
                          text=str(e[1]),
                          text_font_size=font_size,
                          render_mode='css',
                          background_fill_alpha=1.0))

        graph_renderer.edge_renderer.glyph.line_join = 'round'
        output_file("interactive_graphs.html")
        show(plot)
        return
Ejemplo n.º 21
0
    def __init__(self):
        self.InvCapabilityPlot = figure(plot_width=580,
                                        plot_height=350,
                                        tools='',
                                        title="Inverter capability curve")
        self.PVSettingsPlot = figure(plot_width=580,
                                     plot_height=350,
                                     tools='',
                                     title="PV settings")
        self.VoltVarDatasource = ColumnDataSource(data=dict(x=[], y=[]))
        self.PVSettingsPlot.line('x',
                                 'y',
                                 source=self.VoltVarDatasource,
                                 line_width=2,
                                 line_alpha=0.6,
                                 legend='volt/var',
                                 line_color="blue")
        self.VoltWattDatasource = ColumnDataSource(data=dict(x=[], y=[]))
        self.PVSettingsPlot.line('x',
                                 'y',
                                 source=self.VoltWattDatasource,
                                 line_width=2,
                                 line_alpha=0.6,
                                 legend='volt/watt',
                                 line_color="red")

        self.InvCapabilityPlot.xaxis.axis_label = 'Q [p.u]'
        self.InvCapabilityPlot.yaxis.axis_label = 'P [p.u]'
        self.InvCapabilityPlot.toolbar.logo = None
        self.InvCapabilityPlot.toolbar_location = None
        self.InvCapabilityPlot.y_range = Range1d(*(-0.05, 1.15))
        self.InvCapabilityPlot.x_range = Range1d(*(-1.15, 1.15))

        self.InvCapabilityPlot.circle(x=[0],
                                      y=[0],
                                      radius=0.001,
                                      color=["black"])
        self.InvCapabilityPlot.add_layout(
            Arrow(end=VeeHead(size=10),
                  line_color="black",
                  x_start=0.0,
                  y_start=0,
                  x_end=0,
                  y_end=1.1))
        self.InvCapabilityPlot.add_layout(
            Arrow(end=VeeHead(size=10),
                  line_color="black",
                  x_start=-1.1,
                  y_start=0,
                  x_end=1.1,
                  y_end=0))
        self.InvCapabilityPlot.arc(x=[0],
                                   y=[0],
                                   radius=1,
                                   start_angle=0,
                                   end_angle=3.142,
                                   color="navy")

        self.PVcurveDatasource = ColumnDataSource(data=dict(x0=[],
                                                            x1=[],
                                                            x2=[],
                                                            x3=[],
                                                            x4=[],
                                                            x5=[],
                                                            x6=[],
                                                            y0=[],
                                                            y1=[],
                                                            y2=[],
                                                            y3=[],
                                                            y4=[],
                                                            y5=[],
                                                            y6=[]))
        self.InvCapabilityPlot.line('x0',
                                    'y0',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x1',
                                    'y1',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x2',
                                    'y2',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x3',
                                    'y3',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x4',
                                    'y4',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x5',
                                    'y5',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.InvCapabilityPlot.line('x6',
                                    'y6',
                                    source=self.PVcurveDatasource,
                                    line_width=1,
                                    line_alpha=1.0,
                                    line_color="red")
        self.PVSettingsPlot.xaxis.axis_label = 'Voltage [p.u]'
        self.PVSettingsPlot.yaxis.axis_label = 'P,Q [p.u]'
        self.PVSettingsPlot.toolbar.logo = None
        self.PVSettingsPlot.toolbar_location = None
        self.PVSettingsPlot.legend.location = "bottom_left"
        self.PVSettingsPlot.legend.click_policy = "hide"
        self.PVSettingsPlot.x_range = Range1d(*(0.9, 1.2))
        self.PVSettingsPlot.y_range = Range1d(*(-1.15, 1.15))
        self.PVSettingsPlot.circle(x=[1], y=[0], radius=0.001, color=["black"])
        self.ArrowHead1 = Arrow(end=VeeHead(size=10),
                                line_color="black",
                                x_start=1.0,
                                y_start=-1.1,
                                x_end=1,
                                y_end=1.1)
        self.ArrowHead2 = Arrow(end=VeeHead(size=10),
                                line_color="black",
                                x_start=0.9,
                                y_start=0,
                                x_end=1.2,
                                y_end=0)
        self.PVSettingsPlot.add_layout(self.ArrowHead1)
        self.PVSettingsPlot.add_layout(self.ArrowHead2)

        PVwidgetbox = self.createPVwidgetbox()
        PVsettingsLayout = column(self.InvCapabilityPlot,
                                  self.PVSettingsPlot,
                                  PVwidgetbox,
                                  width=800)
        self.final_layout = PVsettingsLayout

        for w in [
                self.PVvar, self.Vlb, self.Vub, self.Vdblb, self.Vdbub,
                self.VWlb, self.VWub, self.VWPmin, self.VWumin,
                self.PVRatingTB, self.PVcutinTB, self.PVcutoutTB, self.PVpf
        ]:
            w.on_change('value', self.updatePVcurves)

        self.updatePVcurves(None, None, None)
        return
Ejemplo n.º 22
0
               y_start=4,
               x_end=6,
               y_end=9,
               line_color='green',
               line_alpha=0.7,
               line_dash='8 4',
               line_width=5,
               end=OpenHead())
arrow1.end.line_width = 8

arrow2 = Arrow(x_start=2,
               y_start=3,
               x_end=7,
               y_end=8,
               start=NormalHead(),
               end=VeeHead())
arrow2.start.fill_color = 'indigo'
arrow2.end.fill_color = 'orange'
arrow2.end.size = 50

plot.add_layout(arrow1)
plot.add_layout(arrow2)

# test arrow body clipping
plot.add_layout(
    Arrow(start=TeeHead(line_width=1),
          x_start=6,
          y_start=5,
          x_end=8,
          y_end=6,
          line_width=10))
Ejemplo n.º 23
0
from bokeh.io import save
from bokeh.models import Arrow, NormalHead, OpenHead, TeeHead, VeeHead
from bokeh.plotting import figure

# Have to specify x/y range as labels aren't included in the plot area solver
plot = figure(width=600, height=600, x_range=(0,10), y_range=(0,10), toolbar_location=None)

arrow1 = Arrow(x_start=1, y_start=4, x_end=6, y_end=9,
               line_color='green', line_alpha=0.7,
               line_dash='8 4', line_width=5, end=OpenHead()
               )
arrow1.end.line_width=8

arrow2 = Arrow(x_start=2, y_start=3, x_end=7, y_end=8,
               start=NormalHead(), end=VeeHead()
               )
arrow2.start.fill_color = 'indigo'
arrow2.end.fill_color = 'orange'
arrow2.end.size = 50

plot.add_layout(arrow1)
plot.add_layout(arrow2)

# test arrow body clipping
plot.add_layout(Arrow(start=TeeHead(line_width=1), x_start=6, y_start=5, x_end=8, y_end=6, line_width=10))
plot.add_layout(Arrow(start=VeeHead(line_width=1, fill_color="white"), x_start=6, y_start=4, x_end=8, y_end=5, line_width=10))
plot.add_layout(Arrow(start=NormalHead(line_width=1, fill_color="white"), x_start=6, y_start=3, x_end=8, y_end=4, line_width=10))
plot.add_layout(Arrow(start=OpenHead(line_width=1), x_start=6, y_start=2, x_end=8, y_end=3, line_width=10))

save(plot)
Ejemplo n.º 24
0
    def create_choropleth(displaySet, displayParam, palette, ogCity):
        """ 
            Fonction qui met à jour la coloration des communes affichées
            Entrées :
                - displaySet : dataFrame contenant les données affichées
                - displayParam : paramètres que l'on souhaite aficher
                - palette : liste de couleurs (identique à celle de la choroplèthe)
                - ogCity : extract de la commune sélectionnée
            Sorties : 
                - Figure contenant la carte.
        """
        # On récupère les limites géographiques pour initialiser la carte
        displayBounds = displaySet.total_bounds

        # conversion du tracé des communes en json pour interpretation par Bokeh
        geosource = GeoJSONDataSource(geojson=displaySet.to_json())

        # Creation de la figure de la carte
        choroPlot = figure(title='Taux ' + select_imp.value + " " +
                           str(slider_yr.value),
                           x_range=(displayBounds[0], displayBounds[2]),
                           y_range=(displayBounds[1], displayBounds[3]),
                           x_axis_type="mercator",
                           y_axis_type="mercator",
                           plot_height=500,
                           plot_width=850,
                           sizing_mode="scale_width",
                           toolbar_location='below',
                           tools="pan, wheel_zoom, box_zoom, reset",
                           x_axis_location=None,
                           y_axis_location=None)

        choroPlot.xgrid.grid_line_color = None
        choroPlot.ygrid.grid_line_color = None

        # Ajout d'un évèmenent de type clic, pour sélectionnr la commune de référence
        choroPlot.on_event(Tap, update_loc)

        #outil de zoom molette activé par défaut
        choroPlot.toolbar.active_scroll = choroPlot.select_one(WheelZoomTool)

        # ajout du fond de carte
        tile_provider = get_provider(Vendors.CARTODBPOSITRON)
        choroPlot.add_tile(tile_provider)

        # On détermine les vals min et max du jeu de test pour la gestion des couleurs
        mini = displaySet[displayParam].min()
        maxi = displaySet[displayParam].max()

        # Création d'une échelle de couleur évoulant linéairement avec le paramètre à afficher
        color_mapper = LinearColorMapper(palette=defaultPalette,
                                         low=mini,
                                         high=maxi,
                                         nan_color='#808080')

        # Ajout du tracé des communes sur la carte
        citiesPatch = choroPlot.patches('xs',
                                        'ys',
                                        source=geosource,
                                        line_color='gray',
                                        line_width=0.25,
                                        fill_alpha=0.5,
                                        fill_color={
                                            'field': displayParam,
                                            'transform': color_mapper
                                        })

        # création de la legende #
        color_bar = ColorBar(color_mapper=color_mapper,
                             label_standoff=8,
                             location=(0, 0),
                             orientation='vertical')
        choroPlot.add_layout(color_bar, 'right')

        # ajout d'une flèche sur la commune de reférence
        start = ogCity.geometry.centroid
        pin_point = Arrow(end=VeeHead(size=15),
                          line_color="red",
                          x_start=start.x,
                          y_start=start.y,
                          x_end=start.x,
                          y_end=start.y - 0.001)
        choroPlot.add_layout(pin_point)

        #  Ajout d'un tooltip au survol de la carte
        choroHover = HoverTool(renderers=[citiesPatch],
                               tooltips=[('Commune', '@nom'),
                                         (displayParam, '@' + displayParam)])
        toolTip = choroPlot.add_tools(choroHover)

        return choroPlot
plt_src = plot_tweet.circle(x='Long', y='Lat', alpha=0.2, size=2, color='Color', source=src)
plot_tweet.axis.visible = False
plot_tweet.toolbar.logo = None
plot_tweet.xgrid.grid_line_color = None
plot_tweet.ygrid.grid_line_color = None
plot_tweet.min_border = 0
plt_src.data_source.on_change('selected', on_selection_change)


#plot_wind()

###########################################################
source_wind = ColumnDataSource(data=dict(
        x1=[], y1=[], x2=[], y2=[]))

arrows = Arrow(end=VeeHead(fill_color="black", size=10, fill_alpha=.8, line_alpha=.5),
               x_start='x1', y_start='y1', x_end='x2', y_end='y2', source=source_wind)

plot_tweet.add_layout(arrows)

##################### slider, play buttons
start = relevant_tweet.Created_at.min() - timedelta(days=1)
end = relevant_tweet.Created_at.max() + timedelta(days=1)

curr_dt = start
end_dt = end
print(start, end, curr_dt)

plot_wind(curr_dt.date())

t1 = end - start
       source=trade_balance_cds,
       line_width=2,
       mode="before",
       color="green",
       legend="Export")
p.xaxis.major_label_orientation = np.pi / 4  # Flip x-axis labels
hover = HoverTool(tooltips=[('Period', '@period'), (
    'Import', '@import_EUR'), ('Export',
                               '@export_EUR'), ('Tradebalance',
                                                '@balance_EUR')])
p.add_tools(hover)
p.legend.location = "top_left"
p.legend.click_policy = "hide"
p.add_layout(
    Arrow(
        end=VeeHead(size=4),
        line_color="black",
        x_start=
        1236552800000,  # Dates converted to milliseconds using online converter
        y_start=42000,
        x_end=1218751200000,
        y_end=37500))
p.add_layout(
    Arrow(end=VeeHead(size=4),
          line_color="black",
          x_start=1083362400000,
          y_start=40000,
          x_end=1083362400000,
          y_end=37500))
p.add_layout(
    Label(x=1216552800000,
Ejemplo n.º 27
0
def gridded_plots(raw_data, TOOLS, gene_from_genome, upstreamBuf):

    dataS = raw_data

    '''
    Stacked Plots (Left-Hand Side)
    '''

    array = []

    for k in range(len(dataS)):
        if (k+6 >= len(dataS)):
            array.append("N/A")
        else:
            s = ""
            list_1 = []
            for l in range(k, k+6):
                list_1.append(dataS.Base[l])
            s = s.join(list_1)
            array.append(s)

    Seq = pd.DataFrame(array, columns = ['Seq'])
    df_comp = pd.concat([dataS, Seq], axis = 1)

    a = 1.5
    b = 18.5

    temp = []
    for q in range(len(df_comp)):
        temp.append(1 - 1/(1 + 2**(a*(df_comp.pASite[q] - b))))

    df_comp['pASiteT'] = temp

    temp2 = []

    for s in range(len(df_comp)):
        if (s == 0):
            temp2.append(df_comp['pASiteT'][0])
        else:
            temp2.append(df_comp['pASiteT'][s]+temp2[s-1])

    df_comp['cumulative'] = temp2

    last = len(df_comp)
    L_entry = df_comp.cumulative[last-1]

    df_comp['cumulative'] = df_comp['cumulative']/L_entry
    df_comp['pASiteT'] = df_comp['pASiteT']/L_entry

    source = ColumnDataSource(df_comp)

    ''' Individual Line Graph for  e1 '''

    s1 = figure(title = 'e1', toolbar_location = "right", tools = TOOLS, tooltips = [('Position', '@Position'), ('Score', '@e1'), ('Sequence', '@Seq')])

    s1.line('Position', 'e1', line_width = 2, color = Viridis5[0], source = source)

    s1.xaxis.visible = False

    ''' Individual Line Graph for  e2 '''

    s2 = figure(title = 'e2', x_range = s1.x_range, y_range = s1.y_range, tools = TOOLS, tooltips = [('Position', '@Position'), ('Score', '@e2'), ('Sequence', '@Seq')])

    s2.line('Position', 'e2', line_width = 2, color = Viridis5[1], source = source)

    s2.xaxis.visible = False

    ''' Individual Line Graph for  e3 '''

    s3 = figure(title = 'e3',x_range = s1.x_range, y_range = s1.y_range, tools = TOOLS, tooltips = [('Position', '@Position'), ('Score', '@e3'), ('Sequence', '@Seq')])

    s3.line('Position', 'e3', line_width = 2, color = Viridis5[2], source = source)

    s3.xaxis.visible = False

    ''' Individual Line Graph for  pA Site '''

    s4 = figure(title = 'pA Site', x_range = s1.x_range, y_range = s1.y_range, tools = TOOLS,
                tooltips = [('Position', '@Position'), ('Score', '@pASite'), ('Sequence', '@Seq')])

    s4.line('Position', 'pASite', line_width = 2, color = Viridis5[3], source = source)

    s4.xaxis.visible = False

    ''' Individual Line Graph for  e4 '''

    s5 = figure(title='e4',x_range = s1.x_range, y_range = s1.y_range, tools = TOOLS, tooltips = [('Position', '@Position'), ('Score', '@e4'), ('Sequence', '@Seq')])

    s5.line('Position', 'e4', line_width = 2, color = Viridis5[4], source = source)

    s5.yaxis.axis_label = "Score"
    s5.xaxis.axis_label = "Position"

    ''' PCF11 '''

    file = open('/var/kristoph_flask/data/pcf11_cumPa.txt', 'r')

    for line in file:
        if re.search(gene_from_genome, line):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneData.txt', 'a+') as f:
                f.write(line)

    file2 = open('/var/kristoph_flask/data/pcf11_paProb.txt', 'r')

    for line2 in file2:
        if re.search(gene_from_genome, line2):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneProb.txt', 'a+') as fa:
                fa.write(line2)


    data = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneData.txt', sep = '\s+', header = None, names = ['#gene', 'chromo', 'position', 'strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount','AGcount',
                                                                                                                                    'Acount', 'Gcount', 'DHch01_20nt_Ttrim', 'DHch02_20nt_Ttrim', 'DHch03_20nt_Ttrim', 'DHch04_20nt_Ttrim', 'DHch05_20nt_Ttrim', 'DHch06_20nt_Ttrim', 'DHch07_20nt_Ttrim', 'DHch08_20nt_Ttrim', 'all'])

    df = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneProb.txt', sep = '\s+', header = None, names = ['#gene', 'chromo', 'position', 'strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount','AGcount',
                                                                                                                                  'Acount', 'Gcount', 'DHch01_20nt_Ttrim', 'DHch02_20nt_Ttrim', 'DHch03_20nt_Ttrim', 'DHch04_20nt_Ttrim', 'DHch05_20nt_Ttrim', 'DHch06_20nt_Ttrim', 'DHch07_20nt_Ttrim', 'DHch08_20nt_Ttrim', 'all'])


    data = data.drop(['strand', 'avgGcount','AGcount', 'Acount', 'Gcount', 'DHch01_20nt_Ttrim', 'DHch02_20nt_Ttrim', 'DHch03_20nt_Ttrim', 'DHch04_20nt_Ttrim', 'DHch05_20nt_Ttrim', 'DHch06_20nt_Ttrim', 'DHch07_20nt_Ttrim', 'DHch08_20nt_Ttrim'], axis = 1)
    df = df.drop(['strand', 'avgGcount','AGcount', 'Acount', 'Gcount', 'DHch01_20nt_Ttrim', 'DHch02_20nt_Ttrim', 'DHch03_20nt_Ttrim', 'DHch04_20nt_Ttrim', 'DHch05_20nt_Ttrim', 'DHch06_20nt_Ttrim', 'DHch07_20nt_Ttrim', 'DHch08_20nt_Ttrim'], axis = 1)


    ''' decay1 '''


    file3 = open('/var/kristoph_flask/data/decay_cumPa.txt', 'r')

    for line3 in file3:
        if re.search(gene_from_genome, line3):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneData.txt', 'a+') as f:
                f.write(line3)

    file4 = open('/var/kristoph_flask/data/decay_paProb.txt', 'r')

    for line4 in file4:
        if re.search(gene_from_genome, line4):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneProb.txt', 'a+') as fa:
                fa.write(line4)

    data2 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneData.txt', sep = '\s+', header = None, names = ['#gene', 'chromo', 'position', 'strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e1_filtered_uniq30nt', 'UA05e1_filtered_uniq30nt', 'UA10e1_filtered_uniq30nt', 'UA20e1_filtered_uniq30nt', 'UA40e1_filtered_uniq30nt', 'UB00e1_filtered_uniq30nt', 'UB05e1_filtered_uniq30nt', 'UB10e1_filtered_uniq30nt', 'UB20e1_filtered_uniq30nt','UB40e1_filtered_uniq30nt','YA00e1_filtered_uniq30nt','YA05e1_filtered_uniq30nt','YA10e1_filtered_uniq30nt','YA20e1_filtered_uniq30nt','YA40e1_filtered_uniq30nt','YB00e1_filtered_uniq30nt','YB05e1_filtered_uniq30nt','YB10e1_filtered_uniq30nt','YB20e1_filtered_uniq30nt','YB40e1_filtered_uniq30nt','all'])

    df2 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneProb.txt', sep = '\s+', header = None, names = ['#gene', 'chromo', 'position', 'strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e1_filtered_uniq30nt', 'UA05e1_filtered_uniq30nt', 'UA10e1_filtered_uniq30nt', 'UA20e1_filtered_uniq30nt', 'UA40e1_filtered_uniq30nt', 'UB00e1_filtered_uniq30nt', 'UB05e1_filtered_uniq30nt', 'UB10e1_filtered_uniq30nt', 'UB20e1_filtered_uniq30nt','UB40e1_filtered_uniq30nt','YA00e1_filtered_uniq30nt','YA05e1_filtered_uniq30nt','YA10e1_filtered_uniq30nt','YA20e1_filtered_uniq30nt','YA40e1_filtered_uniq30nt','YB00e1_filtered_uniq30nt','YB05e1_filtered_uniq30nt','YB10e1_filtered_uniq30nt','YB20e1_filtered_uniq30nt','YB40e1_filtered_uniq30nt','all'])

    data2 = data2.drop(['strand', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e1_filtered_uniq30nt', 'UA05e1_filtered_uniq30nt', 'UA10e1_filtered_uniq30nt', 'UA20e1_filtered_uniq30nt', 'UA40e1_filtered_uniq30nt', 'UB00e1_filtered_uniq30nt', 'UB05e1_filtered_uniq30nt', 'UB10e1_filtered_uniq30nt', 'UB20e1_filtered_uniq30nt','UB40e1_filtered_uniq30nt','YA00e1_filtered_uniq30nt','YA05e1_filtered_uniq30nt','YA10e1_filtered_uniq30nt','YA20e1_filtered_uniq30nt','YA40e1_filtered_uniq30nt','YB00e1_filtered_uniq30nt','YB05e1_filtered_uniq30nt','YB10e1_filtered_uniq30nt','YB20e1_filtered_uniq30nt','YB40e1_filtered_uniq30nt'], axis=1)

    df2 =  df2.drop(['strand', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e1_filtered_uniq30nt', 'UA05e1_filtered_uniq30nt', 'UA10e1_filtered_uniq30nt', 'UA20e1_filtered_uniq30nt', 'UA40e1_filtered_uniq30nt', 'UB00e1_filtered_uniq30nt', 'UB05e1_filtered_uniq30nt', 'UB10e1_filtered_uniq30nt', 'UB20e1_filtered_uniq30nt','UB40e1_filtered_uniq30nt','YA00e1_filtered_uniq30nt','YA05e1_filtered_uniq30nt','YA10e1_filtered_uniq30nt','YA20e1_filtered_uniq30nt','YA40e1_filtered_uniq30nt','YB00e1_filtered_uniq30nt','YB05e1_filtered_uniq30nt','YB10e1_filtered_uniq30nt','YB20e1_filtered_uniq30nt','YB40e1_filtered_uniq30nt'], axis=1)

    ''' decay2 '''

    file5 = open('/var/kristoph_flask/data/decay2_cumPa.txt', 'r')

    for line5 in file5:
        if re.search(gene_from_genome, line5):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneData.txt', 'a+') as f:
                f.write(line5)

    file6 = open('/var/kristoph_flask/data/decay2_paProb.txt', 'r')

    for line6 in file6:
        if re.search(gene_from_genome, line6):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneProb.txt', 'a+') as fa:
                fa.write(line6)

    data3 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneData.txt', sep = '\s+', header = None, names = ['#gene', 'chromo','position','strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e2_filtered_uniq30nt', 'UA05e2_filtered_uniq30nt', 'UA10e2_filtered_uniq30nt', 'UA20e2_filtered_uniq30nt', 'UA40e2_filtered_uniq30nt', 'UB00e2_filtered_uniq30nt', 'UB05e2_filtered_uniq30nt', 'UB10e2_filtered_uniq30nt', 'UB20e2_filtered_uniq30nt', 'UB40e2_filtered_uniq30nt', 'YA00e2_filtered_uniq30nt', 'YA05e2_filtered_uniq30nt','YA10e2_filtered_uniq30nt','YA20e2_filtered_uniq30nt','YA40e2_filtered_uniq30nt','YB00e2_filtered_uniq30nt','YB05e2_filtered_uniq30nt','YB10e2_filtered_uniq30nt','YB20e2_filtered_uniq30nt','YB40e2_filtered_uniq30nt','all'])

    df3 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneProb.txt', sep = '\s+', header = None, names = ['#gene', 'chromo','position','strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e2_filtered_uniq30nt', 'UA05e2_filtered_uniq30nt', 'UA10e2_filtered_uniq30nt', 'UA20e2_filtered_uniq30nt', 'UA40e2_filtered_uniq30nt', 'UB00e2_filtered_uniq30nt', 'UB05e2_filtered_uniq30nt', 'UB10e2_filtered_uniq30nt', 'UB20e2_filtered_uniq30nt', 'UB40e2_filtered_uniq30nt', 'YA00e2_filtered_uniq30nt', 'YA05e2_filtered_uniq30nt','YA10e2_filtered_uniq30nt','YA20e2_filtered_uniq30nt','YA40e2_filtered_uniq30nt','YB00e2_filtered_uniq30nt','YB05e2_filtered_uniq30nt','YB10e2_filtered_uniq30nt','YB20e2_filtered_uniq30nt','YB40e2_filtered_uniq30nt','all'])

    data3 = data3.drop(['strand','avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e2_filtered_uniq30nt', 'UA05e2_filtered_uniq30nt', 'UA10e2_filtered_uniq30nt', 'UA20e2_filtered_uniq30nt', 'UA40e2_filtered_uniq30nt', 'UB00e2_filtered_uniq30nt', 'UB05e2_filtered_uniq30nt', 'UB10e2_filtered_uniq30nt', 'UB20e2_filtered_uniq30nt', 'UB40e2_filtered_uniq30nt', 'YA00e2_filtered_uniq30nt', 'YA05e2_filtered_uniq30nt','YA10e2_filtered_uniq30nt','YA20e2_filtered_uniq30nt','YA40e2_filtered_uniq30nt','YB00e2_filtered_uniq30nt','YB05e2_filtered_uniq30nt','YB10e2_filtered_uniq30nt','YB20e2_filtered_uniq30nt','YB40e2_filtered_uniq30nt'], axis = 1)

    df3 = df3.drop(['strand', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'UA00e2_filtered_uniq30nt', 'UA05e2_filtered_uniq30nt', 'UA10e2_filtered_uniq30nt', 'UA20e2_filtered_uniq30nt', 'UA40e2_filtered_uniq30nt', 'UB00e2_filtered_uniq30nt', 'UB05e2_filtered_uniq30nt', 'UB10e2_filtered_uniq30nt', 'UB20e2_filtered_uniq30nt', 'UB40e2_filtered_uniq30nt', 'YA00e2_filtered_uniq30nt', 'YA05e2_filtered_uniq30nt','YA10e2_filtered_uniq30nt','YA20e2_filtered_uniq30nt','YA40e2_filtered_uniq30nt','YB00e2_filtered_uniq30nt','YB05e2_filtered_uniq30nt','YB10e2_filtered_uniq30nt','YB20e2_filtered_uniq30nt','YB40e2_filtered_uniq30nt'], axis = 1)

    ''' Steinmetz '''

    file7 = open('/var/kristoph_flask/data/steinmetz_cumPa.txt', 'r')

    for line7 in file7:
        if re.search(gene_from_genome, line7):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneData.txt', 'a+') as f:
                f.write(line7)

    file8 = open('/var/kristoph_flask/data/steinmetz_paProb.txt', 'r')

    for line8 in file8:
        if re.search(gene_from_genome, line8):
            with open('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneProb.txt', 'a+') as fa:
                fa.write(line8)

    data4 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneData.txt', sep = '\s+', header = None, names = ['#gene', 'chromo','position', 'strand', 'distToCDSstop','distToCDSstart', 'avgGcount', 'AGcount', 'Acount','Gcount', 'Lane8ByIB_30nt_Ttrim', 'Lane8ByIIB_30nt_Ttrim', 'Lane8ByIIIB_30nt_Ttrim', 'Lane8TS1248IB_30nt_Ttrim', 'Lane8TS1248IIIB_30nt_Ttrim', 'Lane8TS685IB_30nt_Ttrim', 'Lane8TS685IIB_30nt_Ttrim', 'Lane8TS801IB_30nt_Ttrim', 'Lane8TS801IIB_30nt_Ttrim', 'Lane8TS801IIIB_30nt_Ttrim', 'lane3BY4741III_30nt_Ttrim', 'lane3TS1248II_30nt_Ttrim', 'lane3TS685III_30nt_Ttrim', 'lane3TS685II_30nt_Ttrim', 'lane3TS801III_30nt_Ttrim', 'lane3TS801I_30nt_Ttrim', 'all'])

    df4 = pd.read_csv('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneProb.txt', sep = '\s+', header = None, names = ['#gene', 'chromo','position','strand', 'distToCDSstop', 'distToCDSstart', 'avgGcount', 'AGcount', 'Acount','Gcount', 'Lane8ByIB_30nt_Ttrim', 'Lane8ByIIB_30nt_Ttrim', 'Lane8ByIIIB_30nt_Ttrim', 'Lane8TS1248IB_30nt_Ttrim', 'Lane8TS1248IIIB_30nt_Ttrim', 'Lane8TS685IB_30nt_Ttrim', 'Lane8TS685IIB_30nt_Ttrim', 'Lane8TS801IB_30nt_Ttrim', 'Lane8TS801IIB_30nt_Ttrim', 'Lane8TS801IIIB_30nt_Ttrim', 'lane3BY4741III_30nt_Ttrim', 'lane3TS1248II_30nt_Ttrim', 'lane3TS685III_30nt_Ttrim', 'lane3TS685II_30nt_Ttrim', 'lane3TS801III_30nt_Ttrim', 'lane3TS801I_30nt_Ttrim', 'all'])

    data4  = data4.drop(['strand', 'avgGcount', 'AGcount', 'Acount', 'Gcount', 'Lane8ByIB_30nt_Ttrim', 'Lane8ByIIB_30nt_Ttrim', 'Lane8ByIIIB_30nt_Ttrim', 'Lane8TS1248IB_30nt_Ttrim', 'Lane8TS1248IIIB_30nt_Ttrim', 'Lane8TS685IB_30nt_Ttrim', 'Lane8TS685IIB_30nt_Ttrim', 'Lane8TS801IB_30nt_Ttrim', 'Lane8TS801IIB_30nt_Ttrim', 'Lane8TS801IIIB_30nt_Ttrim', 'lane3BY4741III_30nt_Ttrim', 'lane3TS1248II_30nt_Ttrim', 'lane3TS685III_30nt_Ttrim', 'lane3TS685II_30nt_Ttrim', 'lane3TS801III_30nt_Ttrim', 'lane3TS801I_30nt_Ttrim'], axis = 1)

    df4 = df4.drop(['strand', 'avgGcount', 'AGcount', 'Acount','Gcount', 'Lane8ByIB_30nt_Ttrim', 'Lane8ByIIB_30nt_Ttrim', 'Lane8ByIIIB_30nt_Ttrim', 'Lane8TS1248IB_30nt_Ttrim', 'Lane8TS1248IIIB_30nt_Ttrim', 'Lane8TS685IB_30nt_Ttrim', 'Lane8TS685IIB_30nt_Ttrim', 'Lane8TS801IB_30nt_Ttrim', 'Lane8TS801IIB_30nt_Ttrim', 'Lane8TS801IIIB_30nt_Ttrim', 'lane3BY4741III_30nt_Ttrim', 'lane3TS1248II_30nt_Ttrim', 'lane3TS685III_30nt_Ttrim', 'lane3TS685II_30nt_Ttrim', 'lane3TS801III_30nt_Ttrim', 'lane3TS801I_30nt_Ttrim'], axis = 1)


    d1 = []
    for m in range(len(data)):
        if (m == 0):
            d1.append((data['all'][m]))
        else:
            d1.append((data['all'][m]-data['all'][m-1]))

    data['p_indep'] = d1

    d2 = []
    for h in range(len(data2)):
        if (h == 0):
            d2.append((data2['all'][h]))
        else:
            d2.append((data2['all'][h]-data2['all'][h-1]))

    data2['p_indep'] = d2

    d3 = []
    for r in range(len(data3)):
        if (r == 0):
            d3.append((data3['all'][r]))
        else:
            d3.append((data3['all'][r]-data3['all'][r-1]))

    data3['p_indep'] = d3

    d4 = []
    for w in range(len(data4)):
        if (w == 0):
            d4.append((data4['all'][w]))
        else:
            d4.append((data4['all'][w]-data4['all'][w-1]))

    data4['p_indep'] = d4

    if (data.position[0] > data.position[1]):
        antisense = True
    else:
        antisense = False

    print(type(upstreamBuf))
    upstreamBuf = int(upstreamBuf)
    print(type(upstreamBuf))

    if (antisense==True):
        CDS1 = data['position'][0] + data['distToCDSstart'][0]
        gen_pos = CDS1 + upstreamBuf
        df_comp['aligned_pos'] = gen_pos - df_comp.Position
    elif (antisense==False):
        CDS1 = data['position'][0] - data['distToCDSstart'][0]
        gen_pos = CDS1 - upstreamBuf
        df_comp['aligned_pos'] = df_comp.Position + gen_pos

    print(antisense)

    cumul2 = []

    for y in range(len(df_comp)):
        if (y == 0):
            cumul2.append(df_comp.pASiteT[0])
        else:
            cumul2.append(cumul2[y-1]+(1 - cumul2[y-1])*df_comp.pASiteT[y])

    df_comp['cumul2'] = cumul2
    df_comp['cumul2'] = df_comp['cumul2']/df_comp.cumul2[len(df_comp)-1]

    if (antisense == True):
        cds1 = data.position[0]+data.distToCDSstart[0]
        cds2 = data.position[0]+data.distToCDSstop[0]
    elif (antisense == False):
        cds1 = data.position[0]-data.distToCDSstart[0]
        cds2 = data.position[0]-data.distToCDSstop[0]
    
    if (antisense == True):
        indep_c = figure(x_range = (df_comp['aligned_pos'][0], df_comp['aligned_pos'][len(df_comp)-1]))
        c0 = indep_c.line(data['position'], data['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        c1 = indep_c.line(data2['position'], data2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        c2 = indep_c.line(data3['position'], data3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        c3 = indep_c.line(data4['position'], data4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        c4 = indep_c.line(df_comp['aligned_pos'], df_comp['cumulative'], color = '#000000', legend = '?', alpha = 1)
        indep_c.add_layout(Arrow(end=VeeHead(size=25, fill_alpha=0.4, line_alpha=0), line_color="black", x_start=cds1, y_start=-0.05, x_end=cds2, y_end=-0.05, line_alpha = 0.4, line_width = 20))
        indep_c.below[0].formatter.use_scientific = False
        indep_c.legend.location = "top_left"
        indep_c.legend.click_policy="hide"

        indep_p = figure(x_range = indep_c.x_range)
        p0 = indep_p.line(data['position'], data['p_indep'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        p1 = indep_p.line(data2['position'], data2['p_indep'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        p2 = indep_p.line(data3['position'], data3['p_indep'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        p3 = indep_p.line(data4['position'], data4['p_indep'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        p4 = indep_p.line(df_comp['aligned_pos'], df_comp['pASiteT'], color = '#000000', legend = '?', alpha = 1)
        indep_p.below[0].formatter.use_scientific = False
        indep_p.legend.location = "top_left"
        indep_p.legend.click_policy="hide"

        staged_c = figure(x_range = (df_comp['aligned_pos'][0], df_comp['aligned_pos'][len(df_comp)-1]))
        sc0 = staged_c.line(data['position'], data['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        sc1 = staged_c.line(data2['position'], data2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        sc2 = staged_c.line(data3['position'], data3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        sc3 = staged_c.line(data4['position'], data4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        sc4 = staged_c.line(df_comp['aligned_pos'], df_comp['cumul2'], color = '#000000', legend = '?', alpha = 1)
        staged_c.add_layout(Arrow(end=VeeHead(size=25, fill_alpha=0.4, line_alpha=0), line_color="black", x_start=cds1, y_start=-0.05, x_end=cds2, y_end=-0.05, line_alpha = 0.4, line_width = 20))
        staged_c.below[0].formatter.use_scientific = False
        staged_c.legend.location = "top_left"
        staged_c.legend.click_policy="hide"

        staged_p = figure(x_range = staged_c.x_range)
        sp0 = staged_p.line(df['position'], df['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        sp1 = staged_p.line(df2['position'], df2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        sp2 = staged_p.line(df3['position'], df3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        sp3 = staged_p.line(df4['position'], df4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        sp4 = staged_p.line(df_comp['aligned_pos'], df_comp['pASiteT'], color = '#000000', legend = '?', alpha = 1)
        staged_p.below[0].formatter.use_scientific = False
        staged_p.legend.location = "top_left"
        staged_p.legend.click_policy="hide"

    elif (antisense == False):
        indep_c = figure()
        c0 = indep_c.line(data['position'], data['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        c1 = indep_c.line(data2['position'], data2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        c2 = indep_c.line(data3['position'], data3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        c3 = indep_c.line(data4['position'], data4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        c4 = indep_c.line(df_comp['aligned_pos'], df_comp['cumulative'], color = '#000000', legend = '?', alpha = 1)
        indep_c.add_layout(Arrow(end=VeeHead(size=25, fill_alpha=0.4, line_alpha = 0), line_color="black", x_start=cds1, y_start=-0.05, x_end=cds2, y_end=-0.05, line_alpha = 0.4, line_width = 20))
        indep_c.below[0].formatter.use_scientific = False
        indep_c.legend.location = "top_left"
        indep_c.legend.click_policy="hide"

        indep_p = figure(x_range = indep_c.x_range)
        p0 = indep_p.line(data['position'], data['p_indep'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        p1 = indep_p.line(data2['position'], data2['p_indep'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        p2 = indep_p.line(data3['position'], data3['p_indep'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        p3 = indep_p.line(data4['position'], data4['p_indep'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        p4 = indep_p.line(df_comp['aligned_pos'], df_comp['pASiteT'], color = '#000000', legend = '?', alpha = 1)
        indep_p.below[0].formatter.use_scientific = False
        indep_p.legend.location = "top_left"
        indep_p.legend.click_policy="hide"

        staged_c = figure()
        sc0 = staged_c.line(data['position'], data['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        sc1 = staged_c.line(data2['position'], data2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        sc2 = staged_c.line(data3['position'], data3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        sc3 = staged_c.line(data4['position'], data4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        sc4 = staged_c.line(df_comp['aligned_pos'], df_comp['cumul2'], color = '#000000', legend = '?', alpha = 1)
        staged_c.add_layout(Arrow(end=VeeHead(size=25, fill_alpha=0.4, line_alpha=0), line_color="black", x_start=cds1, y_start=-0.05, x_end=cds2, y_end=-0.05, line_alpha = 0.4, line_width = 20))
        staged_c.below[0].formatter.use_scientific = False
        staged_c.legend.location = "top_left"
        staged_c.legend.click_policy="hide"

        staged_p = figure()
        sp0 = staged_p.line(df['position'], df['all'], color = '#4dac26', legend = 'pcf11_DRS', alpha = 1)
        sp1 = staged_p.line(df2['position'], df2['all'], color = '#b8e186', legend = 'Decay1', alpha = 1)
        sp2 = staged_p.line(df3['position'], df3['all'], color = '#f1b6da', legend = 'Decay2', alpha = 1)
        sp3 = staged_p.line(df4['position'], df4['all'], color = '#d01c8b', legend = 'Steinmetz', alpha = 1)
        sp4 = staged_p.line(df_comp['aligned_pos'], df_comp['pASiteT'], color = '#000000', legend = '?', alpha = 1)
        staged_p.below[0].formatter.use_scientific = False
        staged_p.legend.location = "top_left"
        staged_p.legend.click_policy="hide"

    col1 = column(children=[indep_c, indep_p], sizing_mode='stretch_both')
    col2 = column(children=[s1, s2, s3, s4, s5], sizing_mode='stretch_both')

    col3 = column(children=[staged_c, staged_p], sizing_mode='stretch_both')
    col4 = column(children=[s1, s2, s3, s4, s5], sizing_mode='stretch_both')

    l1 = gridplot([[col1, col2]])
    l2 = gridplot([[col3, col4]])

    tab1 = Panel(child=l1,title="Independent")
    tab2 = Panel(child=l2,title="Staged")
    tabs = Tabs(tabs=[ tab1, tab2 ])

    print(os.listdir('/var/kristoph_flask/data/'))

    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneData.txt')
    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_pcf11_specGeneProb.txt')

    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneData.txt')
    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_decay_specGeneProb.txt')

    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneData.txt')
    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_decay2_specGeneProb.txt')

    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneData.txt')
    os.remove('/var/kristoph_flask/data/'+gene_from_genome+'_steinmetz_specGeneProb.txt')

    return(tabs)
Ejemplo n.º 28
0
def protein_annotation(first):
    protein_locs = []
    protein_names = []
    protein_lengths = []

    # Shades in every other protein region. Provides warning if proteins overlap.
    for i in range(0, proteins.shape[0]):
        if (i == 0):
            x1 = 0
        elif (proteins.iloc[i, 1] < proteins.iloc[i - 1, 2]) and first:
            print('WARNING: Protein-' + str(proteins.iloc[i, 0]) +
                  ' is overlapping with Protein-' +
                  str(proteins.iloc[i - 1, 0]))
            print(
                'Analysis will continue but the visualization for these two proteins will look a little funny. Often the fix for this is simply deleting the small ancilary proteins that overlapping from the gff file and using the -f and -g flags. For more help see the readme.'
            )
            x1 = proteins.iloc[i, 1]
        else:
            x1 = proteins.iloc[i, 1]
        if (i == proteins.shape[0] - 1):
            x2 = proteins.iloc[i, 2]
        else:
            x2 = proteins.iloc[(i + 1), 1]
        if (i % 2 == 0):
            genome_plot.add_layout(
                BoxAnnotation(left=x1,
                              right=x2,
                              fill_alpha=0.1,
                              fill_color='green'))
        protein_locs.append((x1 + x2) / 2)
        protein_lengths.append(x2 - x1)
        protein_names.append(proteins.iloc[i, 0])

    if (os.stat("mat_peptides_additions.txt").st_size != 0):
        # Makes arrows for mature peptides.
        for i in range(0, mat_peptides_list.shape[0]):
            x1 = mat_peptides_list.iloc[i, 1]
            x2 = mat_peptides_list.iloc[i, 2]
            genome_plot.add_layout(
                Arrow(end=VeeHead(size=20,
                                  fill_color="cadetblue",
                                  fill_alpha=0.3,
                                  line_alpha=0),
                      line_color="cadetblue",
                      line_width=20,
                      x_start=x1,
                      x_end=x2,
                      y_start=5,
                      y_end=5,
                      line_alpha=0.3))

    # Adds protein labels as tick marks.
    genome_plot.xaxis.ticker = protein_locs
    protein_locs2 = []
    for protein_loc in protein_locs:
        str_protein_loc = str(protein_loc)
        ## print("old str_protein_loc" + str_protein_loc)
        if ".0" in str_protein_loc:
            str_protein_loc = str_protein_loc.split('.')[0]
            ## print("split" + str_protein_loc)
            protein_locs2.append(int(str_protein_loc))
        else:
            protein_locs2.append(float(str_protein_loc))
    genome_plot.xaxis.major_label_overrides = dict(
        zip(protein_locs2, protein_names))
    return protein_names, protein_lengths
Ejemplo n.º 29
0
 def _update_lines(self, line_size=0.25, line_scale=2.0):
     for i, l in enumerate(self.lines):
         shiftedWave = _airtovac(l['lambda']) * (1.0 + self.z)
         visible = (self._line_in_range(shiftedWave)
                    and ((l['emission'] and self._emission) or
                         (self._absorption and not l['emission'])))
         shiftedWave_y = 0.0
         for channel in self.spectra.bands:
             sign = -1.0
             if l['emission']: sign = 1.0
             y_envelope = self.xdata[channel].data[
                 'model'] + sign * line_scale / np.sqrt(
                     self.xdata[channel].data['ivar'])
             if self.xdata[channel].data['wave'].min(
             ) < shiftedWave < self.xdata[channel].data['wave'].max():
                 shiftedWave_y = np.interp(shiftedWave,
                                           self.xdata[channel].data['wave'],
                                           y_envelope)
                 break
         if l['emission']:
             lc = 'blue'
             y_start = shiftedWave_y + line_size
             y_end = shiftedWave_y
         else:
             lc = 'red'
             y_start = shiftedWave_y - line_size
             y_end = shiftedWave_y
         if 'span' in l:
             l['source'].data = dict(x_start=[shiftedWave],
                                     y_start=[y_start],
                                     x_end=[shiftedWave],
                                     y_end=[y_end])
             l['span'].visible = visible
             l['label'].x = shiftedWave
             l['label'].y = y_start
             l['label'].visible = visible
         else:
             l['source'] = ColumnDataSource(data=dict(x_start=[shiftedWave],
                                                      y_start=[y_start],
                                                      x_end=[shiftedWave],
                                                      y_end=[y_end]))
             l['span'] = Arrow(end=VeeHead(size=2,
                                           line_color=lc,
                                           line_alpha=0.3,
                                           fill_color=lc,
                                           fill_alpha=0.3),
                               line_color=lc,
                               line_width=2,
                               line_alpha=0.3,
                               x_start='x_start',
                               y_start='y_start',
                               x_end='x_end',
                               y_end='y_end',
                               source=l['source'],
                               visible=visible)
             l['label'] = Label(x=shiftedWave,
                                y=y_start,
                                text=l['name'],
                                text_color=lc,
                                text_alpha=0.5,
                                visible=visible)
             self.specplot.add_layout(l['span'])
             self.specplot.add_layout(l['label'])
def test_arrow(output_file_url, selenium, screenshot):

    # Have to specify x/y range as labels aren't included in the plot area solver
    plot = figure(height=HEIGHT,
                  width=WIDTH,
                  x_range=(0, 10),
                  y_range=(0, 10),
                  tools='',
                  toolbar_location="above")

    arrow1 = Arrow(x_start=1,
                   y_start=3,
                   x_end=6,
                   y_end=8,
                   line_color='green',
                   line_alpha=0.7,
                   line_dash='8 4',
                   line_width=5,
                   end=OpenHead())
    arrow1.end.line_width = 8

    arrow2 = Arrow(x_start=2,
                   y_start=2,
                   x_end=7,
                   y_end=7,
                   start=NormalHead(),
                   end=VeeHead())
    arrow2.start.fill_color = 'indigo'
    arrow2.end.fill_color = 'orange'
    arrow2.end.size = 50

    plot.add_layout(arrow1)
    plot.add_layout(arrow2)

    # test arrow body clipping
    plot.add_layout(
        Arrow(start=VeeHead(line_width=1, fill_color="white"),
              x_start=6,
              y_start=4,
              x_end=8,
              y_end=5,
              line_width=10))
    plot.add_layout(
        Arrow(start=NormalHead(line_width=1, fill_color="white"),
              x_start=6,
              y_start=3,
              x_end=8,
              y_end=4,
              line_width=10))
    plot.add_layout(
        Arrow(start=OpenHead(line_width=1),
              x_start=6,
              y_start=2,
              x_end=8,
              y_end=3,
              line_width=10))

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)

    # Take screenshot
    screenshot.assert_is_valid()