Пример #1
0
def population():
    xdr = FactorRange(factors=years)
    ydr = DataRange1d()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                plot_width=600,
                plot_height=150,
                toolbar_location=None)

    plot.add_layout(CategoricalAxis(major_label_orientation=pi / 4), 'below')

    known = Line(x="x", y="y", line_color="violet", line_width=2)
    known_glyph = plot.add_glyph(source_known, known)

    predicted = Line(x="x",
                     y="y",
                     line_color="violet",
                     line_width=2,
                     line_dash="dashed")
    predicted_glyph = plot.add_glyph(source_predicted, predicted)

    legend = Legend(location="bottom_right",
                    items=[("known", [known_glyph]),
                           ("predicted", [predicted_glyph])])
    plot.add_layout(legend)

    return plot
Пример #2
0
def population():
    xdr = FactorRange(factors=years)
    ydr = DataRange1d()

    plot = Plot(title=None,
                x_range=xdr,
                y_range=ydr,
                plot_width=800,
                plot_height=200)

    plot.add_layout(CategoricalAxis(major_label_orientation=pi / 4), 'below')

    line_known = Line(x="x", y="y", line_color="violet", line_width=2)
    line_known_glyph = plot.add_glyph(source_known, line_known)

    line_predicted = Line(x="x",
                          y="y",
                          line_color="violet",
                          line_width=2,
                          line_dash="dashed")
    line_predicted_glyph = plot.add_glyph(source_predicted, line_predicted)

    plot.add_layout(
        Legend(
            location="bottom_right",
            legends=[("known", [line_known_glyph]),
                     ("predicted", [line_predicted_glyph])],
        ))

    return plot
Пример #3
0
def test_line_rendering_with_selected_points(output_file_url, selenium,
                                             screenshot):
    plot = Plot(plot_height=400,
                plot_width=400,
                x_range=Range1d(0, 4),
                y_range=Range1d(-1, 1))

    x = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]
    y = [
        0., 0.84147098, 0.90929743, 0.14112001, -0.7568025, -0.95892427,
        -0.2794155, 0.6569866, 0.98935825
    ]  # sin(2*x)

    source = ColumnDataSource(data=dict(x=x, y=y))
    plot.add_glyph(source, Circle(x='x', y='y'))
    plot.add_glyph(source, Line(x='x', y='y'))

    plot.add_tools(BoxSelectTool())

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

    # Perform selection and take screenshot
    perform_box_selection(selenium, (0, 100), (400, 250))
    screenshot.assert_is_valid()
Пример #4
0
def make_plot(title, xname, yname):
    plot = Plot(x_range=xdr,
                y_range=ydr,
                width=400,
                height=400,
                background_fill_color='#efefef')
    plot.title.text = title

    xaxis = LinearAxis(axis_line_color=None)
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_line_color=None)
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    line = Line(x='x', y='y', line_color="#666699", line_width=2)
    plot.add_glyph(lines_source, line)

    circle = Circle(x=xname,
                    y=yname,
                    size=12,
                    fill_color="#cc6633",
                    line_color="#cc6633",
                    fill_alpha=0.5)
    plot.add_glyph(circles_source, circle)

    return plot
Пример #5
0
def altitude_profile(data):
    plot = Plot(plot_width=800, plot_height=400)
    plot.title.text = "%s - Altitude Profile" % name
    plot.y_range.range_padding = 0

    xaxis = LinearAxis(axis_label="Distance (km)")
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_label="Altitude (m)")
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))  # x grid
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))  # y grid

    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    X, Y = data.dist, data.alt
    y0 = min(Y)

    patches_source = ColumnDataSource(
        dict(xs=[[X[i], X[i + 1], X[i + 1], X[i]] for i in range(len(X[:-1]))],
             ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))],
             color=data.colors[:-1]))
    patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color")
    plot.add_glyph(patches_source, patches)

    line_source = ColumnDataSource(dict(x=data.dist, y=data.alt))
    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    return plot
def pages_queried_timeseries(df, plot_width=600, plot_height=200, rule='1T'):
    ts = df[['url']].resample(rule, how='count').cumsum()
    ts.index = ts.index.tz_convert(tzlocal())
    #Bokeh=0.10.0 misencodes timestamps, so we have to shift by
    ts.index = ts.index.shift(ts.index[0].utcoffset().total_seconds(), freq="S")
    ts = pd.concat([ts[:1], ts]) # prepend 0-value for Line chart compat
    ts.iloc[0]['url'] = 0

    formatter = DatetimeTickFormatter(formats=DATETIME_FORMAT)
    ticker = DatetimeTicker(desired_num_ticks=3)

    source = ColumnDataSource(ts)

    plot = Plot(plot_width=plot_width, plot_height=plot_height,
                x_range=DataRange1d(range_padding=0.1),
                y_range=DataRange1d(start=0),
                **PLOT_FORMATS)
    plot.add_glyph(
        source,
        Line(x='retrieved', y='url', **LINE_FORMATS)
    )
    plot.add_layout(
        DatetimeAxis(axis_label="Date Retrieved", formatter=formatter,
                     ticker=ticker, **AXIS_FORMATS),
        'below')
    plot.add_layout(LinearAxis(axis_label="Total Pages", **AXIS_FORMATS), 'left')

    return plot
Пример #7
0
def construct_line(source, value_string, line_color=BLUE):
    xdr = Range1d(1990, 2013)
    ydr = Range1d(0, 100)
    line_plot = Plot(x_range=xdr,
                     y_range=ydr,
                     title="",
                     plot_width=250,
                     plot_height=150,
                     min_border_top=10,
                     min_border_left=50,
                     **PLOT_FORMATS)
    xaxis = LinearAxis(SingleIntervalTicker(interval=50), **AXIS_FORMATS)
    yaxis = LinearAxis(SingleIntervalTicker(interval=10), **AXIS_FORMATS)
    line_plot.add_layout(xaxis, 'left')
    line_plot.add_layout(yaxis, 'below')

    line = Line(
        x='year',
        y=value_string,
        line_width=5,
        line_cap="round",
        line_color=line_color,
    )
    line_plot.add_glyph(source, line)

    return line_plot
Пример #8
0
def trail_map(data):
    lon = (min(data.lon) + max(data.lon)) / 2
    lat = (min(data.lat) + max(data.lat)) / 2

    map_options = GMapOptions(lng=lon, lat=lat, zoom=13)
    plot = GMapPlot(plot_width=800,
                    plot_height=800,
                    map_options=map_options,
                    api_key=API_KEY)
    plot.title.text = "%s - Trail Map" % name
    plot.x_range = Range1d()
    plot.y_range = Range1d()
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    line_source = ColumnDataSource(dict(x=data.lon, y=data.lat,
                                        dist=data.dist))
    line = Line(x="x", y="y", line_color="blue", line_width=2)
    plot.add_glyph(line_source, line)

    if plot.api_key == "GOOGLE_API_KEY":
        plot.add_layout(
            Label(x=240,
                  y=700,
                  x_units='screen',
                  y_units='screen',
                  text='Replace GOOGLE_API_KEY with your own key',
                  text_color='red'))

    return plot
Пример #9
0
def plot(source):
    fig = setup_figure()

    # plot data
    rect = Rect(x='dates',
                y='y',
                width='w',
                height='h',
                line_width=0,
                fill_color='colors',
                fill_alpha=1)
    fig.add_glyph(source, rect)

    line = Line(x='dates', y='avg_to_bed_times')
    fig.add_glyph(source, line)
    # circ = Circle(x='dates', y='avg_to_bed_times', size=3)
    # fig.add_glyph(source, circ)
    line = Line(x='dates', y='avg_get_up_times')
    fig.add_glyph(source, line)
    # circ = Circle(x='dates', y='avg_get_up_times', size=3)
    # fig.add_glyph(source, circ)

    # plot select
    select = figure(
        # background_fill_color='#333333'
        title="",
        plot_width=PLOT_WIDTH,
        plot_height=80,
        toolbar_location=None,  # tools="xwheel_pan",
        x_axis_type="datetime",  # y_axis_type=None,
        x_axis_location=None,
        y_axis_location=None,
        y_range=fig.y_range,
    )
    range_tool = RangeTool(x_range=fig.x_range)
    select.add_tools(range_tool)

    select.line(x=[dt(2013, 5, 1), dt.now()], y=[0, 0], color=None)
    select.add_glyph(source, rect)
    select.ygrid.grid_line_color = None
    select.toolbar.active_multi = range_tool
    select.yaxis.ticker = []

    return fig, select
Пример #10
0
def add_lo_economic_growth_lines(plot, parameter):
    sources, _ = get_lo_national_data(parameter)
    line_renderers = {}
    for scenario in scenarios:
        source = sources[scenario]
        line = Line(
            x='t', y=parameter, line_color=scenarios_colors[scenario],
            line_width=2, line_cap='round', line_join='round', line_dash='dashed'
        )
        line_renderer = plot.add_glyph(source, line)
        line_renderers[scenario] = line_renderer
    return (plot, line_renderers)
Пример #11
0
    def get_y_module(self):
        p2 = figure(title="Prediction Result",
                    tools=self.tools,
                    tooltips=self.tooltips,
                    plot_width=500,
                    plot_height=200)
        p2 = self.get_attribute(p2)
        c1 = p2.line('index',
                     self.y_pred_name,
                     legend_label="pred Y",
                     color="#C9C462",
                     name="pred Y",
                     source=self.source,
                     line_width=1.5)
        c1.nonselection_glyph = Line(
            line_color="#C9C462",
            line_alpha=0.2)  # when selected, change alpha
        # c1.selection_glyph = Line(line_color="#C9C462", line_width=1.5)

        c2 = p2.circle('index',
                       self.config['y_name'],
                       source=self.source,
                       name="real Y",
                       legend_label="real Y",
                       size=5,
                       color="#FF4040")
        c2.nonselection_glyph = Circle(fill_color="#FF4040",
                                       fill_alpha=0.2,
                                       line_color=None,
                                       size=5)
        # c2.selection_glyph = Circle(fill_color='orange', line_color=None, size=10, line_width=15)

        c2 = p2.circle('index',
                       self.y_pred_name,
                       source=self.source,
                       name="pred Y",
                       size=5,
                       color="#C9C462")
        c2.nonselection_glyph = Circle(fill_color="#C9C462",
                                       fill_alpha=0.2,
                                       line_color=None,
                                       size=5)
        vline = Span(location=self.split_loc,
                     dimension='height',
                     line_color='seagreen',
                     line_width=3)
        p2.add_layout(vline)
        p2.legend.location = "top_left"
        p2.legend.click_policy = "hide"
        p2.legend.background_fill_alpha = 0.8
        return p2
Пример #12
0
def large_plot(n):
    from bokeh.models import (
        Plot, LinearAxis, Grid, GlyphRenderer,
        ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool,
        BoxSelectTool, SaveTool, ResetTool
    )
    from bokeh.models import Column, Line

    col = Column()
    objects = set([col])

    for i in range(n):
        source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(x_range=xdr, y_range=ydr)
        xaxis = LinearAxis()
        plot.add_layout(xaxis, "below")
        yaxis = LinearAxis()
        plot.add_layout(yaxis, "left")
        xgrid = Grid(dimension=0)
        plot.add_layout(xgrid, "center")
        ygrid = Grid(dimension=1)
        plot.add_layout(ygrid, "center")
        tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter]
        glyph = Line(x='x', y='y')
        renderer = GlyphRenderer(data_source=source, glyph=glyph)
        plot.renderers.append(renderer)
        pan = PanTool()
        zoom_in = ZoomInTool()
        zoom_out = ZoomOutTool()
        wheel_zoom = WheelZoomTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        save = SaveTool()
        reset = ResetTool()
        tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset]
        plot.add_tools(*tools)
        col.children.append(plot)
        objects |= set([
            xdr, ydr,
            xaxis, yaxis,
            xgrid, ygrid,
            renderer, renderer.view, glyph,
            source, source.selected, source.selection_policy,
            plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title,
            box_zoom.overlay, box_select.overlay,
        ] + tickers + tools)

    return col, objects
Пример #13
0
 def __init__(self, stave, name, value, *args, **kwargs):
     super().__init__(stave, name)
     self.value = value
     self.color = kwargs.setdefault('color', 'green')
     self.width = kwargs.setdefault('width', 1)
     self.dash = kwargs.setdefault('dash', 'solid')
     self.kw_ = {
         'name': self.name,
         'line_color': self.color,
         'line_width': self.width,
         'line_dash': self.dash
     }
     self.line = Line(x='x', y='y', **self.kw_)
     self.line_source = ColumnDataSource(data=dict(x=[], y=[]))
Пример #14
0
def _get_national_scenario_line_plot(sources, data, parameter=None, y_ticks=None, plot_width=600, grid=True, end_factor=None, y_range=None, include_bau=True):
    if not y_range:
        y_range = get_y_range(data)

    plot = Plot(
        x_range=get_year_range(end_factor),
        y_range=y_range,
        plot_width=plot_width,
        **PLOT_FORMATS
    )
    plot = add_axes(plot, y_ticks, color=dark_grey, grid=grid)
    hit_renderers = []
    line_renderers = {}
    if include_bau:
        sc = scenarios
    else:
        sc = scenarios_no_bau
    for scenario in sc:
        source = sources[scenario]
        line = Line(
            x='t', y=parameter, line_color=scenarios_colors[scenario],
            line_width=2, line_cap='round', line_join='round'
        )
        circle = Circle(
            x='t', y=parameter, size=4,
            line_color=scenarios_colors[scenario], line_width=0.5, line_alpha=deselected_alpha,
            fill_color=scenarios_colors[scenario], fill_alpha=0.6
        )
        # invisible circle used for hovering
        hit_target = Circle(
            x='t', y=parameter, size=20,
            line_color=None, fill_color=None
        )
        scenario_label = Text(
            x=value(source.data['t'][-1] + 0.8), y=value(source.data[parameter][-1] * 0.98), text=value(names[scenario]),
            text_color=scenarios_colors[scenario], text_font_size="8pt",
        )

        hit_renderer = plot.add_glyph(source, hit_target)
        hit_renderers.append(hit_renderer)
        line_renderer = plot.add_glyph(source, line)
        line_renderers[scenario] = line_renderer
        plot.add_glyph(source, circle)
        plot.add_glyph(scenario_label)

    plot.add_tools(HoverTool(tooltips="@%s{0,0} (@t)" % parameter, renderers=hit_renderers))
    return (plot, line_renderers)
Пример #15
0
def set_glyphs(colors, column_names, column_time, plot, pos, source):
    for i, name in enumerate(column_names):
        color = colors[i]
        line = Line(x=column_time,
                    y=name,
                    line_width=1,
                    line_alpha=.7,
                    line_color=color)

        plot.add_layout(
            LinearAxis(y_range_name=name,
                       major_label_text_color=color,
                       axis_line_color=color,
                       major_tick_line_color=color,
                       minor_tick_line_color=color), pos[i])

        plot.add_glyph(source, line, y_range_name=name, name=name)
Пример #16
0
def get_pm25_national_plot(plot_width=600, end_factor=None, grid=True):
    sources, data = get_pm25_national_data()
    y_ticks = [30, 40, 50, 60, 70]
    y_range = Range1d(30, 72)
    pm25, line_renderers = _get_national_scenario_line_plot(
        sources, data, 'PM25_exposure',
        y_ticks=y_ticks, plot_width=plot_width, grid=grid, end_factor=end_factor, y_range=y_range
    )
    # Add Targets
    pm25.add_glyph(
        ColumnDataSource(data=dict(x=[2010, 2030], y=[35, 35])),
        Line(x='x', y='y', line_width=2, line_dash='dotdash'),
    )
    pm25.add_glyph(
        ColumnDataSource(data=dict(x=[2010.5], y=[32.5], text=['PM2.5 target'])),
        Text(x='x', y='y', text='text', text_font_size='8pt'),
        level='overlay',
    )
    return (pm25, line_renderers)
    def st_plot_wind_pressure(self):
        """
        Plot wind pressure along the sign face.
        The value may change for 45 degrees and a large aspect ratio.
        """
        #Set up plot
        plot = Plot()

        #Graph of Drag Factors along sign
        x = np.linspace(0, self.sign_w, num=50)
        if self.wind.loadcase is Cases.FAT:
            y = [
                0.5 * 1.2 * self.wind.V_sit_beta.value**2 * self.C_dyn / 1000 *
                self.C_fig for ix in x
            ]
        else:
            y = [
                0.5 * 1.2 * self.wind.V_sit_beta.value**2 *
                self.C_dyn * self.K_p / 1000 * self.C_pn_func(
                    self.sign_w, self.sign_h, self.wind.Wind_mult.height, ix)
                for ix in x
            ]
        source = ColumnDataSource(dict(x=x, y=y))
        drag_factor = Line(x='x', y='y', line_color="#f46d43", line_width=3)
        plot.add_glyph(source, drag_factor)

        #Fille area under line
        fill_under = Band(base='x',
                          upper='y',
                          source=source,
                          level='underlay',
                          fill_color='#55FF88')
        plot.add_layout(fill_under)

        #Plot setup
        plot.add_layout(LinearAxis(), 'below')
        plot.add_layout(LinearAxis(), 'left')
        plot.xaxis.axis_label = "Distance along sign (m)"
        plot.yaxis.axis_label = "Wind Pressure (kPa)"
        plot.y_range = Range1d(0, max(y) * 1.3)

        return plot
Пример #18
0
def get_nonfossil(plot_width=750, end_factor=5, grid=True, include_bau=False):
    plot, line_renderers = get_national_scenario_line_plot(
        parameter='energy_nonfossil_share',
        y_ticks=[10, 15, 20, 25],
        plot_width=plot_width,
        y_range=Range1d(8, 29),
        grid=grid,
        end_factor=end_factor,
        include_bau=include_bau
    )
    plot.add_glyph(
        ColumnDataSource(data=dict(x=[2010, 2030], y=[20, 20])),
        Line(x='x', y='y', line_width=2, line_dash='dotdash'),
    )
    plot.add_glyph(
        ColumnDataSource(data=dict(x=[2010.5], y=[20.2], text=['Non-fossil target'])),
        Text(x='x', y='y', text='text', text_font_size='8pt'),
    )

    return (plot, line_renderers)
Пример #19
0
def large_plot():
    source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1]))

    xdr = Range1d(start=0, end=1)
    xdr.tags.append("foo")
    xdr.tags.append("bar")

    ydr = Range1d(start=10, end=20)
    ydr.tags.append("foo")
    ydr.tags.append(11)

    plot = Plot(x_range=xdr, y_range=ydr)

    ydr2 = Range1d(start=0, end=100)
    plot.extra_y_ranges = {"liny": ydr2}

    circle = Circle(x="x", y="y", fill_color="red", size=5, line_color="black")
    plot.add_glyph(source, circle, name="mycircle")

    line = Line(x="x", y="y")
    plot.add_glyph(source, line, name="myline")

    rect = Rect(x="x", y="y", width=1, height=1, fill_color="green")
    plot.add_glyph(source, rect, name="myrect")

    plot.add_layout(DatetimeAxis(), 'below')
    plot.add_layout(LogAxis(), 'left')
    plot.add_layout(LinearAxis(y_range_name="liny"), 'left')

    plot.add_layout(Grid(dimension=0), 'left')
    plot.add_layout(Grid(dimension=1), 'left')

    plot.add_tools(
        BoxZoomTool(),
        PanTool(),
        SaveTool(),
        ResetTool(),
        WheelZoomTool(),
    )

    return plot
Пример #20
0
def plot_regions_comparison(regions_df, y_col, x_col):
    df_regions_plot = pd.DataFrame(index=regions_df[x_col].unique())

    plot = Plot(title=None,
                plot_width=1000,
                plot_height=600,
                min_border=0,
                toolbar_location='left')

    colors = itertools.cycle(Dark2_5)

    for region, df_region in regions_df.groupby("denominazione_regione"):
        print(df_region.set_index(x_col)[y_col])

        df_regions_plot.loc[df_region.set_index(x_col).index,
                            region] = df_region.set_index(x_col)[y_col].values

        source = ColumnDataSource(
            dict(x=df_region.set_index(x_col).index.values,
                 y=df_region.set_index(x_col)[y_col].values))
        glyph = Line(
            x="x",
            y="y",
            line_color=next(colors),
            line_width=2,
            line_alpha=0.7,
        )
        plot.add_glyph(source, glyph)

    xaxis = LinearAxis()
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis()
    plot.add_layout(yaxis, 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    curdoc().add_root(plot)
    show(plot)
Пример #21
0
def _make_base_plot(dfs, activities, x_range, plot_width=900):
    plot = Plot(
        x_range=x_range,
        y_range=Range1d(0, 11),
        outline_line_color=None,
        background_fill=COLOR_PRIMARY,
        border_fill=COLOR_PRIMARY,
        plot_width=plot_width,
        plot_height=150,
        min_border_top=0,
        toolbar_location=None,
    )

    yticker = BasicTicker(min_interval=3)
    close_ticker = DatetimeTicker(desired_num_ticks=8)
    close_ticks = DatetimeTickFormatter(
        formats={
            'years': ["%b"],
            'months': ["%b"],
            'days': ["%a %d %b"],
            'hours': ["%I%p %d %b"]
        }
    )

    plot.add_layout(LinearAxis(ticker=yticker, **AXIS_PROPERTIES), 'left')
    plot.add_layout(DatetimeAxis(formatter=close_ticks, ticker=close_ticker, **AXIS_PROPERTIES), 'below')
    plot.add_layout(Grid(dimension=1, ticker=yticker, grid_line_alpha=0.3))

    palette = get_palette(activities)

    for i, activity in enumerate(activities):
        source = dfs[activity]
        line = Line(
            line_color=palette[i],
            line_join='round', line_cap='round', line_width=5, line_alpha=0.75,
            x='timestamp', y='cumsum_hrs'
        )
        plot.add_glyph(source, line)

    return plot
Пример #22
0
def get_energy_mix_by_scenario(df, scenario, plot_width=700):
    plot = Plot(
        x_range=get_year_range(end_factor=15),
        y_range=Range1d(0, 4300),
        plot_width=plot_width,
        **PLOT_FORMATS
    )
    plot = add_axes(plot, [0, 2000, 4000], color=scenarios_colors[scenario])
    source = ColumnDataSource(df)

    for energy_mix_column in energy_mix_columns.keys():
        energy_name = energy_mix_columns[energy_mix_column]
        parameter = '%s_%s' % (scenario, energy_mix_column)
        line = Line(
            x='t', y=parameter, line_color='black',
            line_width=2, line_cap='round', line_join='round', line_alpha=0.8
        )
        circle = Circle(
            x='t', y=parameter, size=4, fill_color='black', fill_alpha=0.6
        )
        # invisible circle used for hovering
        hit_target = Circle(
            x='t', y=parameter, size=10, line_color=None, fill_color=None
        )
        scenario_label = Text(
            x=value(source.data['t'][-1] + 2), y=value(source.data[parameter][-1] - 200),
            text=value(energy_name), text_color='grey', text_font_size='8pt',
        )

        hit_renderer = plot.add_glyph(source, hit_target)
        plot.add_tools(HoverTool(tooltips="%s - @%s{0,0} (@t)" % (energy_name, parameter), renderers=[hit_renderer]))
        plot.add_glyph(source, line)
        plot.add_glyph(source, circle)
        plot.add_glyph(scenario_label)

    return plot
Пример #23
0
    def source_MA_30_plot(daily_source):
        
        t = Title()
        t.text = 'Source Count MA30'
        plot = Plot(
            title=t, plot_width=400, plot_height=300,
            min_border=0, toolbar_location=None)

        mean_30 = Line(x="index", y="count_MA_30", line_color="#abd3b1", line_width=3, line_alpha=0.6)
        plot.add_glyph(daily_source, mean_30)
        xaxis = LinearAxis()
        plot.add_layout(xaxis, 'below')
        plot.xaxis.formatter = DatetimeTickFormatter(
            hours=["%d %B %Y"],
            days=["%d %B %Y"],
            months=["%d %B %Y"],
            years=["%d %B %Y"],
        )
        plot.xaxis.major_label_orientation = pi / 4
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
        plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
        return plot
Пример #24
0
def create(palm):
    connected = False
    current_message = None
    stream_t = 0

    doc = curdoc()

    # Streaked and reference waveforms plot
    waveform_plot = Plot(
        title=Title(text="eTOF waveforms"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    waveform_plot.toolbar.logo = None
    waveform_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                            ResetTool())

    # ---- axes
    waveform_plot.add_layout(LinearAxis(axis_label='Photon energy, eV'),
                             place='below')
    waveform_plot.add_layout(LinearAxis(axis_label='Intensity',
                                        major_label_orientation='vertical'),
                             place='left')

    # ---- grid lines
    waveform_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    waveform_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    waveform_source = ColumnDataSource(
        dict(x_str=[], y_str=[], x_ref=[], y_ref=[]))
    waveform_ref_line = waveform_plot.add_glyph(
        waveform_source, Line(x='x_ref', y='y_ref', line_color='blue'))
    waveform_str_line = waveform_plot.add_glyph(
        waveform_source, Line(x='x_str', y='y_str', line_color='red'))

    # ---- legend
    waveform_plot.add_layout(
        Legend(items=[("reference",
                       [waveform_ref_line]), ("streaked",
                                              [waveform_str_line])]))
    waveform_plot.legend.click_policy = "hide"

    # Cross-correlation plot
    xcorr_plot = Plot(
        title=Title(text="Waveforms cross-correlation"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    xcorr_plot.toolbar.logo = None
    xcorr_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                         ResetTool())

    # ---- axes
    xcorr_plot.add_layout(LinearAxis(axis_label='Energy shift, eV'),
                          place='below')
    xcorr_plot.add_layout(LinearAxis(axis_label='Cross-correlation',
                                     major_label_orientation='vertical'),
                          place='left')

    # ---- grid lines
    xcorr_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    xcorr_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    xcorr_source = ColumnDataSource(dict(lags=[], xcorr=[]))
    xcorr_plot.add_glyph(xcorr_source,
                         Line(x='lags', y='xcorr', line_color='purple'))

    # ---- vertical span
    xcorr_center_span = Span(location=0, dimension='height')
    xcorr_plot.add_layout(xcorr_center_span)

    # Delays plot
    pulse_delay_plot = Plot(
        title=Title(text="Pulse delays"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    pulse_delay_plot.toolbar.logo = None
    pulse_delay_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                               ResetTool())

    # ---- axes
    pulse_delay_plot.add_layout(LinearAxis(axis_label='Pulse number'),
                                place='below')
    pulse_delay_plot.add_layout(
        LinearAxis(axis_label='Pulse delay (uncalib), eV',
                   major_label_orientation='vertical'),
        place='left',
    )

    # ---- grid lines
    pulse_delay_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_delay_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_delay_source = ColumnDataSource(dict(x=[], y=[]))
    pulse_delay_plot.add_glyph(pulse_delay_source,
                               Line(x='x', y='y', line_color='steelblue'))

    # Pulse lengths plot
    pulse_length_plot = Plot(
        title=Title(text="Pulse lengths"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location='right',
    )

    # ---- tools
    pulse_length_plot.toolbar.logo = None
    pulse_length_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                                ResetTool())

    # ---- axes
    pulse_length_plot.add_layout(LinearAxis(axis_label='Pulse number'),
                                 place='below')
    pulse_length_plot.add_layout(
        LinearAxis(axis_label='Pulse length (uncalib), eV',
                   major_label_orientation='vertical'),
        place='left',
    )

    # ---- grid lines
    pulse_length_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_length_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_length_source = ColumnDataSource(dict(x=[], y=[]))
    pulse_length_plot.add_glyph(pulse_length_source,
                                Line(x='x', y='y', line_color='steelblue'))

    # Image buffer slider
    def buffer_slider_callback(_attr, _old, new):
        message = receiver.data_buffer[new]
        doc.add_next_tick_callback(partial(update, message=message))

    buffer_slider = Slider(
        start=0,
        end=59,
        value=0,
        step=1,
        title="Buffered Image",
        callback_policy='throttle',
        callback_throttle=500,
    )
    buffer_slider.on_change('value', buffer_slider_callback)

    # Connect toggle button
    def connect_toggle_callback(state):
        nonlocal connected
        if state:
            connected = True
            connect_toggle.label = 'Connecting'
            connect_toggle.button_type = 'default'

        else:
            connected = False
            connect_toggle.label = 'Connect'
            connect_toggle.button_type = 'default'

    connect_toggle = Toggle(label="Connect", button_type='default', width=250)
    connect_toggle.on_click(connect_toggle_callback)

    # Intensity stream reset button
    def reset_button_callback():
        nonlocal stream_t
        stream_t = 1  # keep the latest point in order to prevent full axis reset

    reset_button = Button(label="Reset", button_type='default', width=250)
    reset_button.on_click(reset_button_callback)

    # Stream update coroutine
    async def update(message):
        nonlocal stream_t
        if connected and receiver.state == 'receiving':
            y_ref = message[receiver.reference].value[np.newaxis, :]
            y_str = message[receiver.streaked].value[np.newaxis, :]

            delay, length, debug_data = palm.process({
                '0': y_ref,
                '1': y_str
            },
                                                     debug=True)
            prep_data, lags, corr_res_uncut, _ = debug_data

            waveform_source.data.update(
                x_str=palm.energy_range,
                y_str=prep_data['1'][0, :],
                x_ref=palm.energy_range,
                y_ref=prep_data['0'][0, :],
            )

            xcorr_source.data.update(lags=lags, xcorr=corr_res_uncut[0, :])
            xcorr_center_span.location = delay[0]

            pulse_delay_source.stream({
                'x': [stream_t],
                'y': [delay]
            },
                                      rollover=120)
            pulse_length_source.stream({
                'x': [stream_t],
                'y': [length]
            },
                                       rollover=120)

            stream_t += 1

    # Periodic callback to fetch data from receiver
    async def internal_periodic_callback():
        nonlocal current_message
        if waveform_plot.inner_width is None:
            # wait for the initialization to finish, thus skip this periodic callback
            return

        if connected:
            if receiver.state == 'polling':
                connect_toggle.label = 'Polling'
                connect_toggle.button_type = 'warning'

            elif receiver.state == 'receiving':
                connect_toggle.label = 'Receiving'
                connect_toggle.button_type = 'success'

                # Set slider to the right-most position
                if len(receiver.data_buffer) > 1:
                    buffer_slider.end = len(receiver.data_buffer) - 1
                    buffer_slider.value = len(receiver.data_buffer) - 1

                if receiver.data_buffer:
                    current_message = receiver.data_buffer[-1]

        doc.add_next_tick_callback(partial(update, message=current_message))

    doc.add_periodic_callback(internal_periodic_callback, 1000)

    # assemble
    tab_layout = column(
        row(
            column(waveform_plot, xcorr_plot),
            Spacer(width=30),
            column(buffer_slider, row(connect_toggle, reset_button)),
        ),
        row(pulse_delay_plot, Spacer(width=10), pulse_length_plot),
    )

    return Panel(child=tab_layout, title="Stream")
Пример #25
0
    def __init__(self, **kwargs):
        self.source = ColumnDataSource(
            data={
                'time': [],
                'cpu': [],
                'memory_percent': [],
                'network-send': [],
                'network-recv': []
            })

        x_range = DataRange1d(follow='end',
                              follow_interval=30000,
                              range_padding=0)

        resource_plot = Plot(x_range=x_range,
                             y_range=Range1d(start=0, end=1),
                             toolbar_location=None,
                             min_border_bottom=10,
                             **kwargs)

        line_opts = dict(line_width=2, line_alpha=0.8)
        g1 = resource_plot.add_glyph(
            self.source,
            Line(x='time',
                 y='memory_percent',
                 line_color="#33a02c",
                 **line_opts))
        g2 = resource_plot.add_glyph(
            self.source,
            Line(x='time', y='cpu', line_color="#1f78b4", **line_opts))

        resource_plot.add_layout(
            LinearAxis(formatter=NumeralTickFormatter(format="0 %")), 'left')

        legend_opts = dict(location='top_left',
                           orientation='horizontal',
                           padding=5,
                           margin=5,
                           label_height=5)

        resource_plot.add_layout(
            Legend(items=[('Memory', [g1]), ('CPU', [g2])], **legend_opts))

        network_plot = Plot(x_range=x_range,
                            y_range=DataRange1d(start=0),
                            toolbar_location=None,
                            **kwargs)
        g1 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-send', line_color="#a6cee3",
                 **line_opts))
        g2 = network_plot.add_glyph(
            self.source,
            Line(x='time', y='network-recv', line_color="#b2df8a",
                 **line_opts))

        network_plot.add_layout(DatetimeAxis(axis_label="Time"), "below")
        network_plot.add_layout(LinearAxis(axis_label="MB/s"), 'left')
        network_plot.add_layout(
            Legend(items=[('Network Send', [g1]), ('Network Recv', [g2])],
                   **legend_opts))

        tools = [
            PanTool(dimensions='width'),
            WheelZoomTool(dimensions='width'),
            BoxZoomTool(),
            ResetTool()
        ]

        if 'sizing_mode' in kwargs:
            sizing_mode = {'sizing_mode': kwargs['sizing_mode']}
        else:
            sizing_mode = {}

        combo_toolbar = ToolbarBox(tools=tools,
                                   logo=None,
                                   toolbar_location='right',
                                   **sizing_mode)

        self.root = row(column(resource_plot, network_plot, **sizing_mode),
                        column(combo_toolbar, **sizing_mode),
                        id='bk-resource-profiles-plot',
                        **sizing_mode)

        # Required for update callback
        self.resource_index = [0]
Пример #26
0
def create(palm):
    energy_min = palm.energy_range.min()
    energy_max = palm.energy_range.max()
    energy_npoints = palm.energy_range.size

    current_results = (0, 0, 0, 0)

    doc = curdoc()

    # Streaked and reference waveforms plot
    waveform_plot = Plot(
        title=Title(text="eTOF waveforms"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location="right",
    )

    # ---- tools
    waveform_plot.toolbar.logo = None
    waveform_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                            ResetTool())

    # ---- axes
    waveform_plot.add_layout(LinearAxis(axis_label="Photon energy, eV"),
                             place="below")
    waveform_plot.add_layout(LinearAxis(axis_label="Intensity",
                                        major_label_orientation="vertical"),
                             place="left")

    # ---- grid lines
    waveform_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    waveform_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    waveform_source = ColumnDataSource(
        dict(x_str=[], y_str=[], x_ref=[], y_ref=[]))
    waveform_ref_line = waveform_plot.add_glyph(
        waveform_source, Line(x="x_ref", y="y_ref", line_color="blue"))
    waveform_str_line = waveform_plot.add_glyph(
        waveform_source, Line(x="x_str", y="y_str", line_color="red"))

    # ---- legend
    waveform_plot.add_layout(
        Legend(items=[("reference",
                       [waveform_ref_line]), ("streaked",
                                              [waveform_str_line])]))
    waveform_plot.legend.click_policy = "hide"

    # Cross-correlation plot
    xcorr_plot = Plot(
        title=Title(text="Waveforms cross-correlation"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location="right",
    )

    # ---- tools
    xcorr_plot.toolbar.logo = None
    xcorr_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                         ResetTool())

    # ---- axes
    xcorr_plot.add_layout(LinearAxis(axis_label="Energy shift, eV"),
                          place="below")
    xcorr_plot.add_layout(LinearAxis(axis_label="Cross-correlation",
                                     major_label_orientation="vertical"),
                          place="left")

    # ---- grid lines
    xcorr_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    xcorr_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    xcorr_source = ColumnDataSource(dict(lags=[], xcorr1=[], xcorr2=[]))
    xcorr_plot.add_glyph(
        xcorr_source,
        Line(x="lags", y="xcorr1", line_color="purple", line_dash="dashed"))
    xcorr_plot.add_glyph(xcorr_source,
                         Line(x="lags", y="xcorr2", line_color="purple"))

    # ---- vertical span
    xcorr_center_span = Span(location=0, dimension="height")
    xcorr_plot.add_layout(xcorr_center_span)

    # Delays plot
    pulse_delay_plot = Plot(
        title=Title(text="Pulse delays"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location="right",
    )

    # ---- tools
    pulse_delay_plot.toolbar.logo = None
    pulse_delay_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                               ResetTool())

    # ---- axes
    pulse_delay_plot.add_layout(LinearAxis(axis_label="Pulse number"),
                                place="below")
    pulse_delay_plot.add_layout(
        LinearAxis(axis_label="Pulse delay (uncalib), eV",
                   major_label_orientation="vertical"),
        place="left",
    )

    # ---- grid lines
    pulse_delay_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_delay_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_delay_source = ColumnDataSource(dict(pulse=[], delay=[]))
    pulse_delay_plot.add_glyph(
        pulse_delay_source, Line(x="pulse", y="delay", line_color="steelblue"))

    # ---- vertical span
    pulse_delay_plot_span = Span(location=0, dimension="height")
    pulse_delay_plot.add_layout(pulse_delay_plot_span)

    # Pulse lengths plot
    pulse_length_plot = Plot(
        title=Title(text="Pulse lengths"),
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=PLOT_CANVAS_HEIGHT,
        plot_width=PLOT_CANVAS_WIDTH,
        toolbar_location="right",
    )

    # ---- tools
    pulse_length_plot.toolbar.logo = None
    pulse_length_plot.add_tools(PanTool(), BoxZoomTool(), WheelZoomTool(),
                                ResetTool())

    # ---- axes
    pulse_length_plot.add_layout(LinearAxis(axis_label="Pulse number"),
                                 place="below")
    pulse_length_plot.add_layout(
        LinearAxis(axis_label="Pulse length (uncalib), eV",
                   major_label_orientation="vertical"),
        place="left",
    )

    # ---- grid lines
    pulse_length_plot.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    pulse_length_plot.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    # ---- line glyphs
    pulse_length_source = ColumnDataSource(dict(x=[], y=[]))
    pulse_length_plot.add_glyph(pulse_length_source,
                                Line(x="x", y="y", line_color="steelblue"))

    # ---- vertical span
    pulse_length_plot_span = Span(location=0, dimension="height")
    pulse_length_plot.add_layout(pulse_length_plot_span)

    # Folder path text input
    def path_textinput_callback(_attr, _old_value, new_value):
        save_textinput.value = new_value
        path_periodic_update()

    path_textinput = TextInput(title="Folder Path:",
                               value=os.path.join(os.path.expanduser("~")),
                               width=510)
    path_textinput.on_change("value", path_textinput_callback)

    # Saved runs dropdown menu
    def h5_update(pulse, delays, debug_data):
        prep_data, lags, corr_res_uncut, corr_results = debug_data

        waveform_source.data.update(
            x_str=palm.energy_range,
            y_str=prep_data["1"][pulse, :],
            x_ref=palm.energy_range,
            y_ref=prep_data["0"][pulse, :],
        )

        xcorr_source.data.update(lags=lags,
                                 xcorr1=corr_res_uncut[pulse, :],
                                 xcorr2=corr_results[pulse, :])

        xcorr_center_span.location = delays[pulse]
        pulse_delay_plot_span.location = pulse
        pulse_length_plot_span.location = pulse

    # this placeholder function should be reassigned in 'saved_runs_dropdown_callback'
    h5_update_fun = lambda pulse: None

    def saved_runs_dropdown_callback(_attr, _old_value, new_value):
        if new_value != "Saved Runs":
            nonlocal h5_update_fun, current_results
            saved_runs_dropdown.label = new_value
            filepath = os.path.join(path_textinput.value, new_value)
            tags, delays, lengths, debug_data = palm.process_hdf5_file(
                filepath, debug=True)
            current_results = (new_value, tags, delays, lengths)

            if autosave_checkbox.active:
                save_button_callback()

            pulse_delay_source.data.update(pulse=np.arange(len(delays)),
                                           delay=delays)
            pulse_length_source.data.update(x=np.arange(len(lengths)),
                                            y=lengths)
            h5_update_fun = partial(h5_update,
                                    delays=delays,
                                    debug_data=debug_data)

            pulse_slider.end = len(delays) - 1
            pulse_slider.value = 0
            h5_update_fun(0)

    saved_runs_dropdown = Dropdown(label="Saved Runs",
                                   button_type="primary",
                                   menu=[])
    saved_runs_dropdown.on_change("value", saved_runs_dropdown_callback)

    # ---- saved run periodic update
    def path_periodic_update():
        new_menu = []
        if os.path.isdir(path_textinput.value):
            for entry in os.scandir(path_textinput.value):
                if entry.is_file() and entry.name.endswith((".hdf5", ".h5")):
                    new_menu.append((entry.name, entry.name))
        saved_runs_dropdown.menu = sorted(new_menu, reverse=True)

    doc.add_periodic_callback(path_periodic_update, 5000)

    # Pulse number slider
    def pulse_slider_callback(_attr, _old_value, new_value):
        h5_update_fun(pulse=new_value)

    pulse_slider = Slider(
        start=0,
        end=99999,
        value=0,
        step=1,
        title="Pulse ID",
        callback_policy="throttle",
        callback_throttle=500,
    )
    pulse_slider.on_change("value", pulse_slider_callback)

    # Energy maximal range value text input
    def energy_max_spinner_callback(_attr, old_value, new_value):
        nonlocal energy_max
        if new_value > energy_min:
            energy_max = new_value
            palm.energy_range = np.linspace(energy_min, energy_max,
                                            energy_npoints)
            saved_runs_dropdown_callback("", "", saved_runs_dropdown.label)
        else:
            energy_max_spinner.value = old_value

    energy_max_spinner = Spinner(title="Maximal Energy, eV:",
                                 value=energy_max,
                                 step=0.1)
    energy_max_spinner.on_change("value", energy_max_spinner_callback)

    # Energy minimal range value text input
    def energy_min_spinner_callback(_attr, old_value, new_value):
        nonlocal energy_min
        if new_value < energy_max:
            energy_min = new_value
            palm.energy_range = np.linspace(energy_min, energy_max,
                                            energy_npoints)
            saved_runs_dropdown_callback("", "", saved_runs_dropdown.label)
        else:
            energy_min_spinner.value = old_value

    energy_min_spinner = Spinner(title="Minimal Energy, eV:",
                                 value=energy_min,
                                 step=0.1)
    energy_min_spinner.on_change("value", energy_min_spinner_callback)

    # Energy number of interpolation points text input
    def energy_npoints_spinner_callback(_attr, old_value, new_value):
        nonlocal energy_npoints
        if new_value > 1:
            energy_npoints = new_value
            palm.energy_range = np.linspace(energy_min, energy_max,
                                            energy_npoints)
            saved_runs_dropdown_callback("", "", saved_runs_dropdown.label)
        else:
            energy_npoints_spinner.value = old_value

    energy_npoints_spinner = Spinner(title="Number of interpolation points:",
                                     value=energy_npoints)
    energy_npoints_spinner.on_change("value", energy_npoints_spinner_callback)

    # Save location
    save_textinput = TextInput(title="Save Folder Path:",
                               value=os.path.join(os.path.expanduser("~")))

    # Autosave checkbox
    autosave_checkbox = CheckboxButtonGroup(labels=["Auto Save"],
                                            active=[],
                                            width=250)

    # Save button
    def save_button_callback():
        if current_results[0]:
            filename, tags, delays, lengths = current_results
            save_filename = os.path.splitext(filename)[0] + ".csv"
            df = pd.DataFrame({
                "pulse_id": tags,
                "pulse_delay": delays,
                "pulse_length": lengths
            })
            df.to_csv(os.path.join(save_textinput.value, save_filename),
                      index=False)

    save_button = Button(label="Save Results",
                         button_type="default",
                         width=250)
    save_button.on_click(save_button_callback)

    # assemble
    tab_layout = column(
        row(
            column(waveform_plot, xcorr_plot),
            Spacer(width=30),
            column(
                path_textinput,
                saved_runs_dropdown,
                pulse_slider,
                Spacer(height=30),
                energy_min_spinner,
                energy_max_spinner,
                energy_npoints_spinner,
                Spacer(height=30),
                save_textinput,
                autosave_checkbox,
                save_button,
            ),
        ),
        row(pulse_delay_plot, Spacer(width=10), pulse_length_plot),
    )

    return Panel(child=tab_layout, title="HDF5 File")
def make_line_plot(x_range, y_range, source):
    with make_plot(x_range, y_range, source) as plot:
        for i, energy in enumerate(['gas', 'oil', 'solar']):
            glyph = Line(x='index', y=energy, line_color=Spectral3[i], line_alpha=0.5, line_width=5)
            plot.add_glyph(source, glyph)
    return plot
Пример #28
0
def plot_map(ulog,
             config,
             map_type='plain',
             api_key=None,
             setpoints=False,
             bokeh_plot=None):
    """
    Do a 2D position plot

    :param map_type: one of 'osm', 'google', 'plain'
    :param bokeh_plot: if None, create a new bokeh plot, otherwise use the
                       supplied one (only for 'plain' map_type)

    :return: bokeh plot object
    """

    try:
        cur_dataset = ulog.get_dataset('vehicle_gps_position')
        t = cur_dataset.data['timestamp']
        indices = cur_dataset.data['fix_type'] > 2  # use only data with a fix
        t = t[indices]
        lon = cur_dataset.data['lon'][indices] / 1e7  # degrees
        lat = cur_dataset.data['lat'][indices] / 1e7
        altitude = cur_dataset.data['alt'][indices] / 1e3  # meters

        plots_width = config['plot_width']
        plots_height = config['plot_height']['large']
        anchor_lat = 0
        anchor_lon = 0

        if len(t) == 0:
            raise ValueError('No valid GPS position data')

        if map_type == 'google':
            data_source = ColumnDataSource(data=dict(lat=lat, lon=lon))

            lon_center = (np.amin(lon) + np.amax(lon)) / 2
            lat_center = (np.amin(lat) + np.amax(lat)) / 2

            map_options = GMapOptions(lat=lat_center,
                                      lng=lon_center,
                                      map_type="hybrid",
                                      zoom=19)
            # possible map types: satellite, roadmap, terrain, hybrid

            p = GMapPlot(x_range=DataRange1d(),
                         y_range=DataRange1d(),
                         map_options=map_options,
                         api_key=api_key,
                         plot_width=plots_width,
                         plot_height=plots_height)

            pan = PanTool()
            wheel_zoom = WheelZoomTool()
            p.add_tools(pan, wheel_zoom)
            p.toolbar.active_scroll = wheel_zoom

            line = Line(x="lon",
                        y="lat",
                        line_width=2,
                        line_color=config['maps_line_color'])
            p.add_glyph(data_source, line)

        elif map_type == 'osm':

            # OpenStreetMaps

            # transform coordinates
            lon, lat = WGS84_to_mercator(lon, lat)
            data_source = ColumnDataSource(data=dict(lat=lat, lon=lon))

            p = figure(tools=TOOLS, active_scroll=ACTIVE_SCROLL_TOOLS)
            p.plot_width = plots_width
            p.plot_height = plots_height

            plot_set_equal_aspect_ratio(p, lon, lat)

            p.background_fill_color = "lightgray"
            p.axis.visible = False

            tile_options = {}
            # thunderforest
            tile_options[
                'url'] = 'http://b.tile.thunderforest.com/landscape/{z}/{x}/{y}.png'
            tile_options[
                'attribution'] = 'Maps © <a href="http://www.thunderforest.com">Thunderforest</a>, Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors '

            # default OpenStreetMaps
            #            tile_options['url'] = 'http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png'
            #            tile_options['attribution'] = '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors '

            # FIXME: tiles disabled for now due to a rendering bug
            #            tile_source = WMTSTileSource(**tile_options)
            #            tile_renderer_options = {}
            #            p.add_tile(tile_source, **tile_renderer_options)

            # stamen (black & white)
            #            STAMEN_TONER = WMTSTileSource(
            #                url='http://tile.stamen.com/toner/{Z}/{X}/{Y}.png',
            #                attribution=(
            #                    'Map tiles by <a href="http://stamen.com">Stamen Design</a>, '
            #                    'under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'
            #                    'Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, '
            #                    'under <a href="http://www.openstreetmap.org/copyright">ODbL</a>'
            #                )
            #            )
            #            p.add_tile(STAMEN_TONER)

            p.line(x='lon',
                   y='lat',
                   source=data_source,
                   line_width=2,
                   line_color=config['maps_line_color'])

        else:  # plain

            # transform coordinates
            lat = np.deg2rad(lat)
            lon = np.deg2rad(lon)
            anchor_lat = lat[0]
            anchor_lon = lon[0]

            # try to get the anchor position from the dataset
            try:
                local_pos_data = ulog.get_dataset('vehicle_local_position')
                indices = np.nonzero(local_pos_data.data['ref_timestamp'])
                if len(indices[0]) > 0:
                    anchor_lat = np.deg2rad(
                        local_pos_data.data['ref_lat'][indices[0][0]])
                    anchor_lon = np.deg2rad(
                        local_pos_data.data['ref_lon'][indices[0][0]])
            except:
                pass

            lat, lon = map_projection(lat, lon, anchor_lat, anchor_lon)
            data_source = ColumnDataSource(data=dict(lat=lat, lon=lon))

            if bokeh_plot is None:
                p = figure(tools=TOOLS,
                           active_scroll=ACTIVE_SCROLL_TOOLS,
                           x_axis_label='[m]',
                           y_axis_label='[m]')
                p.plot_width = plots_width
                p.plot_height = plots_height

                plot_set_equal_aspect_ratio(p, lon, lat)
            else:
                p = bokeh_plot

            # TODO: altitude line coloring
            p.line(x='lon',
                   y='lat',
                   source=data_source,
                   line_width=2,
                   line_color=config['maps_line_color'],
                   legend='GPS (projected)')

        if setpoints:
            # draw (mission) setpoint as circles
            try:
                cur_dataset = ulog.get_dataset('position_setpoint_triplet')
                lon = cur_dataset.data['current.lon']  # degrees
                lat = cur_dataset.data['current.lat']

                if map_type == 'osm':
                    lon, lat = WGS84_to_mercator(lon, lat)
                elif map_type == 'plain':
                    lat = np.deg2rad(lat)
                    lon = np.deg2rad(lon)
                    lat, lon = map_projection(lat, lon, anchor_lat, anchor_lon)

                data_source = ColumnDataSource(data=dict(lat=lat, lon=lon))

                p.circle(x='lon',
                         y='lat',
                         source=data_source,
                         line_width=2,
                         size=6,
                         line_color=config['mission_setpoint_color'],
                         fill_color=None,
                         legend='Position Setpoints')
            except:
                pass

    except (KeyError, IndexError, ValueError) as error:
        # log does not contain the value we are looking for
        print(type(error), "(vehicle_gps_position):", error)
        return None
    p.toolbar.logo = None
    return p
Пример #29
0
ydr = DataRange1d()

plot = Plot(
    x_range=xdr,
    y_range=ydr,
    width=1000,
    height=600,
    min_border=0,
    toolbar_location=None,
    background_fill_color='#F0F0F0',
    border_fill_color='lightgray',
)

line_glyph = Line(x="x",
                  y="y",
                  line_color="navy",
                  line_width=2,
                  line_dash="dashed")
line = plot.add_glyph(source, line_glyph)
circle = Circle(x="x",
                y="y2",
                size=6,
                line_color="red",
                fill_color="orange",
                fill_alpha=0.6)
circle = plot.add_glyph(source, circle)

pan = PanTool()
wheel_zoom = WheelZoomTool()
preview_save = SaveTool()
Пример #30
0
    times = [dt.time(11, 30)]*3,
    texts = ["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"],
))

plot = Plot(width=800, height=400)
plot.title.text = "Daylight Hours 2013 - Warsaw, Poland"
plot.toolbar_location = None
plot.x_range.range_padding = 0

patch1 = Patch(x="dates", y="times", fill_color="#282e54")
plot.add_glyph(patch1_source, patch1)

patch2 = Patch(x="dates", y="times", fill_color="#ffdd91")
plot.add_glyph(patch2_source, patch2)

sunrise_line = Line(x="dates", y="sunrises", line_color="orange", line_width=4)
sunrise_line_renderer = plot.add_glyph(source, sunrise_line)

sunset_line = Line(x="dates", y="sunsets", line_color="crimson", line_width=4)
sunset_line_renderer = plot.add_glyph(source, sunset_line)

text = Text(x="dates", y="times", text="texts", text_align="center", text_color="grey")
plot.add_glyph(text_source, text)

xformatter = DatetimeTickFormatter(months="%b %d %Y")
min_time = dt.datetime.min.time()
xticker = FixedTicker(ticks=[
    mktime(dt.datetime.combine(summer_start, min_time).timetuple()) * 1000,
    mktime(dt.datetime.combine(summer_end, min_time).timetuple()) * 1000
])
xaxis = DatetimeAxis(formatter=xformatter, ticker=xticker)