bokeh.layouts.row

Here are the examples of the python api bokeh.layouts.row taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

85 Examples 7

3 Source : trending_delta4.py
with MIT License
from cutright

    def __do_layout(self):
        # TODO: Generalize for 1 or 2 groups
        self.layout = column(row(self.select_y, self.select_linac[1], self.select_linac[2], self.avg_len_input,
                                 self.percentile_input, self.bins_input),
                             row(self.select_energies[1], self.select_energies[2]),
                             row(self.start_date_picker, self.end_date_picker),
                             row(Div(text='Gamma Criteria: '), self.checkbox_button_group),
                             self.div_summary[1],
                             self.div_summary[2],
                             row(Spacer(width=10), self.fig),
                             Spacer(height=50),
                             row(Spacer(width=10), self.histogram),
                             Spacer(height=50),
                             row(Spacer(width=10), self.ichart),
                             row(self.div_center_line[1], self.div_ucl[1], self.div_lcl[1]),
                             row(self.div_center_line[2], self.div_ucl[2], self.div_lcl[2]))

    def update_source_ticker(self, attr, old, new):

3 Source : edit.py
with GNU General Public License v3.0
from j-brady

    def init(self, doc):
        """ initialise the bokeh app """

        doc.add_root(
            column(
                self.intro_div,
                row(column(self.p, self.doc_link), column(self.data_table, self.tabs)),
                sizing_mode="stretch_both",
            )
        )
        doc.title = "peakipy: Edit Fits"

    @property

3 Source : _comparison.py
with MIT License
from metriculous-ml

def _figure_rows(
    model_evaluations: Sequence[Evaluation], include_spacer: Optional[bool],
) -> Sequence[Row]:
    # TODO check figure consistency
    rows = []
    for i_figure, _ in enumerate(model_evaluations[0].lazy_figures):
        row_of_figures = [
            evaluation.lazy_figures[i_figure]()
            for i_model, evaluation in enumerate(model_evaluations)
        ]
        if len(model_evaluations) == 1 and include_spacer in (None, True):
            row_of_figures = row_of_figures + [Spacer()]
        elif include_spacer is True:
            row_of_figures = [Spacer()] + row_of_figures
        rows.append(bokeh.layouts.row(row_of_figures, sizing_mode="scale_width"))
    return rows


def _format_numbers(entry: Any) -> Any:

3 Source : uibokeh.py
with Apache License 2.0
from OpendTect

def getRunButtonsBar(runact,abortact,pauseact,resumeact,timercb):
  runstopbut = getRunStopButton()
  pauseresumebut = getPauseResumeButton()
  pauseresumebut.visible = False
  buttonsgrp = row(pauseresumebut,Spacer(width=but_spacer),runstopbut,width_policy='min')
  buttonsfld = row(Spacer(width=but_spacer),buttonsgrp, sizing_mode='stretch_width')
  ret = {
    'run': runstopbut,
    'pause': pauseresumebut,
    'state': RunState.Ready,
    timerkey: None
  }
  runstopbut.on_click(partial(startStopCB,cb=ret,run_fn=runact,abort_fn=abortact,
                              timer_fn=timercb) )
  pauseresumebut.on_click(partial(pauseResumeCB,cb=ret,pause_fn=pauseact,resume_fn=resumeact))
  return buttonsfld

def startStopCB( cb, run_fn, abort_fn, timer_fn, repeat=2000 ):

3 Source : uibokeh_well.py
with Apache License 2.0
from OpendTect

    def __init__(self):
        self.fields = {'width': bm.Spinner(title='Line Width:',low=0,high=5, step=1,
                                           width_policy='min'),
                       'color': bm.ColorPicker(title='Line Color:', width_policy='min'),
                       'dash':  bm.Select(title='Line Draw Style:', options=list(bce.DashPattern),
                                          width_policy='min')
                       }
        self.layout = bl.row(list(self.fields.values()))

class GridPropertyWidget:

3 Source : uibokeh_well.py
with Apache License 2.0
from OpendTect

    def __init__(self, title, withsteps=True):
        line_props = LinePropertyWidget()
        field_title = bm.Div(text=title)
        self.fields = {'visible': bm.CheckboxGroup(labels=[''], inline= True, active=[0], width_policy='min'),
                       'steps': bm.Spinner(title='Steps:',low=0,high=5, step=1)
                      }
        self.fields.update(line_props.fields)
        self.fields['visible'].on_change('active',self.visible)
        self.layout = bl.column(bl.row(self.fields['visible'],field_title),
                                self.fields['steps'],
                                line_props.layout
                                )

    def visible(self, attr, old, new):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(
                column(self.search_pos, self.search_neg),
                column(self.search_filter_box),
            ),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehTextAnnotator(BokehDataAnnotator, BokehForText):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_pos, self.search_neg),
            row(self.annotator_input, self.annotator_apply),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehTextSoftLabel(BokehSoftLabelExplorer, BokehForText):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_pos, self.search_neg),
            row(self.score_filter),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehTextMargin(BokehMarginExplorer, BokehForText):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_pos, self.search_neg),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehTextSnorkel(BokehSnorkelExplorer, BokehForText):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_pos, self.search_neg),
            row(self.lf_apply_trigger, self.lf_filter_trigger, self.lf_list_refresher),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehAudioFinder(BokehDataFinder, BokehForAudio):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(
                column(self.search_sim, self.search_threshold),
                column(self.search_filter_box),
            ),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehAudioAnnotator(BokehDataAnnotator, BokehForAudio):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.annotator_input, self.annotator_apply),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehAudioSoftLabel(BokehSoftLabelExplorer, BokehForAudio):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.score_filter),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehAudioMargin(BokehMarginExplorer, BokehForAudio):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehAudioSnorkel(BokehSnorkelExplorer, BokehForAudio):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.lf_apply_trigger, self.lf_filter_trigger, self.lf_list_refresher),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehImageFinder(BokehDataFinder, BokehForImage):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(
                column(self.search_sim, self.search_threshold),
                column(self.search_filter_box),
            ),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehImageAnnotator(BokehDataAnnotator, BokehForImage):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.annotator_input, self.annotator_apply),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehImageSoftLabel(BokehSoftLabelExplorer, BokehForImage):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.score_filter),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehImageMargin(BokehMarginExplorer, BokehForImage):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)


class BokehImageSnorkel(BokehSnorkelExplorer, BokehForImage):

3 Source : specialization.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """Define the layout of widgets."""
        layout_rows = (
            row(self.subset_toggle_widget_column, self.selection_option_box),
            row(self.search_sim, self.search_threshold),
            row(self.lf_apply_trigger, self.lf_filter_trigger, self.lf_list_refresher),
            row(self.dropdown_x_axis, self.dropdown_y_axis),
            row(*self._dynamic_widgets.values()),
        )
        return column(*layout_rows)

3 Source : neural.py
with MIT License
from phurwicz

    def _layout_widgets(self):
        """
        ???+ note "Layout of widgets when plotted."
        """
        from bokeh.layouts import row

        return row(self.epochs_slider, self.loglr_slider)

    def view(self):

3 Source : subroutine.py
with MIT License
from phurwicz

def recipe_layout(*components, style="horizontal"):
    """
    ???+ note "Create a recipe-level layout of bokeh objects."

        | Param      | Type     | Description                          |
        | :--------- | :------- | :----------------------------------- |
        | `*components` | `bokeh` objects | objects to be plotted      |
        | `style`    | `str`    | "horizontal" or "vertical"           |
    """
    if style == "horizontal":
        return row(*components)
    elif style == "vertical":
        return column(*components)
    else:
        raise ValueError(f"Unexpected layout style {style}")


def get_explorer_class(task, feature):

3 Source : test_util.py
with MIT License
from rthorst

    def test_layout(self):
        p = figure(plot_width=200, plot_height=300)
        d = Document()
        d.add_root(row(p))
        with pytest.warns(UserWarning) as warns:
            util.set_single_plot_width_height(d, 400, 500)
            assert len(warns) == 1
            assert warns[0].message.args[0] == _SIZE_WARNING

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

3 Source : test_export.py
with MIT License
from rthorst

def test_layout_html_on_child_first():
    p = Plot(x_range=Range1d(), y_range=Range1d())

    bie.get_layout_html(p, height=100, width=100)

    layout = row(p)
    bie.get_layout_html(layout)

def test_layout_html_on_parent_first():

3 Source : test_export.py
with MIT License
from rthorst

def test_layout_html_on_parent_first():
    p = Plot(x_range=Range1d(), y_range=Range1d())

    layout = row(p)
    bie.get_layout_html(layout)

    bie.get_layout_html(p, height=100, width=100)

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

@patch('PIL.Image.Image')

3 Source : test_layouts.py
with MIT License
from rthorst

def test_gridplot_merge_tools_nested():
    p1, p2, p3, p4, p5, p6, p7 = figure(), figure(), figure(), figure(), figure(), figure(), figure()
    r1 = row(p1, p2)
    r2 = row(p3, p4)
    c = column(row(p5), row(p6))

    gridplot([[r1, r2], [c, p7]], merge_tools=True)

    for p in p1, p2, p3, p4, p5, p6, p7:
        assert p.toolbar_location is None


def test_gridplot_None():

3 Source : render.py
with MIT License
from sfu-db

def kde_viz_panel(
    hist: List[Tuple[np.ndarray, np.ndarray]],
    kde: np.ndarray,
    col: str,
    plot_width: int,
    plot_height: int,
    cfg: Config,
) -> Panel:
    """
    Render histogram with overlayed kde
    """
    # pylint: disable=too-many-arguments, too-many-locals
    fig = kde_viz_figure(hist, kde, col, plot_width, plot_height, cfg)
    return Panel(child=row(fig), title="KDE Plot")


def dt_line_viz(

0 Source : visualiser.py
with BSD 3-Clause "New" or "Revised" License
from alexjonesphd

def explore(model, display='combined'):
    """ Allows a user to explore the model outputs using Bokeh, using sliders to adjust predicted shape and texture variables.
    This function will NOT run outside of a Jupyter Notebook.

    Parameters
    ----------
    model : an instance of the Modeller class on which .fit() has been called.

    display : a string specifying the kind of data the user would like to see. Accepts 'texture' to just show texture changes or 'shape'
              to visualise landmark deformation. The default argument visualises both shape and texture changing simultaneously.
    """

    # Set up the notebook output
    output_notebook()

    def make_document(doc):
        """ Internal function to create the document for visualisation. Hidden from users who need only call outer function with a fitted model.
        """

        # Use the model to predict an average representationof  data, using the mean value of each predictor
        centred_predict = model.master_data_frame.mean().to_dict()
        _, final_im, shape, texture_im = model.predict(**centred_predict)

        # Call the image tidy function to change RGB texture to RGBA
        final_im = _image_tidy(final_im)
        texture = _image_tidy(texture_im)

        # Set up the plot for the shape coordinates ###############################
        # Define a column data source
        shape_source = ColumnDataSource( {'x': shape[:,0], 'y': shape[:,1]} )

        # Instantiate plot object for shape coordinates
        shape_plot = figure(title = 'Predicted Shape', y_range = (900, 0), x_range = (0, 900))
        shape_plot.cross('x', 'y', size = 10, source = shape_source)

        # Define hover tool and add to plot
        hover = HoverTool( tooltips = [('x', '@x'), ('y', '@y')] )
        shape_plot.add_tools(hover)
        ###########################################################################

        # Set up a column data source for the actual warped face ##################
        # Define a column data source
        warp_source = ColumnDataSource( {'image': [final_im]} )

        # Instantiate plot object for warped image - add a constant extra few pixels to make sure image is not squashed to window
        warp_image_plot = figure(title = 'Predicted Face', y_range = (0, model.image_dims[0]+150), x_range = (0, model.image_dims[1]+150))
        warp_image_plot.image_rgba(image = 'image', x=0, y=0, dw=model.image_dims[1], dh=model.image_dims[0], source=warp_source)

        # Set up a column data source for the texture-only face ###################
        # Define a column data source
        texture_source = ColumnDataSource( { 'image': [texture] } )

        # Instantiate plot object for shape-free face
        image_plot = figure(title = 'Predicted Texture', y_range = (0, model.image_dims[0]+150), x_range = (0, model.image_dims[1]+150) )
        image_plot.image_rgba( image = 'image', x=0, y=0, dw=model.image_dims[1], dh=model.image_dims[0], source=texture_source)
        ###########################################################################

        # Define the internal callback function to update objects interactively
        def callback(attr, old, new):
            """ Bokeh callback for updating glyphs
            """

            # Iterate over the traits, get their title and their value and store in the dictionary
            predictor_dict = {}
            for slide in sliders:
                predictor_dict[ slide.title ] = slide.value

            # Use this dictionary to feed to the model's predict method, generating new ouput to show
            _, final_im, shape, texture = model.predict(**predictor_dict)

            # Fix the images for show
            final_im = _image_tidy(final_im)
            texture = _image_tidy(texture)

            # Update data sources with the new information
            shape_source.data = {'x':shape[:,0], 'y':shape[:,1]}
            warp_source.data = {'image':[final_im]}
            texture_source.data = {'image':[texture]}

        ###########################################################################
        # Set up sliders to alter properties
        sliders = []
        for trait in model.trait_list:

            #  Get the middle and far end points by applying mean, min, and max, and rounding to zero
            avg, mini, maxi = model.master_data_frame[trait].apply(['mean', 'min', 'max']).round()

            slider = Slider(title = trait, start = mini, end = maxi, step = 1, value = avg)
            slider.on_change('value', callback)
            sliders.append(slider)

        ###########################################################################
        # Set layout according to specification of user, extract from dictionary
        layout_dict = {'combined':warp_image_plot, 'texture':image_plot, 'shape':shape_plot}

        layout = row([widgetbox(sliders), layout_dict[display]])

        # Update and add to curdoc
        doc.add_root(layout)

    # Initialise server with the make_document function defined above
    show(make_document)

0 Source : line.py
with GNU Affero General Public License v3.0
from andrewcooke

def htile(maps, n):
    return column([row(maps[i:i + n]) for i in range(0, len(maps), n)])


def vtile(maps, n):

0 Source : line.py
with GNU Affero General Public License v3.0
from andrewcooke

def vtile(maps, n):
    return row([column(maps[i::n]) for i in range(n)])

0 Source : activity_details.py
with GNU Affero General Public License v3.0
from andrewcooke

def activity_details(local_time, activity_group):

    f'''
    # Activity Details: {local_time} ({activity_group})
    '''

    '''
    $contents
    '''

    '''
    ## Load Data
    
    Open a connection to the database and load the data we require.
    '''

    s = session('-v2')

    activity = std_activity_statistics(s, activity_journal=local_time, activity_group=activity_group)
    health = std_health_statistics(s)
    hr_zones = hr_zones_from_database(s, local_time, activity_group)
    climbs = Statistics(s, sources=climb_sources(s, local_time, activity_group=activity_group)). \
        by_name(SectorCalculator, N.CLIMB_ANY, N.VERTICAL_POWER, like=True).with_. \
        copy_with_units().df
    active = Statistics(s, activity_journal=local_time, activity_group=activity_group). \
        by_name(ActivityCalculator, N.ACTIVE_TIME, N.ACTIVE_DISTANCE). \
        with_.copy_with_units().df.append(climbs)

    f'''
    ## Activity Plots
    
    To the right of each plot of data against distance is a related plot of cumulative data
    (except the last, cadence, which isn't useful and so replaced by HR zones).
    Green and red areas indicate differences between the two dates. 
    Additional red lines on the altitude plot are auto-detected climbs.
    
    Plot tools support zoom, dragging, etc.
    '''

    output_file(filename='/dev/null')

    sp = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_SPEED_KMH, activity, ylo=0)
    add_climb_zones(sp, climbs, activity)
    sp_c = cumulative_plot(200, 200, N.MED_SPEED_KMH, activity, ylo=0)
    xrange = sp.x_range if sp else None

    el = comparison_line_plot(700, 200, N.DISTANCE_KM, N.ELEVATION_M, activity, x_range=xrange)
    add_climbs(el, climbs, activity)
    el_c = cumulative_plot(200, 200, N.CLIMB_MS, activity)
    xrange = xrange or (el.x_range if el else None)

    hri = comparison_line_plot(700, 200, N.DISTANCE_KM, N.HR_IMPULSE_10, activity, ylo=0, x_range=xrange)
    add_climb_zones(hri, climbs, activity)
    hri_c = cumulative_plot(200, 200, N.HR_IMPULSE_10, activity, ylo=0)
    xrange = xrange or (hri.x_range if hri else None)

    hr = comparison_line_plot(700, 200, N.DISTANCE_KM, N.HEART_RATE_BPM, activity, x_range=xrange)
    add_hr_zones(hr, activity, N.DISTANCE_KM, hr_zones)
    add_climb_zones(hr, climbs, activity)
    hr_c = cumulative_plot(200, 200, N.HEART_RATE_BPM, activity)
    xrange = xrange or (hr.x_range if hr else None)

    pw = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_POWER_ESTIMATE_W, activity, ylo=0, x_range=xrange)
    pw.varea(source=activity, x=N.DISTANCE_KM, y1=0, y2=N.MED_VERTICAL_POWER_W,
             level='underlay', color='black', fill_alpha=0.25)
    add_climb_zones(pw, climbs, activity)
    pw_c = cumulative_plot(200, 200, N.MED_POWER_ESTIMATE_W, activity, ylo=0)
    xrange = xrange or (pw.x_range if pw else None)

    cd = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_CADENCE_RPM, activity, ylo=0, x_range=xrange)
    add_climb_zones(cd, climbs, activity)
    hr_h = histogram_plot(200, 200, N.HR_ZONE, activity, xlo=1, xhi=5)

    show(gridplot([[el, el_c], [sp, sp_c], [hri, hri_c], [hr, hr_c], [pw, pw_c], [cd, hr_h]]))

    '''
    ## Activity Maps
    '''

    map = map_plot(400, 400, activity)
    m_el = map_intensity_signed(200, 200, activity, N.GRADE_PC, ranges=map, power=0.5)
    m_sp = map_intensity(200, 200, activity, N.MED_SPEED_KMH, ranges=map, power=2)
    m_hr = map_intensity(200, 200, activity, N.HR_IMPULSE_10, ranges=map)
    m_pw = map_intensity(200, 200, activity, N.MED_POWER_ESTIMATE_W, ranges=map)
    show(row(map, gridplot([[m_el, m_sp], [m_hr, m_pw]], toolbar_location='right')))

    '''
    ## Activity Statistics
    '''

    '''
    Active time and distance exclude pauses.
    '''

    active[[N.ACTIVE_TIME_S, N.ACTIVE_DISTANCE_KM]].dropna(). \
        transform({N.ACTIVE_TIME_S: format_seconds, N.ACTIVE_DISTANCE_KM: format_km})

    '''
    Climbs are auto-detected and shown only for the main activity. They are included in the elevation plot above.
    '''

    if present(climbs, N.CLIMB_TIME):
        display(transform(climbs,
                          {N.CLIMB_TIME: format_seconds, N.CLIMB_ELEVATION: format_metres,
                           N.CLIMB_DISTANCE: format_km, N.CLIMB_GRADIENT: format_percent,
                           N.VERTICAL_POWER: format_watts, N.CLIMB_CATEGORY: lambda x: x}))

    '''
    ## Health and Fitness
    '''

    fitness, fatigue = like(N.FITNESS_ANY, health.columns), like(N.FATIGUE_ANY, health.columns)
    colours = ['black'] * len(fitness) + ['red'] * len(fatigue)
    alphas = [1.0] * len(fitness) + [0.5] * len(fatigue)
    ff = multi_line_plot(900, 300, N.TIME, fitness + fatigue, health, colours, alphas=alphas)
    xrange = ff.x_range if ff else None
    add_multi_line_at_index(ff, N.TIME, fitness + fatigue, health, colours, alphas=alphas, index=-1)
    atd = std_distance_time_plot(900, 200, health, x_range=xrange)
    show(gridplot([[ff], [atd]]))

0 Source : compare_activities.py
with GNU Affero General Public License v3.0
from andrewcooke

def compare_activities(local_time, compare_time, activity_group):

    f'''
    # Compare Activities: {local_time} v {compare_time} ({activity_group})
    '''

    '''
    $contents
    '''

    '''
    ## Load Data
    
    Open a connection to the database and load the data we require.
    '''

    s = session('-v2')

    activity = std_activity_statistics(s, activity_journal=local_time, activity_group=activity_group)
    compare = std_activity_statistics(s, activity_journal=compare_time, activity_group=activity_group)
    health = std_health_statistics(s)
    hr_zones = hr_zones_from_database(s, local_time, activity_group)
    climbs = Statistics(s, sources=climb_sources(s, local_time, activity_group=activity_group)). \
        by_name(SectorCalculator, N.CLIMB_ANY, N.VERTICAL_POWER, like=True).with_. \
        copy_with_units().df
    active = Statistics(s, activity_journal=local_time, activity_group=activity_group). \
        by_name(ActivityCalculator, N.ACTIVE_TIME, N.ACTIVE_DISTANCE). \
        with_.copy_with_units().df.append(climbs)

    f'''
    ## Activity Plots
    
    The black line shows data from {local_time}, 
    the grey line from {compare_time}. 
    To the right of each plot of data against distance is a related plot of cumulative data
    (except the last, cadence, which isn't useful and so replaced by HR zones).
    Green and red areas indicate differences between the two dates. 
    Additional red lines on the altitude plot are auto-detected climbs.
    
    Plot tools support zoom, dragging, etc.
    '''

    output_file(filename='/dev/null')

    sp = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_SPEED_KMH, activity, other=compare, ylo=0)
    add_climb_zones(sp, climbs, activity)
    sp_c = cumulative_plot(200, 200, N.MED_SPEED_KMH, activity, other=compare, ylo=0)
    xrange = sp.x_range if sp else None

    el = comparison_line_plot(700, 200, N.DISTANCE_KM, N.ELEVATION_M, activity, other=compare, x_range=xrange)
    add_climbs(el, climbs, activity)
    el_c = cumulative_plot(200, 200, N.CLIMB_MS, activity, other=compare)
    xrange = xrange or (el.x_range if el else None)

    hri = comparison_line_plot(700, 200, N.DISTANCE_KM, N.HR_IMPULSE_10, activity, other=compare, ylo=0, x_range=xrange)
    add_climb_zones(hri, climbs, activity)
    hri_c = cumulative_plot(200, 200, N.HR_IMPULSE_10, activity, other=compare, ylo=0)
    xrange = xrange or (hri.x_range if hri else None)

    hr = comparison_line_plot(700, 200, N.DISTANCE_KM, N.HEART_RATE_BPM, activity, other=compare, x_range=xrange)
    add_hr_zones(hr, activity, N.DISTANCE_KM, hr_zones)
    add_climb_zones(hr, climbs, activity)
    hr_c = cumulative_plot(200, 200, N.HEART_RATE_BPM, activity, other=compare)
    xrange = xrange or (hr.x_range if hr else None)

    pw = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_POWER_ESTIMATE_W, activity, other=compare, ylo=0, x_range=xrange)
    add_climb_zones(pw, climbs, activity)
    pw_c = cumulative_plot(200, 200, N.MED_POWER_ESTIMATE_W, activity, other=compare, ylo=0)
    xrange = xrange or (pw.x_range if pw else None)

    cd = comparison_line_plot(700, 200, N.DISTANCE_KM, N.MED_CADENCE_RPM, activity, other=compare, ylo=0, x_range=xrange)
    add_climb_zones(cd, climbs, activity)
    hr_h = histogram_plot(200, 200, N.HR_ZONE, activity, xlo=1, xhi=5)

    show(gridplot([[el, el_c], [sp, sp_c], [hri, hri_c], [hr, hr_c], [pw, pw_c], [cd, hr_h]]))

    '''
    ## Activity Maps
    '''

    map = map_plot(400, 400, activity, other=compare)
    m_el = map_intensity_signed(200, 200, activity, N.GRADE_PC, ranges=map, power=0.5)
    m_sp = map_intensity(200, 200, activity, N.MED_SPEED_KMH, ranges=map, power=2)
    m_hr = map_intensity(200, 200, activity, N.HR_IMPULSE_10, ranges=map)
    m_pw = map_intensity(200, 200, activity, N.MED_POWER_ESTIMATE_W, ranges=map)
    show(row(map, gridplot([[m_el, m_sp], [m_hr, m_pw]], toolbar_location='right')))

    '''
    ## Activity Statistics
    '''

    '''
    Active time and distance exclude pauses.
    '''

    active[[N.ACTIVE_TIME_S, N.ACTIVE_DISTANCE_KM]].dropna(). \
        transform({N.ACTIVE_TIME_S: format_seconds, N.ACTIVE_DISTANCE_KM: format_km})

    '''
    Climbs are auto-detected and shown only for the main activity. They are included in the elevation plot above.
    '''

    if present(climbs, N.CLIMB_TIME):
        display(transform(climbs,
                          {N.CLIMB_TIME: format_seconds, N.CLIMB_ELEVATION: format_metres,
                           N.CLIMB_DISTANCE: format_km, N.CLIMB_GRADIENT: format_percent,
                           N.VERTICAL_POWER: format_watts, N.CLIMB_CATEGORY: lambda x: x}))

    '''
    ## Health and Fitness
    '''

    fitness, fatigue = like(N.FITNESS_ANY, health.columns), like(N.FATIGUE_ANY, health.columns)
    colours = ['black'] * len(fitness) + ['red'] * len(fatigue)
    alphas = [1.0] * len(fitness) + [0.5] * len(fatigue)
    ff = multi_line_plot(900, 300, N.TIME, fitness + fatigue, health, colours, alphas=alphas)
    xrange = ff.x_range if ff else None
    add_multi_line_at_index(ff, N.TIME, fitness + fatigue, health, colours, alphas=alphas, index=-1)
    atd = std_distance_time_plot(900, 200, health, x_range=xrange)
    show(gridplot([[ff], [atd]]))

0 Source : utils.py
with Apache License 2.0
from CNES

def compare_2_disparities(
    input_first_disp_map: xr.Dataset, first_title: str, input_second_disp_map: xr.Dataset, second_title: str
) -> None:
    """
    Show 2 disparity maps
    :param input_first_disp_map: disparity map
    :type input_first_disp_map: dataset
    :param first_title: disparity map title
    :type first_title: str
    :param input_second_disp_map: disparity map
    :type input_second_disp_map: dataset
    :param second_title: disparity map title
    :type second_title: str
    :return: none
    """
    output_notebook()
    size = 0.5

    first_disp_map = add_validity_mask_to_dataset(input_first_disp_map)
    second_disp_map = add_validity_mask_to_dataset(input_second_disp_map)

    valid_idx = np.where(first_disp_map["validity_mask"].data == 0)
    min_d = np.nanmin(first_disp_map["disparity_map"].data[valid_idx])
    max_d = np.nanmax(first_disp_map["disparity_map"].data[valid_idx])

    cmap_pandora = pandora_cmap()
    mapper_avec_opti = LinearColorMapper(palette=cmap_to_palette(cmap_pandora), low=min_d, high=max_d)

    color_bar = ColorBar(
        color_mapper=mapper_avec_opti, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)
    )

    dw = first_disp_map["disparity_map"].shape[1]
    dh = first_disp_map["disparity_map"].shape[0]

    if first_title == None:
        first_title = "First disparity map"
    if second_title == None:
        second_title = "Second disparity map"

    # First disparity map
    first_fig = figure(
        title=first_title, width=450, height=450, tools=["reset", "pan", "box_zoom"], output_backend="webgl"
    )

    first_fig.image(
        image=[np.flip(first_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(first_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(first_disp_map["invalid_mask"].data != 0)[0]
    first_inv_msk = first_fig.circle(x=x, y=y, size=size, color="black")

    legend = Legend(items=[("inv msk", [first_inv_msk])], location="center", click_policy="hide")

    first_fig.add_layout(legend, "below")
    first_fig.add_layout(color_bar, "right")

    # Second disparity map
    second_fig = figure(
        title=second_title,
        width=450,
        height=450,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        x_range=first_fig.x_range,
        y_range=first_fig.y_range,
    )

    second_fig.image(
        image=[np.flip(second_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(second_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(second_disp_map["invalid_mask"].data != 0)[0]
    second_inv_msk = second_fig.circle(x=x, y=y, size=size, color="black")

    legend = Legend(
        items=[("inv msk", [second_inv_msk])], glyph_height=10, glyph_width=10, location="center", click_policy="hide"
    )

    second_fig.add_layout(legend, "below")
    second_fig.add_layout(color_bar, "right")

    layout = column(row(first_fig, second_fig))

    show(layout)


def compare_3_disparities_and_error(

0 Source : utils.py
with Apache License 2.0
from CNES

def compare_3_disparities_and_error(
    input_first_disp_map: xr.Dataset,
    first_title: str,
    input_second_disp_map: xr.Dataset,
    second_title: str,
    input_third_disp_map: xr.Dataset,
    third_title: str,
    error_map: np.array,
    error_title: str,
) -> None:
    """
    Show 3 disparity maps and error
    :param input_first_disp_map: disparity map
    :type input_first_disp_map: dataset
    :param first_title: disparity map title
    :type first_title: str
    :param input_second_disp_map: disparity map
    :type input_second_disp_map: dataset
    :param second_title: disparity map title
    :type second_title: str
    :param input_third_disp_map: disparity map
    :type input_third_disp_map: dataset
    :param third_title: disparity map title
    :type third_title: str
    :param error_map: error map
    :type error_map: np.array
    :param error_title: error title
    :type error_title: str
    :return: none
    """
    output_notebook()
    size = 0.5

    first_disp_map = add_validity_mask_to_dataset(input_first_disp_map)
    second_disp_map = add_validity_mask_to_dataset(input_second_disp_map)
    third_disp_map = add_validity_mask_to_dataset(input_third_disp_map)

    valid_idx = np.where(first_disp_map["validity_mask"].data == 0)
    min_d = np.nanmin(first_disp_map["disparity_map"].data[valid_idx])
    max_d = np.nanmax(first_disp_map["disparity_map"].data[valid_idx])
    cmap_pandora = pandora_cmap()
    mapper_avec_opti = LinearColorMapper(palette=cmap_to_palette(cmap_pandora), low=min_d, high=max_d)

    color_bar = ColorBar(
        color_mapper=mapper_avec_opti, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)
    )

    dw = first_disp_map["disparity_map"].shape[1]
    dh = first_disp_map["disparity_map"].shape[0]

    # First disparity map
    first_fig = figure(
        title=first_title, width=400, height=400, tools=["reset", "pan", "box_zoom"], output_backend="webgl"
    )

    first_fig.image(
        image=[np.flip(first_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(first_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(first_disp_map["invalid_mask"].data != 0)[0]
    first_inv_msk = first_fig.circle(x=x, y=y, size=size, color="black")
    legend = Legend(items=[("inv msk", [first_inv_msk])], location="center", click_policy="hide")
    first_fig.add_layout(legend, "below")
    first_fig.add_layout(color_bar, "right")

    # Second disparity map
    second_fig = figure(
        title=second_title,
        width=400,
        height=400,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        x_range=first_fig.x_range,
        y_range=first_fig.y_range,
    )

    second_fig.image(
        image=[np.flip(second_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(second_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(second_disp_map["invalid_mask"].data != 0)[0]
    second_inv_msk = second_fig.circle(x=x, y=y, size=size, color="black")
    legend = Legend(
        items=[("inv msk", [second_inv_msk])], glyph_height=10, glyph_width=10, location="center", click_policy="hide"
    )
    second_fig.add_layout(legend, "below")
    second_fig.add_layout(color_bar, "right")

    # Third disparity map
    third_fig = figure(
        title=third_title,
        width=400,
        height=400,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        x_range=first_fig.x_range,
        y_range=first_fig.y_range,
    )

    third_fig.image(
        image=[np.flip(third_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(third_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(third_disp_map["invalid_mask"].data != 0)[0]
    third_inv_msk = third_fig.circle(x=x, y=y, size=size, color="black")

    legend = Legend(
        items=[("inv msk", [third_inv_msk])], glyph_height=10, glyph_width=10, location="center", click_policy="hide"
    )
    third_fig.add_layout(legend, "below")
    third_fig.add_layout(color_bar, "right")

    # Error plot
    error_fig = figure(
        title=error_title,
        width=400,
        height=400,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        x_range=first_fig.x_range,
        y_range=first_fig.y_range,
    )
    min_d = 0
    max_d = 10
    reds_cmap = cm.get_cmap("Reds", 256)
    mapper_avec_opti = LinearColorMapper(palette=cmap_to_palette(reds_cmap), low=min_d, high=max_d)

    color_bar = ColorBar(
        color_mapper=mapper_avec_opti, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)
    )
    error_fig.image(image=[np.flip(error_map, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti)
    error_fig.add_layout(color_bar, "right")

    layout = column(row(first_fig, second_fig), row(third_fig, error_fig))

    show(layout)


def compare_disparity_and_error(

0 Source : utils.py
with Apache License 2.0
from CNES

def compare_disparity_and_error(
    input_first_disp_map: xr.Dataset, first_title: str, error_map: np.array, error_title: str
) -> None:
    """
    Show disparity map and error
    :param left_disp_map: disparity map
    :type left_disp_map: dataset
    :param title: disparity map title
    :type title: str
    :param error_map: error map
    :type error_map: np.array
    :param error_title: error title
    :type error_title: str
    :return: none
    """
    output_notebook()
    size = 0.5

    # Disparity map
    first_disp_map = add_validity_mask_to_dataset(input_first_disp_map)

    valid_idx = np.where(first_disp_map["validity_mask"].data == 0)
    min_d = np.nanmin(first_disp_map["disparity_map"].data[valid_idx])
    max_d = np.nanmax(first_disp_map["disparity_map"].data[valid_idx])
    cmap_pandora = pandora_cmap()
    mapper_avec_opti = LinearColorMapper(palette=cmap_to_palette(cmap_pandora), low=min_d, high=max_d)

    color_bar = ColorBar(
        color_mapper=mapper_avec_opti, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)
    )

    dw = first_disp_map["disparity_map"].shape[1]
    dh = first_disp_map["disparity_map"].shape[0]

    first_fig = figure(
        title=first_title,
        width=450,
        height=450,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        sizing_mode="scale_width",
    )
    first_fig.image(
        image=[np.flip(first_disp_map["disparity_map"].data, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti
    )

    x = np.where(first_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(first_disp_map["invalid_mask"].data != 0)[0]
    first_inv_msk = first_fig.circle(x=x, y=y, size=size, color="black")
    legend = Legend(items=[("inv msk", [first_inv_msk])], location="center", click_policy="hide")

    first_fig.add_layout(legend, "below")
    first_fig.add_layout(color_bar, "right")

    # Error plot
    error_fig = figure(
        title=error_title,
        width=450,
        height=450,
        tools=["reset", "pan", "box_zoom"],
        output_backend="webgl",
        x_range=first_fig.x_range,
        y_range=first_fig.y_range,
        sizing_mode="scale_width",
    )
    min_d = 0
    max_d = 10
    reds_cmap = cm.get_cmap("Reds", 256)
    mapper_avec_opti = LinearColorMapper(palette=cmap_to_palette(reds_cmap), low=min_d, high=max_d)

    color_bar = ColorBar(
        color_mapper=mapper_avec_opti, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)
    )
    error_fig.image(image=[np.flip(error_map, 0)], x=1, y=0, dw=dw, dh=dh, color_mapper=mapper_avec_opti)

    # Add disparity's error mask on error
    x = np.where(first_disp_map["invalid_mask"].data != 0)[1]
    y = dh - np.where(first_disp_map["invalid_mask"].data != 0)[0]
    error_inv_msk = error_fig.circle(x=x, y=y, size=size, color="black")
    legend = Legend(items=[("inv msk", [error_inv_msk])], location="center", click_policy="hide")

    error_fig.add_layout(legend, "below")
    error_fig.add_layout(color_bar, "right")

    layout = column(row(first_fig, error_fig))
    show(layout)


def show_input_images(img_left: xr.Dataset, img_right: xr.Dataset) -> None:

0 Source : utils.py
with Apache License 2.0
from CNES

def show_input_images(img_left: xr.Dataset, img_right: xr.Dataset) -> None:
    """
    Show input images and anaglyph
    :param left_disp_map: disparity map
    :type left_disp_map: dataset
    :param right_disp_map: right disparity map
    :type right_disp_map: dataset
    :return: none
    """
    output_notebook()

    dw = np.flip(img_left.im.data, 0).shape[1]
    dh = np.flip(img_right.im.data, 0).shape[0]
    width = 320
    height = 320

    # Image left
    img_left_data = img_left.im.data
    left_fig = bpl.figure(title="Left image", width=width, height=height)
    left_fig.image(image=[np.flip(img_left_data, 0)], x=1, y=0, dw=dw, dh=dh)

    # Image right
    img_right_data = img_right.im.data
    right_fig = bpl.figure(
        title="Right image", width=width, height=height, x_range=left_fig.x_range, y_range=left_fig.y_range
    )
    right_fig.image(image=[np.flip(img_right_data, 0)], x=1, y=0, dw=dw, dh=dh)

    # Anaglyph
    img_left, img_right_align = xr.align(img_left, img_right)
    anaglyph = np.stack((img_left.im, img_right_align.im, img_right_align.im), axis=-1)

    clip_percent = 5
    vmin_ref = np.percentile(img_left.im, clip_percent)
    vmax_ref = np.percentile(img_left.im, 100 - clip_percent)
    vmin_sec = np.percentile(img_right.im, clip_percent)
    vmax_sec = np.percentile(img_right.im, 100 - clip_percent)
    vmin_anaglyph = np.array([vmin_ref, vmin_sec, vmin_sec])
    vmax_anaglyph = np.array([vmax_ref, vmax_sec, vmax_sec])
    img = np.clip((anaglyph - vmin_anaglyph) / (vmax_anaglyph - vmin_anaglyph), 0, 1)
    anaglyph = np.clip((anaglyph - vmin_anaglyph) / (vmax_anaglyph - vmin_anaglyph), 0, 1)

    # Add 4rth channel to use bokeh's image_rgba function
    img = np.empty((dh, dw), dtype=np.uint32)
    view = img.view(dtype=np.uint8).reshape(dh, dw, 4)
    for i in range(dh):
        for j in range(dw):
            view[i, j, 0] = anaglyph[i, j, 0] * 255
            view[i, j, 1] = anaglyph[i, j, 1] * 255
            view[i, j, 2] = anaglyph[i, j, 2] * 255
            view[i, j, 3] = 255
    anaglyph_fig = bpl.figure(
        title="Anaglyph", width=width, height=height, x_range=left_fig.x_range, y_range=left_fig.y_range
    )
    anaglyph_fig.image_rgba(image=[np.flip(img, 0)], x=1, y=0, dw=dw, dh=dh)
    layout = column(row(left_fig, right_fig, anaglyph_fig))
    show(layout)


def get_error(

0 Source : plot.py
with BSD 3-Clause "New" or "Revised" License
from CoffeaTeam

def bokeh_plot(histo, jup_url="http://127.0.0.1:8889"):
    if not isnotebook():
        raise NotImplementedError("Only usable in jupyter notebook")
    import bokeh.plotting.figure as bk_figure
    from bokeh.io import show
    from bokeh import palettes
    from bokeh.layouts import row, column
    from bokeh.models import ColumnDataSource
    from bokeh.models.widgets import RadioButtonGroup, CheckboxButtonGroup
    from bokeh.models.widgets import RangeSlider, Div
    from bokeh.io import output_notebook  # enables plot interface in J notebook

    # init bokeh

    from bokeh.application import Application
    from bokeh.application.handlers import FunctionHandler

    from bokeh.core.validation import silence
    from bokeh.core.validation.warnings import EMPTY_LAYOUT

    silence(EMPTY_LAYOUT, True)

    output_notebook()

    # Set up widgets
    cfg_labels = ["Ghost"]
    wi_config = CheckboxButtonGroup(labels=cfg_labels, active=[0])
    wi_dense_select = RadioButtonGroup(
        labels=[ax.name for ax in histo.dense_axes()], active=0
    )
    wi_sparse_select = RadioButtonGroup(
        labels=[ax.name for ax in histo.sparse_axes()], active=0
    )

    # Dense widgets
    sliders = {}
    for ax in histo.dense_axes():
        edge_vals = (histo.axis(ax.name).edges()[0], histo.axis(ax.name).edges()[-1])
        _smallest_bin = numpy.min(numpy.diff(histo.axis(ax.name).edges()))
        sliders[ax.name] = RangeSlider(
            title=ax.name,
            value=edge_vals,
            start=edge_vals[0],
            end=edge_vals[1],
            step=_smallest_bin,
            name=ax.name,
        )

    # Cat widgets
    togglers = {}
    for ax in histo.sparse_axes():
        togglers[ax.name] = CheckboxButtonGroup(
            labels=[i.name for i in ax.identifiers()], active=[0], name=ax.name
        )

    # Toggles for all widgets
    configers = {}
    for ax in histo.sparse_axes():
        configers[ax.name] = CheckboxButtonGroup(
            labels=["Display", "Ghost"], active=[0, 1], name=ax.name
        )
    for ax in histo.dense_axes():
        configers[ax.name] = CheckboxButtonGroup(
            labels=["Display"], active=[0], name=ax.name
        )

    # Figure
    fig = bk_figure(
        title="1D Projection",
        plot_width=500,
        plot_height=500,
        min_border=20,
        toolbar_location=None,
    )
    fig.yaxis.axis_label = "N"
    fig.xaxis.axis_label = "Quantity"

    # Iterate over possible overlays
    _max_idents = 0  # Max number of simultaneou histograms
    for ax in histo.sparse_axes():
        _max_idents = max(_max_idents, len([i.name for i in ax.identifiers()]))

    # Data source list
    sources = []
    sources_ghost = []
    for i in range(_max_idents):
        sources.append(ColumnDataSource(dict(left=[], top=[], right=[], bottom=[])))
        sources_ghost.append(
            ColumnDataSource(dict(left=[], top=[], right=[], bottom=[]))
        )

    # Hist list
    hists = []
    hists_ghost = []
    for i in range(_max_idents):
        if _max_idents   <   10:
            _color = palettes.Category10[min(max(3, _max_idents), 10)][i]
        else:
            _color = palettes.magma(_max_idents)[i]
        hists.append(
            fig.quad(
                left="left",
                right="right",
                top="top",
                bottom="bottom",
                source=sources[i],
                alpha=0.9,
                color=_color,
            )
        )
        hists_ghost.append(
            fig.quad(
                left="left",
                right="right",
                top="top",
                bottom="bottom",
                source=sources_ghost[i],
                alpha=0.05,
                color=_color,
            )
        )

    def update_data(attrname, old, new):
        sparse_active = wi_sparse_select.active
        sparse_name = [ax.name for ax in histo.sparse_axes()][sparse_active]
        sparse_other = [ax.name for ax in histo.sparse_axes() if ax.name != sparse_name]

        dense_active = wi_dense_select.active
        dense_name = [ax.name for ax in histo.dense_axes()][dense_active]
        dense_other = [ax.name for ax in histo.dense_axes() if ax.name != dense_name]

        # Apply cuts in projections
        _h = histo.copy()
        for proj_ax in sparse_other:
            _idents = histo.axis(proj_ax).identifiers()
            _labels = [ident.name for ident in _idents]
            if 0 in configers[proj_ax].active:
                _h = _h.integrate(
                    proj_ax, [_labels[i] for i in togglers[proj_ax].active]
                )
            else:
                _h = _h.integrate(proj_ax)

        for proj_ax in dense_other:
            _h = _h.integrate(
                proj_ax, slice(sliders[proj_ax].value[0], sliders[proj_ax].value[1])
            )

        for cat_ix in range(_max_idents):
            # Update histo for each toggled overlay
            if cat_ix in togglers[sparse_name].active:
                cat_value = histo.axis(sparse_name).identifiers()[cat_ix]
                h1d = _h.integrate(sparse_name, cat_value)

                # Get shown histogram
                values = h1d.project(dense_name).values()
                if values != {}:
                    h = values[()]
                    bins = h1d.axis(dense_name).edges()

                    # Apply cuts on shown axis
                    bin_los = bins[:-1][bins[:-1] > sliders[dense_name].value[0]]
                    bin_his = bins[1:][bins[1:]  <  sliders[dense_name].value[1]]
                    new_bins = numpy.intersect1d(bin_los, bin_his)
                    bin_ixs = numpy.searchsorted(bins, new_bins)[:-1]
                    h = h[bin_ixs]

                    sources[cat_ix].data = dict(
                        left=new_bins[:-1],
                        right=new_bins[1:],
                        top=h,
                        bottom=numpy.zeros_like(h),
                    )
                else:
                    sources[cat_ix].data = dict(left=[], right=[], top=[], bottom=[])

                # Add ghosts
                if 0 in wi_config.active:
                    h1d = histo.integrate(sparse_name, cat_value)
                    for proj_ax in sparse_other:
                        _idents = histo.axis(proj_ax).identifiers()
                        _labels = [ident.name for ident in _idents]
                        if 1 not in configers[proj_ax].active:
                            h1d = h1d.integrate(
                                proj_ax, [_labels[i] for i in togglers[proj_ax].active]
                            )
                        else:
                            h1d = h1d.integrate(proj_ax)
                    values = h1d.project(dense_name).values()
                    if values != {}:
                        h = h1d.project(dense_name).values()[()]
                        bins = h1d.axis(dense_name).edges()
                        sources_ghost[cat_ix].data = dict(
                            left=bins[:-1],
                            right=bins[1:],
                            top=h,
                            bottom=numpy.zeros_like(h),
                        )
                    else:
                        sources_ghost[cat_ix].data = dict(
                            left=[], right=[], top=[], bottom=[]
                        )
            else:
                sources[cat_ix].data = dict(left=[], right=[], top=[], bottom=[])
                sources_ghost[cat_ix].data = dict(left=[], right=[], top=[], bottom=[])

        # Cosmetics
        fig.xaxis.axis_label = dense_name

    for name, slider in sliders.items():
        slider.on_change("value", update_data)
    for name, toggler in togglers.items():
        toggler.on_change("active", update_data)
    for name, configer in configers.items():
        configer.on_change("active", update_data)
    # Button
    for w in [wi_dense_select, wi_sparse_select, wi_config]:
        w.on_change("active", update_data)

    from bokeh.models.widgets import Panel, Tabs

    layout = row(
        fig,
        column(
            Div(
                text=" < b>Overlay Axis: < /b>",
                style={"font-size": "100%", "color": "black"},
            ),
            wi_sparse_select,
            Div(
                text=" < b>Plot Axis: < /b>", style={"font-size": "100%", "color": "black"}
            ),
            wi_dense_select,
            Div(
                text=" < b>Categorical Cuts: < /b>",
                style={"font-size": "100%", "color": "black"},
            ),
            *[toggler for name, toggler in togglers.items()],
            Div(
                text=" < b>Dense Cuts: < /b>", style={"font-size": "100%", "color": "black"}
            ),
            *[slider for name, slider in sliders.items()]
        ),
    )

    # Config prep
    incl_lists = [[], [], []]
    for i, key in enumerate(list(configers.keys())):
        incl_lists[i // max(5, len(list(configers.keys())) / 3)].append(
            Div(
                text=" < b>{}: < /b>".format(key),
                style={"font-size": "70%", "color": "black"},
            )
        )
        incl_lists[i // max(5, len(list(configers.keys())) / 3)].append(configers[key])

    layout_cfgs = column(
        row(
            column(
                Div(
                    text=" < b>Configs: < /b>",
                    style={"font-size": "100%", "color": "black"},
                ),
                wi_config,
            )
        ),
        Div(
            text=" < b>Axis togglers: < /b>", style={"font-size": "100%", "color": "black"}
        ),
        row(
            column(incl_lists[0]),
            column(incl_lists[1]),
            column(incl_lists[2]),
        ),
    )

    # Update active buttons
    def update_layout(attrname, old, new):
        active_axes = [None]
        for name, wi in configers.items():
            if 0 in wi.active:
                active_axes.append(name)
        for child in layout.children[1].children:
            if child.name not in active_axes:
                child.visible = False
            else:
                child.visible = True

    for name, configer in configers.items():
        configer.on_change("active", update_layout)

    tab1 = Panel(child=layout, title="Projection")
    tab2 = Panel(child=layout_cfgs, title="Configs")
    tabs = Tabs(tabs=[tab1, tab2])

    def modify_doc(doc):
        doc.add_root(row(tabs, width=800))
        doc.title = "Sliders"

    handler = FunctionHandler(modify_doc)
    app = Application(handler)

    show(app, notebook_url=jup_url)
    update_data("", "", "")

0 Source : bokeh_sliders.py
with GNU General Public License v3.0
from drscotthawley

def update_effect(attrname, old, new):
    global effect, model, knob_names, knob_ranges, num_knobs, knob_sliders
    # match the menu option with the right entry in effects_dict
    long_name = effect_select.value
    plot.title.text = f"Trying to setup effect '{long_name}'..."
    shortname = ''
    for key, val in effects_dict.items():
        if val['name'] == long_name:
            shortname = key
            break
    if '' == shortname:
        plot.title.text = f"**ERROR: Effect '{long_name}' not defined**"
        return
    effect = effects_dict[shortname]['effect']
    num_knobs = 0
    if effect is not None:
        knob_names, knob_ranges = effect.knob_names, np.array(effect.knob_ranges)
        num_knobs = len(knob_names)

    # try to read the checkpoint file
    checkpoint_file = effects_dict[shortname]['checkpoint']
    model = setup_model(checkpoint_file, fatal=False)
    if model is  None:
        msg = f"**ERROR: checkpoint file '{checkpoint_file}' not found**"
        print("\n",msg)
        plot.title.text = msg

    # rebuild the entire display  (because knobs have changed)
    knob_sliders = []
    if num_knobs > 0:
        knobs_wc = knob_ranges.mean(axis=1)
        for k in range(num_knobs):
            start, end = knob_ranges[k][0], knob_ranges[k][1]
            mid = knobs_wc[k]
            step = (end-start)/25
            tmp = Slider(title=knob_names[k], value=mid, start=start, end=end, step=step)
            knob_sliders.append(tmp)
        for w in knob_sliders:  # since we now defined new widgets, we need triggers for them
            w.on_change('value', update_data)

    inputs = column([effect_select, input_select]+knob_sliders )
    curdoc().clear()
    curdoc().add_root(row(inputs, plot, width=800))
    curdoc().title = "SignalTrain Demo"

    update_data(attrname, old, new)


def update_input(attrname, old, new):

0 Source : plotting.py
with BSD 3-Clause "New" or "Revised" License
from FeatureLabs

def piechart(col, sort=True, mergepast=None, drop_n=None, figargs=None):
    '''Creates a piechart.
    Finds all of the unique values in a column and makes a piechart
    out of them. By default, this will make a dynamic piechart with
    sliders for the different parameters.

    Args:
        col (pd.Series): The column from which to make the piechart.
        sort (bool): Whether or not to sort by frequency for static plot. Default is True.
        mergepast (int): Merge infrequent column values for static plot. Default is 10.
        drop_n (int): How many high frequency values to drop for static plot. Default is None.

    Example:
        If the dataframe ``X`` has a column named ``car_color``:

        >>> import henchman.plotting as hplot
        >>> plot = hplot.piechart(X['car_color'])
        >>> hplot.show(plot)

        For a static plot:

        >>> import henchman.plotting as hplot
        >>> plot = hplot.piechart(X['car_color'], sort=False)
        >>> hplot.show(plot, static=True)
    '''
    if figargs is None:
        return lambda figargs: piechart(col, sort, mergepast, drop_n, figargs)

    source = ColumnDataSource(_make_piechart_source(col, mergepast, sort, drop_n, figargs))
    plot = _make_piechart_plot(source, figargs)
    plot = _modify_plot(plot, figargs)

    if figargs['static']:
        return plot

    def modify_doc(doc, col, sort, mergepast, drop_n, figargs):
        def callback(attr, old, new):
            try:
                source.data = ColumnDataSource(
                    _make_piechart_source(col,
                                          sort=sorted_button.active,
                                          mergepast=merge_slider.value,
                                          drop_n=drop_slider.value,
                                          figargs=figargs)).data
            except Exception as e:
                print(e)

        sorted_button, merge_slider, drop_slider = _piechart_widgets(
            col, sort, mergepast, drop_n, callback)

        doc.add_root(
            column(row(column(merge_slider, drop_slider), sorted_button), plot))

    return lambda doc: modify_doc(doc, col, sort, mergepast, drop_n, figargs)


def histogram(col, y=None, n_bins=10, col_max=None, col_min=None,

0 Source : candlestick.py
with Apache License 2.0
from FitzHoo

def candlestick_plot():
    def obv_indicator(data):
        res = talib.OBV(data.close.values, data.volume.values)
        return res

    def rsi_indicator(data):
        res = talib.RSI(data.close.values, timeperiod=14)
        return res

    def cci_indicator(data):
        res = talib.CCI(data.high.values, data.low.values, data.close.values, timeperiod=14)
        return res

    def technical_indicator(data, indicator):
        if indicator == 'CCI':
            data['tech'] = cci_indicator(data)
        elif indicator == 'RSI':
            data['tech'] = rsi_indicator(data)
        else:
            data['tech'] = obv_indicator(data)
        return data

    def load_data(obid, start, end, freq='1d'):
        print('running....')
        data = get_price(obid, start, end, freqency=freq).reset_index()
        data['pct_change'] = data['close'].pct_change()
        # data.dropna(inplace=True)

        data['pct_change'] = data['pct_change'].apply(lambda x: str(round(x * 100, 2)) + '%')
        data['index'] = list(np.arange(len(data)))
        data['date'] = data['date'].apply(lambda x: x.strftime("%Y%m%d"))

        return data

    def moving_average(data, selection):
        selection_mapping = {k: int(k.split('_')[-1]) for k in selection}
        for k, v in selection_mapping.items():
            data[k] = data['close'].rolling(window=v).mean()
        return data

    def update_lines(attr, old, new):
        line_0.visible = 0 in average_selection.active
        line_1.visible = 1 in average_selection.active
        line_2.visible = 2 in average_selection.active
        line_3.visible = 3 in average_selection.active
        line_4.visible = 4 in average_selection.active
        line_5.visible = 5 in average_selection.active

    def update_plot(attr, old, new):
        indicator = indicator_selection.value
        new_data = technical_indicator(data, indicator)
        new_source = ColumnDataSource(new_data)

        source.data.update(new_source.data)

    def update_data():
        # global obid, start, end
        obid = order_book_id.value
        start = start_date.value
        end = end_date.value

        # 提取数据,均线根据选取与否进行添加
        new_data = load_data(obid, start, end)
        new_data_1 = moving_average(new_data, average_labels)
        new_data_2 = technical_indicator(new_data, indicator_selection.value)

        new_source = ColumnDataSource(new_data_2)
        new_source_1 = ColumnDataSource(new_data_1)
        source.data.update(new_source.data)
        source_1.data.update(new_source_1.data)

        inc = new_data.close >= new_data.open
        dec = new_data.close   <   new_data.open

        inc_source.data = inc_source.from_df(new_data_2.loc[inc])
        dec_source.data = dec_source.from_df(new_data_2.loc[dec])

        p.title.text = instruments(obid).symbol
        p.x_range.end = len(new_data) + 1
        p2.xaxis.major_label_overrides = {i: date for i, date in enumerate(new_data['date'])}

    today = datetime.now().date()

    average_labels = ["MA_5", "MA_10", "MA_20", 'MA_30', 'MA_60', 'MA_120']
    average_selection = CheckboxGroup(labels=average_labels, active=[0, 1, 2, 3, 4, 5, 6])

    indicator_selection = Select(title='TechnicalIndicator', value='RSI', options=['OBV', 'RSI', 'CCI'])

    order_book_id = TextInput(title='StockCode', value='002916.XSHE')
    symbol = instruments(order_book_id.value).symbol
    start_date = DatePicker(title="StartDate", value='2018-01-01', min_date='2015-01-01', max_date=today)
    end_date = DatePicker(title="EndDate", value=today, min_date=start_date.value, max_date=today)

    #     labels = [average_selection.labels[i] for i in average_selection.active]
    data = load_data(order_book_id.value, start_date.value, end_date.value)

    # 均线计算
    data_1 = moving_average(data, average_labels)  # 计算各种长度的均线

    # 技术指标计算
    data_2 = technical_indicator(data, indicator_selection.value)

    source = ColumnDataSource(data_2)
    source_1 = ColumnDataSource(data_1)

    inc = data.close >= data.open
    dec = data.open > data.close

    inc_source = ColumnDataSource(data_2.loc[inc])
    dec_source = ColumnDataSource(data_2.loc[dec])

    TOOLS = 'save, pan, box_zoom, reset, wheel_zoom'

    hover = HoverTool(tooltips=[('date', '@date'),
                                ('open', '@open'),
                                ('high', '@high'),
                                ('low', '@low'),
                                ('close', '@close'),
                                ('pct_change', "@pct_change")
                                ]
                      )

    length = len(data)
    p = figure(plot_width=1000, plot_height=500, title='{}'.format(symbol), tools=TOOLS, x_range=(0, length + 1))
    p.xaxis.visible = False  # 隐藏x-axis
    p.min_border_bottom = 0

    # 均线图
    line_0 = p.line(x='index', y='MA_5', source=source_1, color=Spectral6[5])
    line_1 = p.line(x='index', y='MA_10', source=source_1, color=Spectral6[4])
    line_2 = p.line(x='index', y='MA_20', source=source_1, color=Spectral6[3])
    line_3 = p.line(x='index', y='MA_30', source=source_1, color=Spectral6[2])
    line_4 = p.line(x='index', y='MA_60', source=source_1, color=Spectral6[1])
    line_5 = p.line(x='index', y='MA_120', source=source_1, color=Spectral6[0])

    p.segment(x0='index', y0='high', x1='index', y1='low', color='red', source=inc_source)
    p.segment(x0='index', y0='high', x1='index', y1='low', color='green', source=dec_source)
    p.vbar('index', 0.5, 'open', 'close', fill_color='red', line_color='red', source=inc_source, hover_fill_alpha=0.5)
    p.vbar('index', 0.5, 'open', 'close', fill_color='green', line_color='green', source=dec_source,
           hover_fill_alpha=0.5)

    p.add_tools(hover)

    p1 = figure(plot_width=p.plot_width, plot_height=200, x_range=p.x_range, toolbar_location=None)
    p1.vbar('index', 0.5, 0, 'volume', color='red', source=inc_source)
    p1.vbar('index', 0.5, 0, 'volume', color='green', source=dec_source)
    p1.xaxis.visible = False

    p2 = figure(plot_width=p.plot_width, plot_height=p1.plot_height, x_range=p.x_range, toolbar_location=None)
    p2.line(x='index', y='tech', source=source)

    p2.xaxis.major_label_overrides = {i: date for i, date in enumerate(data['date'])}
    p2.xaxis.major_label_orientation = pi / 4
    p2.min_border_bottom = 0

    button = Button(label="ClickToChange", button_type="success")
    button.on_click(update_data)
    average_selection.inline = True
    average_selection.width = 500
    average_selection.on_change('active', update_lines)
    indicator_selection.on_change('value', update_plot)
    widgets = column(row(order_book_id, start_date, end_date, button), row(indicator_selection, average_selection))

    layouts = column(widgets, p, p1, p2)

    # doc.add_root(pp)
    # make a layout
    tab = Panel(child=layouts, title='StockPrice')

    return tab


# tabs = Tabs(tabs=[candlestick_plot()])
# curdoc().add_root(tabs)


0 Source : industry_analysis.py
with Apache License 2.0
from FitzHoo

def sw_industry_analysis():

    def nix(val, lst):
        return [x for x in lst if x != val]

    def get_data(ticker_1, ticker_2, start='20180101', end=datetime.today().date()):
        df = get_price([ticker_1, ticker_2], start, end, fields='close')
        df['t1_returns'] = np.log(df[ticker_1]).diff()
        df['t2_returns'] = np.log(df[ticker_2]).diff()
        return df.dropna().reset_index()

    def get_hhist_data(data):
        hhist, hedges = np.histogram(data['t1_returns'], bins=20)
        hzeros = np.zeros_like(hhist)
        hhist_data = {'left': hedges[:-1], 'right': hedges[1:], 'bottom': hzeros,
                      'top': hhist, 'top_1': hzeros, 'top_2': hzeros}
        return hhist_data

    def get_vhist_data(data):
        vhist, vedges = np.histogram(data['t2_returns'], bins=20)
        vzeros = np.zeros_like(vhist)
        vhist_data = {'left': vzeros, 'right': vhist, 'bottom': vedges[:-1],
                      'top': vedges[1:], 'right_1': vzeros, 'right_2': vzeros}
        return vhist_data

    def ticker1_change(attr, old, new):
        ticker_2.options = nix(new, DEFAULT_TICKERS)
        update()

    def ticker2_change(attr, old, new):
        ticker_1.options = nix(new, DEFAULT_TICKERS)
        update()

    def update():
        global df
        ticker_1_name, ticker_2_name = SHENWAN_INDUSTRY_MAP_[ticker_1.value], SHENWAN_INDUSTRY_MAP_[ticker_2.value]
        df = get_data(ticker_1_name, ticker_2_name)

        source.data.update(dict(x=df['t1_returns'], y=df['t2_returns'], x_p=df[ticker_1_name],
                                y_p=df[ticker_2_name], date=df['date']))

        hhist_data_dict = get_hhist_data(df)
        source_hhist.data.update(hhist_data_dict)
        hmax = max(source_hhist.data['top']) * 1.1
        ph.y_range.update(start=-hmax, end=hmax)
        print('ph.y_range', ph.y_range.end)

        vhist_data_dict = get_vhist_data(df)
        source_vhist.data.update(vhist_data_dict)
        vmax = max(source_vhist.data['right']) * 1.1
        pv.x_range.update(start=vmax, end=-vmax)
        print('pv.x_range', pv.x_range.end)
        print(20 * '=')

        update_stats(df, ticker_1_name, ticker_2_name)

        corr.title.text = "{} vs. {}".format(ticker_1.value, ticker_2.value)
        ts1.title.text = ticker_1.value
        ts2.title.text = ticker_2.value

    def udpate_selection(attr, old, new):
        inds = new  # 选定的数据对应的索引
        length = len(df)
        if 0   <   len(inds)  <  length:
            neg_inds = [s for s in range(length) if s not in inds]  # 未选定数据点的对应索引
            _, hedges = np.histogram(df['t1_returns'], bins=20)
            _, vedges = np.histogram(df['t2_returns'], bins=20)

            new_hhist_df = df['t1_returns']
            new_vhist_df = df['t2_returns']

            hhist1, _ = np.histogram(new_hhist_df.iloc[inds], bins=hedges)
            hhist2, _ = np.histogram(new_hhist_df.iloc[neg_inds], bins=hedges)

            vhist1, _ = np.histogram(new_vhist_df.iloc[inds], bins=vedges)
            vhist2, _ = np.histogram(new_vhist_df.iloc[neg_inds], bins=vedges)

            source_hhist.patch({'top_1': [(slice(None), hhist1)], 'top_2': [(slice(None), -hhist2)]})
            source_vhist.patch({'right_1': [(slice(None), vhist1)], 'right_2': [(slice(None), -vhist2)]})

    def update_stats(data, t1, t2):
        stats_indicator = data[[t1, t2, 't1_returns', 't2_returns']].describe()
        ticker_1_name, ticker_2_name = ticker_1.value, ticker_2.value
        stats_indicator.columns = [ticker_1_name, ticker_2_name, ticker_1_name + '收益率', ticker_2_name + '收益率']
        stats.text = str(stats_indicator)

    # Set Up Widgets
    stats = PreText(text='', width=700)
    ticker_1 = Select(value='非银金融', options=nix('食品饮料', DEFAULT_TICKERS))
    ticker_2 = Select(value='食品饮料', options=nix('非银金融', DEFAULT_TICKERS))

    # Callback
    ticker_1.on_change('value', ticker1_change)
    ticker_2.on_change('value', ticker2_change)

    # Construct DataSource
    source = ColumnDataSource(data=dict(x=[], y=[], x_p=[], y_p=[], date=[]))
    source_hhist = ColumnDataSource(data=dict(left=[], right=[], bottom=[], top=[], top_1=[], top_2=[]))
    source_vhist = ColumnDataSource(data=dict(left=[], right=[], bottom=[], top=[], right_1=[], right_2=[]))

    # 收益率散点图
    corr = figure(plot_width=500, plot_height=500, tools=TOOLS)
    r = corr.scatter(x='x', y='y', size=2, source=source, selection_color='orange', alpha=0.6,
                     nonselection_alpha=0.1, selection_alpha=0.4)

    # 添加横轴直方图
    hmax = 40
    ph = figure(toolbar_location=None, plot_width=corr.plot_width, plot_height=200, y_range=(-hmax, hmax),
                min_border=10, min_border_left=None, y_axis_location='left', x_axis_location='above')
    ph.quad(bottom='bottom', top='top', left='left', right='right', color='white', line_color="#3A5785",
            source=source_hhist)
    ph.quad(bottom='bottom', top='top_1', left='left', right='right', alpha=0.5, source=source_hhist, **LINE_ARGS)
    ph.quad(bottom='bottom', top='top_2', left='left', right='right', alpha=0.1, source=source_hhist, **LINE_ARGS)

    ph.xgrid.grid_line_color = None
    ph.yaxis.major_label_orientation = np.pi / 4
    ph.background_fill_color = '#fafafa'

    # 添加纵轴直方图
    vmax = 40
    pv = figure(toolbar_location=None, plot_height=corr.plot_height, plot_width=200, x_range=(vmax, -vmax),
                min_border=10, min_border_left=None, y_axis_location='left')
    pv.quad(bottom='bottom', top='top', left='left', right='right', color='white', line_color="#3A5785",
            source=source_vhist)
    pv.quad(bottom='bottom', top='top', left='left', right='right_1', alpha=0.5, source=source_vhist, **LINE_ARGS)
    pv.quad(bottom='bottom', top='top', left='left', right='right_2', alpha=0.1, source=source_vhist, **LINE_ARGS)

    # 股价时间序列图
    ts1 = figure(plot_width=900, plot_height=200, tools=TOOLS, x_axis_type='datetime', active_drag='box_select',
                 toolbar_location='above')
    ts1.line('date', 'x_p', source=source)
    ts1.circle('date', 'x_p', size=1, source=source, color=None, selection_color='orange')

    ts2 = figure(plot_width=ts1.plot_width, plot_height=ts1.plot_height, tools=TOOLS, x_axis_type='datetime',
                 active_drag='box_select', toolbar_location='above')
    ts2.x_range = ts1.x_range
    ts2.line('date', 'y_p', source=source)
    ts2.circle('date', 'y_p', size=1, source=source, color=None, selection_color='orange')

    # 初始化数据
    update()

    r.data_source.selected.on_change('indices', udpate_selection)

    widgets = column(ticker_1, ticker_2, widgetbox(stats))
    layout_1 = column(row(Spacer(width=200, height=200), ph), row(pv, corr, widgets))

    layout_2 = column(layout_1, ts1, ts2)

    tab = Panel(child=layout_2, title='IndustryAnalysis')

    return tab

# tabs = Tabs(tabs=[sw_industry_analysis()])
# curdoc().add_root(tabs)

0 Source : figures.py
with GNU General Public License v3.0
from gotzl

def getLapControls(ds, slider):

    #### create a player that iterates over the data
    def increment(stepsize, direction=1):
        i = slider.value + direction*stepsize
        if i  <  0: i = 0
        if i>len(ds.data['dist']): i = len(ds.data['dist'])-1
        # update of the selected item in the ds by modifying the slider value
        slider.value = i
        slider.trigger('value', slider.value, i)


    def cbcrl(stop=False):
        global cb

        if cb is None and not stop:
            cb = curdoc().add_periodic_callback(lambda: increment(5), 5*50)
            # reset hovertool
            # hover0.renderers = []
            # hover.renderers = []
            play.label = "Pause"
        else:
            try:  curdoc().remove_periodic_callback(cb)
            except: pass
            cb = None
            play.label = "Play"

    global cb
    if not 'cb' in globals():
        cb = None
    if cb is not None:
        try:  curdoc().remove_periodic_callback(cb)
        except: cb = None

    play = Button(label="Play")
    play.on_click(cbcrl)

    btns = []
    def bb(): increment(50, -1)
    def b(): increment(5, -1)
    def f(): increment(5, 1)
    def ff(): increment(50, 1)
    for l,s in [(' <  < ',bb),(' < ',b),('>',f),('>>',ff)]:
        b = Button(label=l, width=50)
        b.on_click(s)
        btns.append(b)

    return row(play, *btns)


def getTrackMap(target, reference=None, mode='speed', view='lapsdelta'):

0 Source : laptable.py
with GNU General Public License v3.0
from gotzl

def create():
    columns = [
        TableColumn(field="name", title="File name"),
        TableColumn(field="datetime", title="Datetime"),
        TableColumn(field="driver", title="Driver"),
        TableColumn(field="track", title="Track"),
        TableColumn(field="car", title="Car"),
        TableColumn(field="lap", title="Lap"),
        TableColumn(field="time", title="Lap time"),
    ]

    source = ColumnDataSource()
    filter_source = ColumnDataSource()
    data_table = DataTable(source=filter_source, columns=columns, width=800)

    ### https://gist.github.com/dennisobrien/450d7da20daaba6d39d0
    # callback code to be used by all the filter widgets
    combined_callback_code = """
    var data = {};
    var original_data = source.data;
    var track = track_select_obj.value;
    var car = car_select_obj.value;
    for (var key in original_data) {
        data[key] = [];
        for (var i = 0; i   <   original_data['track'].length; ++i) {
            if ((track === "ALL" || original_data['track'][i] === track) &&
                    (car === "ALL" || original_data['car'][i] === car)) {
                data[key].push(original_data[key][i]);
            }
        }
    }
    
    filter_source.data = data;
    filter_source.change.emit();
    target_obj.change.emit();
    """

    # define the filter widgets
    track_select = Select(title="Track:", value='ALL', options=['ALL'])
    car_select = Select(title="Car:", value='ALL', options=['ALL'])

    # define the callback object
    generic_callback = CustomJS(
        args=dict(source=source,
                  filter_source=filter_source,
                  track_select_obj=track_select,
                  car_select_obj=car_select,
                  target_obj=data_table),
        code=combined_callback_code
    )

    # connect the callbacks to the filter widgets
    track_select.js_on_change('value', generic_callback)
    car_select.js_on_change('value', generic_callback)
    filters = row(track_select, car_select)
    ######

    return filters, data_table, source, filter_source, track_select, car_select

0 Source : client.py
with GNU General Public License v3.0
from happydasch

    def _createmodel(self):

        def on_select_filter(self, a, old, new):
            _logger.debug(f'Switching filter to {new}...')
            # ensure datahandler is stopped
            self._datahandler.stop()
            self._filter = new
            self.updatemodel()
            _logger.debug('Switching filter finished')

        def on_click_nav_action(self):
            if not self._paused:
                self._pause()
            else:
                self._resume()
            refresh(self)

        def on_click_nav_prev(self, steps=1):
            self._pause()
            self._set_data_by_idx(self._datahandler.get_last_idx() - steps)
            update_nav_buttons(self)

        def on_click_nav_next(self, steps=1):
            self._pause()
            self._set_data_by_idx(self._datahandler.get_last_idx() + steps)
            update_nav_buttons(self)

        def refresh(self):
            self.doc.add_next_tick_callback(partial(update_nav_buttons, self))

        def reset_nav_buttons(self):
            btn_nav_prev.disabled = True
            btn_nav_next.disabled = True
            btn_nav_action.label = '❙❙'

        def update_nav_buttons(self):
            last_idx = self._datahandler.get_last_idx()
            last_avail_idx = self._app.get_last_idx(self._figid)

            if last_idx   <   self.lookback:
                btn_nav_prev.disabled = True
                btn_nav_prev_big.disabled = True
            else:
                btn_nav_prev.disabled = False
                btn_nav_prev_big.disabled = False
            if last_idx >= last_avail_idx:
                btn_nav_next.disabled = True
                btn_nav_next_big.disabled = True
            else:
                btn_nav_next.disabled = False
                btn_nav_next_big.disabled = False
            if self._paused:
                btn_nav_action.label = '▶'
            else:
                btn_nav_action.label = '❙❙'

        # filter selection
        datanames = get_datanames(self._strategy)
        options = [('', 'Strategy')]
        for d in datanames:
            options.append(('D' + d, f'Data: {d}'))
        options.append(('G', 'Plot Group'))
        self._filter = 'D' + datanames[0]
        select_filter = Select(
            value=self._filter,
            options=options)
        select_filter.on_change(
            'value',
            partial(on_select_filter, self))
        # nav
        btn_nav_prev = Button(label='❮', width=self.NAV_BUTTON_WIDTH)
        btn_nav_prev.on_click(partial(on_click_nav_prev, self))
        btn_nav_prev_big = Button(label='❮❮', width=self.NAV_BUTTON_WIDTH)
        btn_nav_prev_big.on_click(partial(on_click_nav_prev, self, 10))
        btn_nav_action = Button(label='❙❙', width=self.NAV_BUTTON_WIDTH)
        btn_nav_action.on_click(partial(on_click_nav_action, self))
        btn_nav_next = Button(label='❯', width=self.NAV_BUTTON_WIDTH)
        btn_nav_next.on_click(partial(on_click_nav_next, self))
        btn_nav_next_big = Button(label='❯❯', width=self.NAV_BUTTON_WIDTH)
        btn_nav_next_big.on_click(partial(on_click_nav_next, self, 10))
        # layout
        controls = row(
            children=[select_filter])
        nav = row(
            children=[btn_nav_prev_big,
                      btn_nav_prev,
                      btn_nav_action,
                      btn_nav_next,
                      btn_nav_next_big])
        # tabs
        tabs = Tabs(
            id='tabs',
            sizing_mode=self._app.scheme.plot_sizing_mode)
        # model
        model = layout(
            [
                # app settings, top area
                [column(controls, width_policy='min'),
                 Spacer(),
                 column(nav, width_policy='min')],
                Spacer(height=15),
                # layout for tabs
                [tabs]
            ],
            sizing_mode='stretch_width')
        return model, partial(refresh, self)

    def updatemodel(self):

0 Source : analyzer.py
with GNU General Public License v3.0
from happydasch

    def _create_content(self):
        title_area = []
        title = Paragraph(
            text='Available Analyzer Results',
            css_classes=['panel-title'])
        title_area.append(row([title], width_policy='min'))
        if self._client:
            btn_refresh = Button(label='Refresh', width_policy='min')
            btn_refresh.on_click(self._on_update_analyzer_info)
            title_area.append(Spacer())
            title_area.append(row([btn_refresh], width_policy='min'))
        # set content in self
        return layout(
            [
                title_area,
                # initialize with info
                [self._get_analyzer_info()]
            ],
            sizing_mode='stretch_width')

    def _get_panel(self):

0 Source : metadata.py
with GNU General Public License v3.0
from happydasch

    def _create_content(self):
        title_area = []
        title = Paragraph(
            text='Strategy Metadata Overview',
            css_classes=['panel-title'])
        title_area.append(row([title], width_policy='min'))
        if self._client:
            btn_refresh = Button(label='Refresh', width_policy='min')
            btn_refresh.on_click(self._on_update_metadata_info)
            title_area.append(Spacer())
            title_area.append(row([btn_refresh], width_policy='min'))
        # set content in self
        return layout(
            [
                title_area,
                # initialize with info
                [self._get_metadata_info()]
            ],
            sizing_mode='stretch_width')

    def _get_panel(self):

0 Source : ui.py
with Apache License 2.0
from IntelLabs

def _create_header(train_dropdown, inference_dropdown, text_status) -> layouts.Row:
    """Utility function for creating and styling the header row in the UI layout."""

    architect_logo = Div(
        text='  <  a href="https://intellabs.github.io/nlp-architect">  < img border="0" '
        'src="style/nlp_architect.jpg" width="200"> < /a> by Intel® AI Lab',
        style={
            "margin-left": "500px",
            "margin-top": "20px",
            "font-size": "110%",
            "text-align": "center",
        },
    )
    css_link = Div(
        text=" < link rel='stylesheet' type='text/css' href='style/lexicon_manager.css'>",
        style={"font-size": "0%"},
    )

    js_script = Div(text=" < input type='file' id='inputOS' hidden='true'>")

    title = Div(
        text="ABSApp",
        style={
            "font-size": "300%",
            "color": "royalblue",
            "font-weight": "bold",
            "margin-left": "500px",
        },
    )

    return row(
        column(
            row(children=[train_dropdown, lexicons_dropdown, inference_dropdown], width=500),
            row(text_status),
        ),
        css_link,
        js_script,
        widgetbox(title, width=900, height=84),
        widgetbox(architect_logo, width=400, height=84),
    )


def empty_table(*headers):

0 Source : edit.py
with GNU General Public License v3.0
from j-brady

    def setup_plot(self):
        """" code to setup the bokeh plots """
        #  make bokeh figure
        tools = [
            "tap",
            "box_zoom",
            "lasso_select",
            "box_select",
            "wheel_zoom",
            "pan",
            "reset",
        ]
        self.p = figure(
            x_range=(self.peakipy_data.f2_ppm_0, self.peakipy_data.f2_ppm_1),
            y_range=(self.peakipy_data.f1_ppm_0, self.peakipy_data.f1_ppm_1),
            x_axis_label=f"{self.peakipy_data.f2_label} - ppm",
            y_axis_label=f"{self.peakipy_data.f1_label} - ppm",
            tools=tools,
            active_drag="pan",
            active_scroll="wheel_zoom",
            active_tap=None,
        )
        if not self.thres:
            self.thres = threshold_otsu(self.peakipy_data.data[0])
        self.contour_start = self.thres  # contour level start value
        self.contour_num = 20  # number of contour levels
        self.contour_factor = 1.20  # scaling factor between contour levels
        cl = self.contour_start * self.contour_factor ** np.arange(self.contour_num)
        if len(cl) > 1 and np.min(np.diff(cl))   <  = 0.0:
            print(f"Setting contour levels to np.abs({cl})")
            cl = np.abs(cl)
        self.extent = (
            self.peakipy_data.f2_ppm_0,
            self.peakipy_data.f2_ppm_1,
            self.peakipy_data.f1_ppm_0,
            self.peakipy_data.f1_ppm_1,
        )
        self.spec_source = get_contour_data(
            self.peakipy_data.data[0], cl, extent=self.extent, cmap=viridis
        )
        #  negative contours
        self.spec_source_neg = get_contour_data(
            self.peakipy_data.data[0] * -1.0, cl, extent=self.extent, cmap=autumn
        )
        self.p.multi_line(
            xs="xs", ys="ys", line_color="line_color", source=self.spec_source
        )
        self.p.multi_line(
            xs="xs", ys="ys", line_color="line_color", source=self.spec_source_neg
        )
        # contour_num = Slider(title="contour number", value=20, start=1, end=50,step=1)
        # contour_start = Slider(title="contour start", value=100000, start=1000, end=10000000,step=1000)
        self.contour_start = TextInput(
            value="%.2e" % self.thres, title="Contour level:", width=100
        )
        # contour_factor = Slider(title="contour factor", value=1.20, start=1., end=2.,step=0.05)
        self.contour_start.on_change("value", self.update_contour)
        # for w in [contour_num,contour_start,contour_factor]:
        #    w.on_change("value",update_contour)

        #  plot mask outlines
        el = self.p.ellipse(
            x="X_PPM",
            y="Y_PPM",
            width="X_DIAMETER_PPM",
            height="Y_DIAMETER_PPM",
            source=self.source,
            fill_color="color",
            fill_alpha=0.1,
            line_dash="dotted",
            line_color="red",
        )

        self.p.add_tools(
            HoverTool(
                tooltips=[
                    ("Index", "$index"),
                    ("Assignment", "@ASS"),
                    ("CLUSTID", "@CLUSTID"),
                    ("RADII", "@X_RADIUS_PPM{0.000}, @Y_RADIUS_PPM{0.000}"),
                    (
                        f"{self.peakipy_data.f2_label},{self.peakipy_data.f1_label}",
                        "$x{0.000} ppm, $y{0.000} ppm",
                    ),
                ],
                mode="mouse",
                # add renderers
                renderers=[el],
            )
        )
        # p.toolbar.active_scroll = "auto"
        # draw border around spectrum area
        spec_border_x = [
            self.peakipy_data.f2_ppm_min,
            self.peakipy_data.f2_ppm_min,
            self.peakipy_data.f2_ppm_max,
            self.peakipy_data.f2_ppm_max,
            self.peakipy_data.f2_ppm_min,
        ]

        spec_border_y = [
            self.peakipy_data.f1_ppm_min,
            self.peakipy_data.f1_ppm_max,
            self.peakipy_data.f1_ppm_max,
            self.peakipy_data.f1_ppm_min,
            self.peakipy_data.f1_ppm_min,
        ]

        self.p.line(
            spec_border_x,
            spec_border_y,
            line_width=1,
            line_color="black",
            line_dash="dotted",
            line_alpha=0.5,
        )
        self.p.circle(x="X_PPM", y="Y_PPM", source=self.source, color="color")
        # plot cluster numbers
        self.p.text(
            x="X_PPM",
            y="Y_PPM",
            text="CLUSTID",
            text_color="color",
            source=self.source,
            text_font_size="8pt",
            text_font_style="bold",
        )

        self.p.on_event(DoubleTap, self.peak_pick_callback)

        self.pos_neg_contour_dic = {0: "pos/neg", 1: "pos", 2: "neg"}
        self.pos_neg_contour_radiobutton = RadioButtonGroup(
            labels=[
                self.pos_neg_contour_dic[i] for i in self.pos_neg_contour_dic.keys()
            ],
            active=0,
        )
        self.pos_neg_contour_radiobutton.on_change("active", self.update_contour)
        # call fit_peaks
        self.fit_button = Button(label="Fit selected cluster", button_type="primary")
        # lineshape selection
        self.lineshapes = {
            0: "PV",
            1: "V",
            2: "G",
            3: "L",
            4: "PV_PV",
            # 5: "PV_L",
            # 6: "PV_G",
            # 7: "G_L",
        }
        self.radio_button_group = RadioButtonGroup(
            labels=[self.lineshapes[i] for i in self.lineshapes.keys()], active=0
        )
        self.ls_div = Div(
            text="""Choose lineshape you wish to fit. This can be Voigt (V), pseudo-Voigt (PV), Gaussian (G), Lorentzian (L).
            PV_PV fits a PV lineshape with independent "fraction" parameters for the direct and indirect dimensions"""
        )
        self.clust_div = Div(
            text="""If you want to adjust how the peaks are automatically clustered then try changing the
                width/diameter/height (integer values) of the structuring element used during the binary dilation step
                (you can also remove it by selecting 'None'). Increasing the size of the structuring element will cause
                peaks to be more readily incorporated into clusters. Be sure to save your peak list before doing this as
                any manual edits will be lost."""
        )
        self.intro_div = Div(
            text=""" < h2>peakipy - interactive fit adjustment  < /h2> 
            """
        )

        self.doc_link = Div(
            text=" < h3> < a href='https://j-brady.github.io/peakipy/build/usage/instructions.html', target='_blank'> ℹ️ click here for documentation < /a> < /h3>"
        )
        self.fit_reports = ""
        self.fit_reports_div = Div(text="", height=400, style={"overflow": "scroll"})
        # Plane selection
        self.select_planes_list = [
            f"{i}"
            for i in range(self.peakipy_data.data.shape[self.peakipy_data.planes])
        ]
        self.select_plane = Select(
            title="Select plane:",
            value=self.select_planes_list[0],
            options=self.select_planes_list,
        )
        self.select_planes_dic = {
            f"{i}": i
            for i in range(self.peakipy_data.data.shape[self.peakipy_data.planes])
        }
        self.select_plane.on_change("value", self.update_contour)

        self.checkbox_group = CheckboxGroup(
            labels=["fit current plane only"], active=[]
        )

        #  not sure this is needed
        selected_df = self.peakipy_data.df.copy()

        self.fit_button.on_event(ButtonClick, self.fit_selected)

        columns = [
            TableColumn(field="ASS", title="Assignment"),
            TableColumn(field="CLUSTID", title="Cluster", editor=IntEditor()),
            TableColumn(
                field="X_PPM",
                title=f"{self.peakipy_data.f2_label}",
                editor=NumberEditor(step=0.0001),
                formatter=NumberFormatter(format="0.0000"),
            ),
            TableColumn(
                field="Y_PPM",
                title=f"{self.peakipy_data.f1_label}",
                editor=NumberEditor(step=0.0001),
                formatter=NumberFormatter(format="0.0000"),
            ),
            TableColumn(
                field="X_RADIUS_PPM",
                title=f"{self.peakipy_data.f2_label} radius (ppm)",
                editor=NumberEditor(step=0.0001),
                formatter=NumberFormatter(format="0.0000"),
            ),
            TableColumn(
                field="Y_RADIUS_PPM",
                title=f"{self.peakipy_data.f1_label} radius (ppm)",
                editor=NumberEditor(step=0.0001),
                formatter=NumberFormatter(format="0.0000"),
            ),
            TableColumn(
                field="XW_HZ",
                title=f"{self.peakipy_data.f2_label} LW (Hz)",
                editor=NumberEditor(step=0.01),
                formatter=NumberFormatter(format="0.00"),
            ),
            TableColumn(
                field="YW_HZ",
                title=f"{self.peakipy_data.f1_label} LW (Hz)",
                editor=NumberEditor(step=0.01),
                formatter=NumberFormatter(format="0.00"),
            ),
            TableColumn(
                field="VOL", title="Volume", formatter=NumberFormatter(format="0.0")
            ),
            TableColumn(
                field="include",
                title="Include",
                editor=SelectEditor(options=["yes", "no"]),
            ),
            TableColumn(field="MEMCNT", title="MEMCNT", editor=IntEditor()),
        ]

        self.data_table = DataTable(
            source=self.source, columns=columns, editable=True, fit_columns=True
        )

        # callback for adding
        # source.selected.on_change('indices', callback)
        self.source.selected.on_change("indices", self.select_callback)

        # Document layout
        fitting_controls = column(
            row(
                column(self.slider_X_RADIUS, self.slider_Y_RADIUS),
                column(
                    row(
                        widgetbox(self.contour_start, self.pos_neg_contour_radiobutton)
                    ),
                    widgetbox(self.fit_button),
                ),
            ),
            row(
                column(widgetbox(self.ls_div), widgetbox(self.radio_button_group)),
                column(widgetbox(self.select_plane), widgetbox(self.checkbox_group)),
            ),
        )

        # reclustering tab
        self.struct_el = Select(
            title="Structuring element:",
            value="disk",
            options=["square", "disk", "rectangle", "None", "mask_method"],
            width=100,
        )
        self.struct_el_size = TextInput(
            value="3",
            title="Size(width/radius or width,height for rectangle):",
            width=100,
        )

        self.recluster = Button(label="Re-cluster", button_type="warning")
        self.recluster.on_event(ButtonClick, self.recluster_peaks)

        # edit_fits tabs
        fitting_layout = fitting_controls
        log_layout = self.fit_reports_div
        recluster_layout = row(
            self.clust_div,
            column(
                self.contour_start, self.struct_el, self.struct_el_size, self.recluster
            ),
        )
        save_layout = column(self.savefilename, self.button, self.exit_button)

        fitting_tab = Panel(child=fitting_layout, title="Peak fitting")
        log_tab = Panel(child=log_layout, title="Log")
        recluster_tab = Panel(child=recluster_layout, title="Re-cluster peaks")
        save_tab = Panel(child=save_layout, title="Save edited peaklist")
        self.tabs = Tabs(
            tabs=[fitting_tab, log_tab, recluster_tab, save_tab],
            sizing_mode="scale_both",
        )

    def recluster_peaks(self, event):

0 Source : viz.py
with Apache License 2.0
from llSourcell

    def __init__(self, n_nodes):
        self.i = 0
        kps = [crypto_sign_keypair() for _ in range(n_nodes)]
        stake = {kp[0]: 1 for kp in kps}

        network = {}
        self.nodes = [Node(kp, network, n_nodes, stake) for kp in kps]
        for n in self.nodes:
            network[n.pk] = n.ask_sync
        self.ids = {kp[0]: i for i, kp in enumerate(kps)}

        self.main_its = [n.main() for n in self.nodes]
        for m in self.main_its:
            next(m)

        def toggle():
            if play.label == '► Play':
                play.label = '❚❚ Pause'
                curdoc().add_periodic_callback(self.animate, 50)
            else:
                play.label = '► Play'
                curdoc().remove_periodic_callback(self.animate)

        play = Button(label='► Play', width=60)
        play.on_click(toggle)

        def sel_node(new):
            self.active = new
            node = self.nodes[new]
            self.tbd = {}
            self.tr_src.data, self.links_src.data = self.extract_data(
                    node, bfs((node.head,), lambda u: node.hg[u].p), 0)
            for u, j in tuple(self.tbd.items()):
                self.tr_src.data['line_alpha'][j] = 1 if node.famous.get(u) else 0
                if u in node.idx:
                    self.tr_src.data['round_color'][j] = idx_color(node.idx[u])
                self.tr_src.data['idx'][j] = node.idx.get(u)
                if u in node.idx and u in node.famous:
                    del self.tbd[u]
                    print('updated')
            self.tr_src.trigger('data', None, self.tr_src.data)

        selector = RadioButtonGroup(
                labels=['Node %i' % i for i in range(n_nodes)], active=0,
                name='Node to inspect')
        selector.on_click(sel_node)

        plot = figure(
                plot_height=700, plot_width=900, y_range=(0, 30),
                tools=[PanTool(dimensions=['height']),
                       HoverTool(tooltips=[
                           ('round', '@round'), ('hash', '@hash'),
                           ('timestamp', '@time'), ('payload', '@payload'),
                           ('number', '@idx')])])
        plot.xgrid.grid_line_color = None
        plot.xaxis.minor_tick_line_color = None
        plot.ygrid.grid_line_color = None
        plot.yaxis.minor_tick_line_color = None

        self.links_src = ColumnDataSource(data={'x0': [], 'y0': [], 'x1': [],
                                                'y1': [], 'width': []})
        #self.links_rend = plot.add_layout(
        #        Arrow(end=NormalHead(fill_color='black'), x_start='x0', y_start='y0', x_end='x1',
        #        y_end='y1', source=self.links_src))
        self.links_rend = plot.segment(color='#777777',
                x0='x0', y0='y0', x1='x1',
                y1='y1', source=self.links_src, line_width='width')

        self.tr_src = ColumnDataSource(
                data={'x': [], 'y': [], 'round_color': [], 'idx': [],
                    'line_alpha': [], 'round': [], 'hash': [], 'payload': [],
                    'time': []})

        self.tr_rend = plot.circle(x='x', y='y', size=20, color='round_color',
                                   line_alpha='line_alpha', source=self.tr_src, line_width=5)

        sel_node(0)
        curdoc().add_root(row([widgetbox(play, selector, width=300), plot], sizing_mode='fixed'))

    def extract_data(self, node, trs, i):

See More Examples