Ejemplo n.º 1
0
race_table = raceTable(data_race, t_source, t_last_update)

tableData = dict(
    race=['Asian', 'Black', 'Cdph-other', 'Latino', 'White', 'Other'],
    confirmed_cases_percent=race_table.confirm,
    deaths_percent=race_table.death,
    population_percent=race_table.percent,
    last_update=race_table.last_update,
    source=race_table.source)
source2 = ColumnDataSource1(tableData)
columns = [
    TableColumn(field="race", title="Race"),
    TableColumn(field='confirmed_cases_percent',
                title="Confirmed_cases_percent"),
    TableColumn(field="deaths_percent", title="Deaths_percent"),
    TableColumn(field="population_percent", title="Population_percent")
]
# TableColumn(field="last_update",title="Last_update"),TableColumn(field="source",title="Source")
table = DataTable(source=source2, columns=columns, width=width, height=500)
date_picker = DatePicker(title='Select a date',
                         value="2020-10-26",
                         min_date="2020-05-01",
                         max_date="2020-11-02")
date_picker.on_change('value', update1)
pre3 = TextAreaInput(value='Source: ' + t_source + '\nLast update: ' +
                     t_last_update,
                     rows=3)
layout = column(pre, dropdown_state, textbox, p, pre2, date_picker, pre3,
                table)
curdoc().add_root(layout)
Ejemplo n.º 2
0
        str(round(0, 4)) + '%',
        round(0, 4),
        round(0, 4),
        str(round(0, 4)) + '%',
        round(0, 4)
    ])
stats_source = ColumnDataSource(stats_data)

stats_columns = [
    TableColumn(field="metrics", title="metrics"),
    TableColumn(field="selected", title="selection"),
    TableColumn(field="benchmark", title="index"),
]
stats_table = DataTable(source=stats_source,
                        columns=stats_columns,
                        width=400,
                        height=300,
                        index_position=None)

plot = figure(plot_width=1100,
              plot_height=1000,
              x_range=(-1.0, 1.0),
              y_range=(-1.0, 1.0),
              toolbar_location="below",
              background_fill_color="#fafafa")
plot.axis.visible = False
plot.xgrid.visible = False
plot.ygrid.visible = False

labels = LabelSet(x='x',
                  y='y',
Ejemplo n.º 3
0
        d5['end_datetime_str'].push(  d6['end_datetime_str'][draw_index]);
        d5['start_datetime_dt'].push( d6['start_datetime_dt'][draw_index]);
        d5['end_datetime_dt'].push(   d6['end_datetime_dt'][draw_index]);

        source_sx_draw_highlight.data = d5;
        source_sx_draw_highlight.change.emit();
        
    """)
silder_draw_index.js_on_change('value', callback)



columns = [
        TableColumn(field="start_datetime_dt", title="start_datetime_dt"),
        TableColumn(field="sx_value", title="sx_value")
          ]
data_table = DataTable(source=source_sx_persistency, columns=columns, width=400, height=280)

controles=Column(silder_draw_index, slider_sx, sizing_mode='stretch_width')
p_sx_layout  = Column(p_sx,  controles, margin=( 8 , 8 , 8 , 8 ))

toggles = Row(toggle1, toggle2)
p_crd_layout = Column(p_crd, toggles, slider_alpha_Value, data_table, margin=( 8 , 8 , 8 , 8 ))

#最後の部分
plots = Row(p_sx_layout, p_crd_layout)
#output_file("MOGE.html")
show(plots)
curdoc().add_root(plots)

Ejemplo n.º 4
0
    def modify_doc(doc):
        im_num = [
            0,
        ]

        images = [
            np.pad(im, ((max_height - im.shape[0], 0),
                        (0, max_width - im.shape[1])), 'constant')
            for im in ims
        ]

        plot, source = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]],
                                                       return_im=True)
        source = source.data_source

        booleans = [
            True if frame == im_num[-1] else False
            for frame in point_labels.data['frame']
        ]
        view = CDSView(source=point_labels, filters=[BooleanFilter(booleans)])

        renderer = plot.scatter(x='x',
                                y='y',
                                source=point_labels,
                                view=view,
                                color=point_tool_color,
                                size=point_size)
        columns = [
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field='frame', title='frame')
        ]
        table = DataTable(source=point_labels,
                          columns=columns,
                          editable=True,
                          height=table_height)
        draw_tool = PointDrawTool(renderers=[renderer], empty_value=im_num[-1])
        plot.add_tools(draw_tool)
        plot.add_tools(CrosshairTool(line_alpha=crosshair_tool_alpha))
        plot.toolbar.active_tap = draw_tool

        def update_image(new_ind):
            _, data = bootcamp_utils.viz.bokeh_imshow(images[new_ind],
                                                      return_im=True)
            data = data.data_source
            source.data = data.data

        def callback_point_view(event):
            booleans = [
                True if frame == im_num[-1] else False
                for frame in point_labels.data['frame']
            ]
            view = CDSView(source=point_labels,
                           filters=[BooleanFilter(booleans)])
            renderer.view = view

        def callback_slider(attr, old, new):
            update_image(new)

            im_num.append(int(new))
            draw_tool.empty_value = im_num[-1]
            callback_point_view('tap')

        def callback_button(direction):
            new = im_num[-1] + direction
            if (((len(images) - 1) < new and direction == 1)
                    or (new == -1 and direction == -1)):
                return None
            update_image(new)

            im_num.append(new)
            draw_tool.empty_value = im_num[-1]
            callback_point_view('tap')

        slider = Slider(start=0,
                        end=len(images),
                        value=0,
                        step=1,
                        title="Frame Number")
        slider.on_change('value', callback_slider)

        button_back = Button(label='back', button_type="success")
        button_back.on_click(partial(callback_button, direction=-1))

        button_forward = Button(label='forward', button_type="success")
        button_forward.on_click(partial(callback_button, direction=1))

        plot.on_event('tap', callback_point_view)

        doc.add_root(
            column(row(slider), plot, row(button_back, button_forward), table))
Ejemplo n.º 5
0
    def setup_pop_table(self, **kwargs):
        """
        ???+ note "Set up a bokeh `DataTable` widget for monitoring subset data populations."

            | Param      | Type   | Description                  |
            | :--------- | :----- | :--------------------------- |
            | `**kwargs` |        | forwarded to the `DataTable` |
        """
        subsets = [
            *self.__class__.SCRATCH_SUBSETS,
            *self.__class__.PUBLIC_SUBSETS,
            *self.__class__.PRIVATE_SUBSETS,
        ]
        pop_source = ColumnDataSource(dict())
        pop_columns = [
            TableColumn(field="label", title="label"),
            *[
                TableColumn(field=f"count_{_subset}", title=_subset)
                for _subset in subsets
            ],
            TableColumn(
                field="color",
                title="color",
                formatter=HTMLTemplateFormatter(template=COLOR_GLYPH_TEMPLATE),
            ),
        ]
        self.pop_table = DataTable(source=pop_source,
                                   columns=pop_columns,
                                   **kwargs)

        def update_population():
            """
            Callback function.
            """
            # make sure that the label coding is correct
            self.setup_label_coding()

            # re-compute label population
            eff_labels = [module_config.ABSTAIN_DECODED, *self.classes]
            color_dict = auto_label_color(self.classes)
            eff_colors = [color_dict[_label] for _label in eff_labels]

            pop_data = dict(color=eff_colors, label=eff_labels)
            for _subset in subsets:
                _subpop = self.dfs[_subset]["label"].value_counts()
                pop_data[f"count_{_subset}"] = [
                    _subpop.get(_label, 0) for _label in eff_labels
                ]

            # push results to bokeh data source
            pop_source.data = pop_data

            self._good(
                f"Population updater: latest population with {len(self.classes)} classes."
            )

        update_population()
        self.dedup_trigger.on_click(update_population)

        # store the callback so that it can be referenced by other methods
        self._callback_update_population = update_population
Ejemplo n.º 6
0
        'Haar': haar_coef,
        'Comp. Haar': comp_haar_coef,
        'Comp. Signal': comp_y
    }
    error_label.text = "Error: {:2.5f}".format(
        np.square(np.subtract(y, comp_y)).mean())


min_cutoff_slider.on_change('value', update_data)
max_cutoff_slider.on_change('value', update_data)
signal_select.on_change('value', update_data)
start_slider.on_change('value', update_data)
end_slider.on_change('value', update_data)
start_reconstruct.on_change('value', update_data)
stop_reconstruct.on_change('value', update_data)

data_table = DataTable(source=source,
                       columns=[
                           TableColumn(field="X", title="X"),
                           TableColumn(field="Signal", title="Signal"),
                           TableColumn(field="Haar", title='Haar'),
                           TableColumn(field='Comp. Haar', title="Comp. Haar"),
                           TableColumn(field="Comp. Signal",
                                       title="Comp. Signal")
                       ])
curdoc().add_root(
    column(plot, signal_select, row(min_cutoff_slider, max_cutoff_slider),
           row(start_reconstruct, stop_reconstruct),
           row(start_slider, end_slider)))
curdoc().title = "1D Haar Compression"
Ejemplo n.º 7
0
def test_table() -> None:
    from bokeh.models import DataTable
    test_table = DataTable()
    return test_table
Ejemplo n.º 8
0
p3.ygrid.grid_line_color = None
p3.border_fill_color = "whitesmoke"
p3.min_border_left = 5

#******************************************************************************************************************************
## bokeh create datatable from pandas dataframe tab2
#******************************************************************************************************************************

columns = [
    TableColumn(field="Species", title="Species"),
    TableColumn(field="sepal length (cm)", title="Sepal_Length"),
    TableColumn(field="sepal width (cm)", title="Sepal_Width"),
]
table = DataTable(source=source,
                  columns=columns,
                  height=800,
                  width=600,
                  name="table",
                  sizing_mode="scale_both")

# tab building for the bokeh server
n1 = column(row(select, text_input), row(p1, p2, p3), row(p))

n2 = column(row(select, text_input), row(table))

tab1 = Panel(
    child=n1,
    title="Main Report",
)
tab2 = Panel(child=n2, title="Detail Report")

tabs = Tabs(tabs=[tab1, tab2])
Ejemplo n.º 9
0
                title="Transmission",
                editor=SelectEditor(options=sorted(mpg["trans"].unique()))),
    TableColumn(field="drv",
                title="Drive",
                editor=SelectEditor(options=sorted(mpg["drv"].unique()))),
    TableColumn(field="class",
                title="Class",
                editor=SelectEditor(options=sorted(mpg["class"].unique()))),
    TableColumn(field="cty",
                title="City MPG",
                editor=IntEditor()),
    TableColumn(field="hwy",
                title="Highway MPG",
                editor=IntEditor()),
]
table = DataTable(source=source, columns=columns, editable=True, width=800)

widgets = Column(children=[
    Row(children=[
        Column(children=[
            click_button, disabled_button, toggle, dropdown, dropdown_split,
            checkbox_group, radio_group,
            checkbox_button_group, radio_button_group,
            Row(children=[checkbox_button_group_vertical, radio_button_group_vertical]),
        ]),
        Column(children=[
            text_input, autocomplete_input, text_area,
            select, multi_select, multi_choice,
            slider, range_slider, date_slider, date_range_slider,
            spinner, color_picker, date_picker,
            paragraph, div, pre_text,
Ejemplo n.º 10
0
                title='Agentless passive'),
    TableColumn(field='nrOfMatches_PassivesWordu46ByPassive',
                title='By passive'),
    TableColumn(field='nrOfMatches_PronounWordu46ItPronoun', title='Pronoun'),
    TableColumn(
        field='nrOfMatches_ThatComplementWordu46ThatAdjectiveComplement',
        title='That adjective'),
    TableColumn(field='nrOfMatches_ThatComplementWordu46ThatVerbComplement',
                title='That verb'),
    TableColumn(field='nrOfMatches_ThatComplementWordu46ThatVerbComplement',
                title='That verb'),
    TableColumn(field='nrOfMatches_WHClauseWordu46WH_Clause', title='Clause')
]

# Create table with the columns above
data_table = DataTable(source=source, columns=columns, width=1000, height=700)
# ------------------------------------------------------------------------------

# Define columns for the statistical values table
stats_columns = [
    TableColumn(field='value', title='value'),
    TableColumn(field='mins', title='min'),
    TableColumn(field='maxs', title='max'),
    TableColumn(field='means', title='mean'),
    TableColumn(field='std', title='standard deviation')
]

# Create data table for the statistical values
stats_table = DataTable(source=data,
                        columns=stats_columns,
                        width=300,
Ejemplo n.º 11
0
def player_displacement_value_tab(events_df, metrica_attack, metrica_defence,
                                  bokeh_attack, bokeh_defence, shirt_mapping,
                                  match_list):

    import metrica_to_bokeh as mtb
    import Metrica_PitchControl as mpc
    import pitch_value_model as pvm
    from bokeh.models import ColumnDataSource, Select, TextInput, Panel, Div, Button, DataTable, TableColumn, Paragraph
    from bokeh.events import ButtonClick
    from bokeh.layouts import row, column, WidgetBox

    import numpy as np
    from scipy import interpolate

    def make_dataset(play,
                     event_frame,
                     metrica_attack,
                     metrica_defence,
                     bokeh_attack,
                     bokeh_defence,
                     field_dimen=(
                         106.,
                         68.,
                     ),
                     new_grid_size=500):

        params = mpc.default_model_params(3)

        event = events_df.loc[[(play, int(event_frame))]]
        tracking_frame = event['Start Frame'][0]

        att_frame = bokeh_attack.loc[(play, tracking_frame)]
        att_player_frame = att_frame[att_frame['player'] != "ball"]
        att_player_frame['Shirt Number'] = att_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        def_frame = bokeh_defence.loc[(play, tracking_frame)]
        def_player_frame = def_frame[def_frame['player'] != "ball"]
        def_player_frame['Shirt Number'] = def_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        ball_frame = att_frame[att_frame['player'] == "ball"]

        PPCF, xgrid, ygrid = pvm.lastrow_generate_pitch_control_for_event(
            play,
            event_frame,
            events_df,
            metrica_attack,
            metrica_defence,
            params,
            field_dimen=(
                106.,
                68.,
            ),
            n_grid_cells_x=50)
        print('calculating..')
        PT = pvm.generate_relevance_at_event(play, event_frame, events_df,
                                             PPCF, params)
        print('calculating..')
        PS = pvm.generate_scoring_opportunity(field_dimen=(
            106.,
            68.,
        ),
                                              n_grid_cells_x=50)
        print('calculating..')
        PPV = pvm.generate_pitch_value(PPCF,
                                       PT,
                                       PS,
                                       field_dimen=(
                                           106.,
                                           68.,
                                       ),
                                       n_grid_cells_x=50)
        print('calculating..')
        RPPV = pvm.generate_relative_pitch_value(play, event_frame, events_df,
                                                 metrica_attack, PPV, xgrid,
                                                 ygrid)

        xgrid_new = np.linspace(-field_dimen[0] / 2., field_dimen[0] / 2.,
                                new_grid_size)
        ygrid_new = np.linspace(-field_dimen[1] / 2., field_dimen[1] / 2.,
                                new_grid_size)

        PPCF_int = interpolate.interp2d(xgrid, ygrid, PPCF, kind='cubic')
        PPCF_new = PPCF_int(xgrid_new, ygrid_new)
        PPCF_dict = dict(image=[PPCF_new],
                         x=[xgrid.min()],
                         y=[ygrid.min()],
                         dw=[field_dimen[0]],
                         dh=[field_dimen[1]])
        PT_int = interpolate.interp2d(xgrid, ygrid, PT, kind='cubic')
        PT_new = PT_int(xgrid_new, ygrid_new)
        PT_dict = dict(image=[PT_new],
                       x=[xgrid.min()],
                       y=[ygrid.min()],
                       dw=[field_dimen[0]],
                       dh=[field_dimen[1]])
        PS_int = interpolate.interp2d(xgrid, ygrid, PS, kind='cubic')
        PS_new = PS_int(xgrid_new, ygrid_new)
        PS_dict = dict(image=[PS_new],
                       x=[xgrid.min()],
                       y=[ygrid.min()],
                       dw=[field_dimen[0]],
                       dh=[field_dimen[1]])
        PPV_int = interpolate.interp2d(xgrid, ygrid, PPV, kind='cubic')
        PPV_new = PPV_int(xgrid_new, ygrid_new)
        PPV_dict = dict(image=[PPV_new],
                        x=[xgrid.min()],
                        y=[ygrid.min()],
                        dw=[field_dimen[0]],
                        dh=[field_dimen[1]])
        RPPV_int = interpolate.interp2d(xgrid, ygrid, RPPV, kind='cubic')
        RPPV_new = RPPV_int(xgrid_new, ygrid_new)
        RPPV_dict = dict(image=[RPPV_new],
                         x=[xgrid.min()],
                         y=[ygrid.min()],
                         dw=[field_dimen[0]],
                         dh=[field_dimen[1]])

        event_src = ColumnDataSource(event)
        att_src = ColumnDataSource(att_player_frame)
        def_src = ColumnDataSource(def_player_frame)
        ball_src = ColumnDataSource(ball_frame)
        PPCF_src = ColumnDataSource(PPCF_dict)
        PT_src = ColumnDataSource(PT_dict)
        PS_src = ColumnDataSource(PS_dict)
        PPV_src = ColumnDataSource(PPV_dict)
        RPPV_src = ColumnDataSource(RPPV_dict)

        return event_src, att_src, def_src, ball_src, PPCF_src, PT_src, PS_src, PPV_src, RPPV_src, xgrid, ygrid

    def make_plot(event_src,
                  att_src,
                  def_src,
                  ball_src,
                  surface_src,
                  bokeh_attack,
                  bokeh_defence,
                  xgrid,
                  ygrid,
                  field_dimen=(
                      106.,
                      68.,
                  ),
                  new_grid_size=500,
                  point_click=False):

        surface = mtb.plot_bokeh_surface_at_event(event_src,
                                                  att_src,
                                                  def_src,
                                                  ball_src,
                                                  surface_src,
                                                  bokeh_attack,
                                                  bokeh_defence,
                                                  xgrid,
                                                  ygrid,
                                                  point_click=True)

        return surface

    def update(attr, old, new):
        match_selection = match_select.value
        event_selection = event_select.value

        new_og_event_src, new_og_att_src, new_og_def_src, new_og_ball_src, new_og_PPCF_src, new_og_PT_src, new_og_PS_src, new_og_PPV_src, new_og_RPPV_src, xgrid, ygrid = make_dataset(
            match_selection, event_selection, metrica_attack, metrica_defence,
            bokeh_attack, bokeh_defence)
        print('calculating..')
        og_att_src.data.update(new_og_att_src.data)
        og_def_src.data.update(new_og_def_src.data)
        og_ball_src.data.update(new_og_ball_src.data)
        og_PPCF_src.data.update(new_og_PPCF_src.data)
        og_PT_src.data.update(new_og_PT_src.data)
        og_PT_src.data.update(new_og_PS_src.data)
        og_PPV_src.data.update(new_og_PPV_src.data)
        og_RPPV_src.data.update(new_og_RPPV_src.data)

        new_event_src, new_att_src, new_def_src, new_ball_src, new_PPCF_src, new_PT_src, new_PS_src, new_PPV_src, new_RPPV_src, xgrid, ygrid = make_dataset(
            match_selection, event_selection, metrica_attack, metrica_defence,
            bokeh_attack, bokeh_defence)
        print('calculating..')
        event_src.data.update(new_event_src.data)
        att_src.data.update(new_att_src.data)
        def_src.data.update(new_def_src.data)
        ball_src.data.update(new_ball_src.data)
        PPCF_src.data.update(new_PPCF_src.data)
        PT_src.data.update(new_PT_src.data)
        PT_src.data.update(new_PS_src.data)
        PPV_src.data.update(new_PPV_src.data)
        RPPV_src.data.update(new_RPPV_src.data)

    match_select = Select(title="Select Match:",
                          value=match_list[0],
                          options=match_list)
    match_select.on_change('value', update)

    event_select = TextInput(title="Event:", value="0")
    event_select.on_change('value', update)

    player_select = TextInput(title="Index of Player Moved:", value="")

    team_select = Select(title="Team of Player Moved:",
                         value="attack",
                         options=["attack", "defence"])

    def recalculate(event):
        match_selection = match_select.value
        event_selection = event_select.value
        player_selection = int(player_select.value)
        team_selection = team_select.value

        if team_selection == 'attack':

            player = att_src.data['player'][player_selection]
            shirt = att_src.data['Shirt Number'][player_selection]
            # attack
            selected_att_x = att_src.data['x'][player_selection]
            selected_att_y = att_src.data['y'][player_selection]
            og_selected_att_x = og_att_src.data['x'][player_selection]
            og_selected_att_y = og_att_src.data['y'][player_selection]
            x_displacement = selected_att_x - og_selected_att_x
            y_displacement = selected_att_y - og_selected_att_y

            metrica_attack_new = mtb.player_displacement(
                match_selection, event_selection, events_df, metrica_attack,
                metrica_defence, 'attack', player, x_displacement,
                y_displacement)
            bokeh_attack_new = mtb.tracking_to_bokeh_format(metrica_attack_new)

            new_event_src, new_att_src, new_def_src, new_ball_src, new_PPCF_src, new_PT_src, new_PS_src, new_PPV_src, new_RPPV_src, xgrid, ygrid = make_dataset(
                match_selection, event_selection, metrica_attack_new,
                metrica_defence, bokeh_attack_new, bokeh_defence)
            print('calculating..')
            event_src.data.update(new_event_src.data)
            att_src.data.update(new_att_src.data)
            def_src.data.update(new_def_src.data)
            ball_src.data.update(new_ball_src.data)
            PPCF_src.data.update(new_PPCF_src.data)
            PT_src.data.update(new_PT_src.data)
            PT_src.data.update(new_PS_src.data)
            PPV_src.data.update(new_PPV_src.data)
            RPPV_src.data.update(new_RPPV_src.data)

            pitch_value = make_plot(event_src,
                                    att_src,
                                    def_src,
                                    ball_src,
                                    PPV_src,
                                    bokeh_attack,
                                    bokeh_defence,
                                    xgrid,
                                    ygrid,
                                    field_dimen=(
                                        106.,
                                        68.,
                                    ),
                                    new_grid_size=500)
            relative_pitch_value = make_plot(event_src,
                                             att_src,
                                             def_src,
                                             ball_src,
                                             RPPV_src,
                                             bokeh_attack,
                                             bokeh_defence,
                                             xgrid,
                                             ygrid,
                                             field_dimen=(
                                                 106.,
                                                 68.,
                                             ),
                                             new_grid_size=500)

        elif team_selection == 'defence':

            player = def_src.data['player'][player_selection]
            shirt = def_src.data['Shirt Number'][player_selection]

            # defence
            selected_def_x = def_src.data['x'][player_selection]
            selected_def_y = def_src.data['y'][player_selection]
            og_selected_def_x = og_def_src.data['x'][player_selection]
            og_selected_def_y = og_def_src.data['y'][player_selection]
            x_displacement = selected_def_x - og_selected_def_x
            y_displacement = selected_def_y - og_selected_def_y

            metrica_defence_new = mtb.player_displacement(
                match_selection, event_selection, events_df, metrica_attack,
                metrica_defence, 'defence', player, x_displacement,
                y_displacement)
            bokeh_defence_new = mtb.tracking_to_bokeh_format(
                metrica_defence_new)

            new_event_src, new_att_src, new_def_src, new_ball_src, new_PPCF_src, new_PT_src, new_PS_src, new_PPV_src, new_RPPV_src, xgrid, ygrid = make_dataset(
                match_selection, event_selection, metrica_attack,
                metrica_defence_new, bokeh_attack, bokeh_defence_new)
            print('calculating..')
            event_src.data.update(new_event_src.data)
            att_src.data.update(new_att_src.data)
            def_src.data.update(new_def_src.data)
            ball_src.data.update(new_ball_src.data)
            PPCF_src.data.update(new_PPCF_src.data)
            PT_src.data.update(new_PT_src.data)
            PT_src.data.update(new_PS_src.data)
            PPV_src.data.update(new_PPV_src.data)
            RPPV_src.data.update(new_RPPV_src.data)

            pitch_value = make_plot(event_src,
                                    att_src,
                                    def_src,
                                    ball_src,
                                    PPV_src,
                                    bokeh_attack,
                                    bokeh_defence,
                                    xgrid,
                                    ygrid,
                                    field_dimen=(
                                        106.,
                                        68.,
                                    ),
                                    new_grid_size=500)
            relative_pitch_value = make_plot(event_src,
                                             att_src,
                                             def_src,
                                             ball_src,
                                             RPPV_src,
                                             bokeh_attack,
                                             bokeh_defence,
                                             xgrid,
                                             ygrid,
                                             field_dimen=(
                                                 106.,
                                                 68.,
                                             ),
                                             new_grid_size=500)

    recalculate_button = Button(label="Re-Calculate Pitch Value")
    recalculate_button.on_event(ButtonClick, recalculate)

    # Initial match to plot
    print('create initial tab2')
    play = 'Bayern 0 - [1] Liverpool'
    event_frame = 0

    og_event_src, og_att_src, og_def_src, og_ball_src, og_PPCF_src, og_PT_src, og_PS_src, og_PPV_src, og_RPPV_src, xgrid, ygrid = make_dataset(
        play, event_frame, metrica_attack, metrica_defence, bokeh_attack,
        bokeh_defence)
    print('calculating..')
    event_src, att_src, def_src, ball_src, PPCF_src, PT_src, PS_src, PPV_src, RPPV_src, xgrid, ygrid = make_dataset(
        play, event_frame, metrica_attack, metrica_defence, bokeh_attack,
        bokeh_defence)
    print('calculating..')
    pitch_value = make_plot(event_src,
                            att_src,
                            def_src,
                            ball_src,
                            PPV_src,
                            bokeh_attack,
                            bokeh_defence,
                            xgrid,
                            ygrid,
                            field_dimen=(
                                106.,
                                68.,
                            ),
                            new_grid_size=500)
    pitch_value.title.text = "Pitch Value"
    pitch_value.title.text_font_size = "20px"
    print('calculating..')
    relative_pitch_value = make_plot(event_src,
                                     att_src,
                                     def_src,
                                     ball_src,
                                     RPPV_src,
                                     bokeh_attack,
                                     bokeh_defence,
                                     xgrid,
                                     ygrid,
                                     field_dimen=(
                                         106.,
                                         68.,
                                     ),
                                     new_grid_size=500)
    relative_pitch_value.title.text = "Relative Pitch Value"
    relative_pitch_value.title.text_font_size = "20px"

    # Create data tables for viewing movements
    columns = [
        TableColumn(field="Shirt Number", title="Shirt Number"),
        TableColumn(field="player", title="player"),
        TableColumn(field="x", title="x"),
        TableColumn(field="y", title="y"),
    ]
    att_table = DataTable(source=att_src,
                          columns=columns,
                          width=400,
                          height=280,
                          editable=True)
    att_title = Div(text="Red Team")
    def_table = DataTable(source=def_src,
                          columns=columns,
                          width=400,
                          height=280,
                          editable=True)
    def_title = Div(text="Blue Team")

    # Paragraph for instructions and disclaimers
    disclaimer = Paragraph(
        text=
        "*** Disclaimer - You can click the PointDrawTool in Pitch Value for each team to move a single player at a time. If you wish to re-calculate the Pitch Value based on the new location, you must add in a new player (click anywhere on the pitch with the PointDrawTool) and then remove them again (click on them to highlight only them, then press backspace). This is necessary to do for each team everytime you want to re-calculate Pitch Values. Any advice on correcting this would be appreciated! ***"
    )
    instructions = Paragraph(
        text=
        "Select a match from the dropdown list below. Then enter an event number. If a player is moved, enter their Index to the respective table and select their team (Red = attack, Blue = defence). Pitch Value is the same as in 'Events - Pitch Value'. Relative Pitch Value highlights areas that will increase Pitch Value compared to the starting position. Again can turn off some HoverTools if necessary."
    )
    #notes = column(disclaimer, instructions)

    # Layout setup
    control = WidgetBox(
        column(match_select, event_select, player_select, team_select,
               recalculate_button))
    plots = column(pitch_value, relative_pitch_value)
    tables = column(column(att_title, att_table), column(def_title, def_table))
    layout = column(disclaimer, instructions,
                    row(plots, column(control, tables)))

    tab3 = Panel(child=layout, title='Player Displacement - Pitch Value')

    return tab3
Ejemplo n.º 12
0
for c in sfdf.columns:
    data[c] =  list(sfdf[c])

source = ColumnDataSource(sfdf)

columns = []
for c in sfdf.columns:
    columns.append(TableColumn(field = c, title = c))
cities = pd.read_csv('cities.csv')
    
quantityinputs = [Paragraph(text = 'Enter Quantities for Order', height = 13)]
for x in range(10):
    quantityinputs.append(TextInput(height = cellheight, width = 100))

search_table = DataTable(source=source, columns=columns, width=400, height=280)
def search():
    global search_table
    global sfdf
    global note
    params = {}
    params['title'] = search_params[1].value
    params['authors'] = search_params[2].value
    params['isbn'] = search_params[3].value
    params['genere'] = search_params[4].value
    print(params)
    query = 'SELECT * FROM storefront'
    b = True
    for k in params.keys():
        if(params[k] != ''):
            if b:
Ejemplo n.º 13
0
def plot_chart_bokeh(processed, dataCollection, keys, outputfilename):
    stock = processed['data']

    # Define constants
    W_PLOT = 1000
    H_PLOT = 360
    TOOLS = 'pan,wheel_zoom,reset'

    VBAR_WIDTH = 1 * 12 * 60 * 60 * 1000  # one day in ms
    RED = Category20[7][6]
    GREEN = Category20[5][4]

    BLUE = Category20[3][0]
    BLUE_LIGHT = Category20[3][1]

    ORANGE = Category20[3][2]
    PURPLE = Category20[9][8]
    BROWN = Category20[11][10]

    # ==========================================================================
    # ===================       PLOT CANDLE STICK GRAPH     ====================
    # ==========================================================================
    p1 = figure(plot_width=W_PLOT,
                plot_height=H_PLOT,
                tools=TOOLS,
                toolbar_location='right')

    inc = stock.data['Close'] >= stock.data['Open']
    dec = stock.data['Open'] > stock.data['Close']
    # limit = stock.data['ZC_d2/dt2'] > 10
    # limit = stock.data['ZC_d/dt'] > 0

    # view_inc = CDSView(source=stock, filters=[BooleanFilter(inc), BooleanFilter(limit)])
    # view_dec = CDSView(source=stock, filters=[BooleanFilter(dec), BooleanFilter(limit)])
    view_inc = CDSView(source=stock, filters=[BooleanFilter(inc)])
    view_dec = CDSView(source=stock, filters=[BooleanFilter(dec)])

    # # map dataframe indices to date strings and use as label overrides
    p1.y_range.start = 0.9 * min(stock.data['Low'])
    p1.y_range.end = 1.1 * max(stock.data['High'])
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=GREEN,
               source=stock,
               view=view_inc)
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=RED,
               source=stock,
               view=view_dec)

    vb1 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='forestgreen',
                  fill_alpha=1,
                  line_color='forestgreen',
                  source=stock,
                  view=view_inc,
                  name="price")
    vb2 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='orangered',
                  fill_alpha=1,
                  line_color='orangered',
                  source=stock,
                  view=view_dec,
                  name="price")

    # Bollinger band plot
    patch1 = p1.varea(x='Date',
                      y1='lowerband',
                      y2='upperband',
                      source=stock,
                      fill_alpha=0.05,
                      fill_color='dodgerblue')
    patch_line1 = p1.line(x='Date',
                          y='lowerband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)
    patch_line2 = p1.line(x='Date',
                          y='middleband',
                          source=stock,
                          line_color='grey',
                          line_alpha=0.8,
                          line_dash='dotdash')
    patch_line3 = p1.line(x='Date',
                          y='upperband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)

    # ZC Line plot
    zc_7 = p1.line(x='Date',
                   y='ma7',
                   source=stock,
                   line_color='crimson',
                   line_alpha=0.4)
    zc_26 = p1.line(x='Date',
                    y='ma26',
                    source=stock,
                    line_color='darkslateblue',
                    line_alpha=0.4)

    # # Resistance plots
    # r1 = p1.line(x='Date', y='r1', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.6)
    # r2 = p1.line(x='Date', y='r2', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.8)
    # r3 = p1.line(x='Date', y='r3', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=1.0)

    # # Support plots
    # s1 = p1.line(x='Date', y='s1', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.6)
    # s2 = p1.line(x='Date', y='s2', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.8)
    # s3 = p1.line(x='Date', y='s3', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=1.0)

    # Extrema plots
    # minima = p1.inverted_triangle(x='Date', y='minima', source=stock, size=5, color="goldenrod", alpha=0.5)
    # maxima = p1.triangle(x='Date', y='maxima', source=stock, size=5, color="teal", alpha=0.5)
    # minima = p1.circle(
    #     x='Date', y='minima', source=stock, size=10,
    #     fill_color="grey", hover_fill_color="firebrick",
    #     fill_alpha=0.2, hover_alpha=0.8, hover_line_color="white")
    # maxima = p1.triangle(
    #     x='Date', y='maxima', source=stock,
    #     size=10, fill_color="grey", fill_alpha=0.2,
    #     hover_fill_color="firebrick", hover_alpha=0.8, hover_line_color="white")

    # Volume plot
    # Setting the second y axis range name and range
    p1.extra_y_ranges = {
        "vol_axis": Range1d(start=0, end=max(stock.data['Volume']) * 4)
    }
    # Adding the second axis to the plot.
    p1.add_layout(LinearAxis(y_range_name="vol_axis", visible=False), 'right')
    vol_inc = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=GREEN,
                      fill_alpha=0.1,
                      line_color=GREEN,
                      line_alpha=0.2,
                      source=stock,
                      view=view_inc,
                      y_range_name="vol_axis")
    vol_dec = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=RED,
                      fill_alpha=0.1,
                      line_color=RED,
                      line_alpha=0.2,
                      source=stock,
                      view=view_dec,
                      y_range_name="vol_axis")

    legend = Legend(items=[
        LegendItem(
            label="All",
            renderers=[
                patch1,
                patch_line1,
                patch_line2,
                patch_line3,
                vol_inc,
                vol_dec,
                zc_7,
                zc_26,
                #    s1, s2, s3,r1, r2, r3,
                #    minima, maxima
            ],
            index=0),
        LegendItem(label="BB",
                   renderers=[patch1, patch_line1, patch_line2, patch_line3],
                   index=1),
        LegendItem(label="Volume", renderers=[vol_inc, vol_dec], index=2),
        LegendItem(label="ZC", renderers=[zc_7, zc_26], index=3),
        LegendItem(label="MA7", renderers=[zc_7], index=4),
        LegendItem(label="MA26", renderers=[zc_26], index=5),
        # LegendItem(label="Support", renderers=[s1, s2, s3], index=6),
        # LegendItem(label="Resistance", renderers=[r1, r2, r3], index=7),
        # LegendItem(label="Extrema", renderers=[minima, maxima], index=8)
    ])
    p1.add_layout(legend)
    p1.legend.location = "top_left"
    p1.legend.border_line_alpha = 0
    p1.legend.background_fill_alpha = 0
    p1.legend.click_policy = "hide"
    p1.legend.orientation = "horizontal"
    # p1.add_layout(Title(text="Stock price", align="left"), "left")

    p1.yaxis.axis_label = 'Stock price'
    p1.yaxis.formatter = NumeralTickFormatter(format='0.00')
    p1.x_range.range_padding = 0.05
    p1.xaxis.ticker.desired_num_ticks = 40
    p1.xaxis.major_label_orientation = 3.14 / 4
    p1.xaxis.visible = False
    p1.xgrid.grid_line_color = None
    p1.ygrid.grid_line_color = None

    # Select specific tool for the plot
    p1.add_tools(
        HoverTool(
            tooltips=[("Datetime", "@Date{%Y-%m-%d}"),
                      ("Open", "@Open{0,0.00}"), ("Close", "@Close{0,0.00}"),
                      ("Volume", "@Volume{(0.00 a)}")],
            formatters={"@Date": 'datetime'},

            # display a tooltip whenever the cursor is vertically in line with a glyph
            mode='vline',
            renderers=[vb1, vb2]))

    # ==========================================================================
    # ===================      PLOT STOCH / RSI GRAPH          =================
    # ==========================================================================
    p2 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 4),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime')  # , y_range=(-20, 120)

    stoch_k = p2.line(x='Date',
                      y='slowk',
                      source=stock,
                      line_color='royalblue',
                      alpha=0.8,
                      muted_alpha=0.2)
    stoch_d = p2.line(x='Date',
                      y='slowd',
                      source=stock,
                      line_color='tomato',
                      alpha=0.8,
                      muted_alpha=0.2)
    rsi = p2.line(x='Date',
                  y='rsi',
                  source=stock,
                  line_color='gray',
                  alpha=0.8,
                  muted_alpha=0.2)
    mid_box = BoxAnnotation(bottom=20,
                            top=80,
                            fill_alpha=0.2,
                            fill_color='palegreen',
                            line_color='lightcoral',
                            line_alpha=0.4,
                            line_dash='dashed')
    # candle = p2.line(x='Date', y='candle', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # mid_box = BoxAnnotation(bottom=-300, top=300, fill_alpha=0.2, fill_color='palegreen', line_color='lightcoral', line_alpha=0.4, line_dash='dashed')
    legend = Legend(items=[
        LegendItem(label="Stoch", renderers=[stoch_k, stoch_d], index=0),
        LegendItem(label="RSI", renderers=[rsi], index=1)
        # LegendItem(label="Candle", renderers=[candle], index=1)
    ])
    p2.add_layout(legend)
    p2.add_layout(mid_box)
    # p2.add_layout(lower)
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p2.add_layout(zero)
    p2.yaxis.axis_label = 'Stochastic / RSI'
    p2.x_range.range_padding = 0.05
    # p2.toolbar.autohide = True
    p2.xaxis.visible = False
    p2.legend.location = "top_left"
    p2.legend.border_line_alpha = 0
    p2.legend.background_fill_alpha = 0
    p2.legend.click_policy = "mute"
    p2.xgrid.grid_line_color = None
    p2.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================                 Plot MACD         ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['macd_hist'], key=abs))
    y2_limit = abs(max(stock.data['macd_d/dt'], key=abs))
    p3 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 2.5),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))
    mapper = LinearColorMapper(palette=Viridis256)
    macd_line = p3.line(x='Date',
                        y='macd_hist',
                        source=stock,
                        line_color='darkgreen',
                        alpha=0.8,
                        muted_alpha=0.2)
    # macd_hist = p3.vbar_stack(['macd'], x='Date', source=stock, width=int(VBAR_WIDTH * 2), fill_color={'field':'macd', 'transform': mapper})

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p3.add_layout(zero)
    p3.add_layout(mid_box)

    # Setting the second y axis range name and range
    p3.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p3.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')
    macd_v = p3.line(x='Date',
                     y='macd_d/dt',
                     source=stock,
                     line_color='dodgerblue',
                     line_dash='solid',
                     alpha=0.8,
                     muted_alpha=0.2,
                     y_range_name="extra_y_axis")
    macd_acc = p3.line(x='Date',
                       y='macd_d2/dt2',
                       source=stock,
                       line_color='tomato',
                       line_dash='dotdash',
                       alpha=0.8,
                       muted_alpha=0.2,
                       y_range_name="extra_y_axis")

    legend = Legend(items=[
        LegendItem(label="MACD", renderers=[macd_line], index=0),
        LegendItem(label="MACD-v", renderers=[macd_v], index=1),
        LegendItem(label="MACD-a", renderers=[macd_acc], index=2)
    ])
    p3.add_layout(legend)
    p3.legend.location = "top_left"
    p3.legend.border_line_alpha = 0
    p3.legend.background_fill_alpha = 0
    p3.legend.click_policy = "mute"
    p3.legend.orientation = "horizontal"
    # p3.add_layout(Title(text="MACD", align="center"), "left")
    p3.yaxis.axis_label = 'MACD'
    p3.x_range.range_padding = 0.05
    p3.xaxis.visible = False
    p3.xaxis.ticker.desired_num_ticks = 40
    p3.xaxis.major_label_orientation = 3.14 / 4
    p3.toolbar.autohide = True
    p3.xgrid.grid_line_color = None
    p3.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================         Plot ZC        ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['ZC'], key=abs))
    y2_limit = abs(max(stock.data['ZC_d/dt'], key=abs))
    # y_limit = abs(max(stock.data['slowk'], key=abs))
    # y2_limit = abs(max(stock.data['slowk_d/dt'], key=abs))
    p4 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 3),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))

    p4.xaxis.formatter = DatetimeTickFormatter(
        hours=["%d.%m.%y"],
        days=["%d.%m.%y"],
        months=["%d.%m.%y"],
        years=["%d.%m.%y"],
    )
    # macd_v = p4.line(x='Date', y='macd_d/dt', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # macd_acc = p4.line(x='Date', y='macd_d2/dt2', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # ad = p4.line(x='Date', y='ck_AD', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # adosc = p4.line(x='Date', y='ck_ADOSC', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # obv = p4.line(x='Date', y='OBV', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)

    # Setting the second y axis range name and range
    p4.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p4.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')

    zc = p4.line(x='Date',
                 y='ZC',
                 source=stock,
                 line_color='darkgreen',
                 alpha=0.8,
                 muted_alpha=0.2)
    zc_v = p4.line(x='Date',
                   y='ZC_d/dt',
                   source=stock,
                   line_color='dodgerblue',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    zc_a = p4.line(x='Date',
                   y='ZC_d2/dt2',
                   source=stock,
                   line_color='tomato',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    # slowk = p4.line(x='Date', y='slowk', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)
    # slowk_v = p4.line(x='Date', y='slowk_d/dt', source=stock, line_color='dodgerblue', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")
    # slowk_a = p4.line(x='Date', y='slowk_d2/dt2', source=stock, line_color='tomato', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p4.add_layout(zero)
    p4.add_layout(mid_box)
    # p4.yaxis.axis_label = 'MACD v/acc'
    legend = Legend(items=[
        LegendItem(label="ZC", renderers=[zc], index=0),
        LegendItem(label="ZC-v", renderers=[zc_v], index=1),
        LegendItem(label="ZC-a", renderers=[zc_a], index=2),
        # LegendItem(label="slowk", renderers=[slowk], index=0),
        # LegendItem(label="slowk-v", renderers=[slowk_v], index=1),
        # LegendItem(label="slowk-a", renderers=[slowk_a], index=2)
    ])
    p4.add_layout(legend)
    p4.legend.location = "top_left"
    p4.legend.border_line_alpha = 0
    p4.legend.background_fill_alpha = 0
    p4.legend.click_policy = "mute"
    p4.legend.orientation = "horizontal"
    p4.x_range.range_padding = 0.05
    p4.xaxis.ticker.desired_num_ticks = 40
    p4.xaxis.major_label_orientation = 3.14 / 4
    p4.toolbar.autohide = True
    p4.xgrid.grid_line_color = None
    p4.ygrid.grid_line_color = None

    addSpans([p1, p2, p3, p4])

    columns = [
        TableColumn(field="Date",
                    title="Date",
                    formatter=DateFormatter(format='%d.%b')),
        # TableColumn(field="Open", title="Open", formatter=NumberFormatter(format='0.00')),
        # TableColumn(field="Close", title="Close", formatter=NumberFormatter(format='0.00')),
        TableColumn(field="ZC",
                    title="ZC",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="ZC_d/dt",
                    title="ZC-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_hist",
                    title="MACD",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_d/dt",
                    title="MACD-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        # TableColumn(field="macd_d2/dt2", title="MACD-a", formatter=NumberFormatter(format='0.000')),
        TableColumn(field="stoch",
                    title="STOCH",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        TableColumn(field="stoch-v",
                    title="STOCH-v",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        # TableColumn(field="slowk_d/dt", title="slowk-v", formatter=NumberFormatter(format='0.000')),
        # TableColumn(field="slowk_d2/dt2", title="slowk-a", formatter=NumberFormatter(format='0.000')),
    ]
    data_table = DataTable(source=stock,
                           columns=columns,
                           width=int(W_PLOT / 3),
                           height=int(H_PLOT * 2.2),
                           index_position=None,
                           width_policy='min')

    # ==========================================================================
    # ===================            SELECT WIDGET          ====================
    # ==========================================================================

    callback_select_main = """
        var d0 = s0.data;
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;

        /// Iterate over keys in new data and reassign old data with new data
        for (const key of Object.keys(data)) {
            d0[key] = []
            d0[key] = data[key]
        }
        s0.change.emit()

        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = 0.9 * Math.min(...data['Low'])
        plot.y_range.end = 1.1 * Math.max(...data['High'])
        plot.extra_y_ranges['vol_axis'].have_updated_interactively = true
        plot.extra_y_ranges['vol_axis'].start  = 0
        plot.extra_y_ranges['vol_axis'].end  = Math.max(...data['Volume']) * 4
        """

    callback_select_va = """
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;
        var y_limit = Math.max.apply(null, data[param_main].map(Math.abs));
        var y_extra_limit = Math.max.apply(null, data[param_extra].map(Math.abs));
        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = -y_limit
        plot.y_range.end = y_limit
        plot.extra_y_ranges['extra_y_axis'].have_updated_interactively = true
        plot.extra_y_ranges['extra_y_axis'].start  = -y_extra_limit
        plot.extra_y_ranges['extra_y_axis'].end  = y_extra_limit
        """
    selecthandler_main = CustomJS(args={
        's0': stock,
        'dataCollection': dataCollection,
        'plot': p1
    },
                                  code=callback_select_main)
    selecthandler_p3 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p3,
        'param_main': 'macd_hist',
        'param_extra': 'macd_d/dt'
    },
                                code=callback_select_va)
    selecthandler_p4 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p4,
        'param_main': 'ZC',
        'param_extra': 'ZC_d/dt'
    },
                                code=callback_select_va)
    # selecthandler_p4 = CustomJS(args={'dataCollection':dataCollection, 'plot':p4, 'param_main': 'slowk', 'param_extra': 'slowk_d/dt'}, code = callback_select_va)
    select = Select(title="Select:", value=keys[0], options=keys)
    select.js_on_change('value', selecthandler_main)
    select.js_on_change('value', selecthandler_p3)
    select.js_on_change('value', selecthandler_p4)

    # [cleanDate(x, stock.data) for x in [p1, p2, p3, p4]]
    # show the results
    gp1 = gridplot([select, data_table],
                   ncols=1,
                   plot_width=150,
                   toolbar_options=dict(autohide=True))
    gp2 = gridplot([p1, p2, p3, p4],
                   ncols=1,
                   sizing_mode='scale_width',
                   toolbar_location='right')

    output_file(outputfilename + '.html')
    show(row(gp1, gp2))
    # show(gp2)
    return True
Ejemplo n.º 14
0
def plotHistogram(fileName,
                  initData,
                  stations,
                  dateRange,
                  bokehPlaceholderId='bokehContent'):
    data = {
        'xs': [initData['bins']],
        'ys': [initData['values']],
        'ss': [1, 2],
        'es': [3, 4]
    }  #ss and es are for test purposes we'll add  other values of the controlles e.g. age, usertype, Gender coming fetshed from initdata

    source = ColumnDataSource(data=data)
    stations.insert(0, "All")
    selectSS = Select(title="Start Station:", value="All", options=stations)
    selectES = Select(title="End Station:", value="All", options=stations)

    selectUT = Select(title="User Type:",
                      value="All",
                      options=["All", "Subscriber", "Customer"])
    selectGender = Select(title="Gender:",
                          value="All",
                          options=["All", "Male", "Female"])
    sliderAge = Slider(start=8, end=100, value=30, step=5, title="Age")

    startDP = DatePicker(title="Start Date:",
                         min_date=dateRange[0],
                         max_date=dateRange[1],
                         value=dateRange[0])
    endDP = DatePicker(title="End Date:",
                       min_date=dateRange[0],
                       max_date=dateRange[1],
                       value=dateRange[1])
    binSize = TextInput(value="15", title="Bin Size (Days):")
    AddButton = Toggle(label="Add", type="success")
    DeleteButton = Toggle(label="delete", type="success")

    columns = [
        TableColumn(field="ss", title="Start Station"),
        TableColumn(field="es", title="End Station")
    ]  # add other columns contains values of other controllers
    data_table = DataTable(source=source,
                           columns=columns,
                           width=650,
                           height=300)

    model = dict(source=source,
                 selectSS=selectSS,
                 selectES=selectES,
                 startDP=startDP,
                 endDP=endDP,
                 binSize=binSize,
                 selectUT=selectUT,
                 selectGender=selectGender,
                 sliderAge=sliderAge)
    plot = Figure(plot_width=650, plot_height=400, x_axis_type="datetime")
    plot.multi_line('xs',
                    'ys',
                    source=source,
                    line_width='width',
                    line_alpha=0.6,
                    line_color='color')

    callback = CustomJS(args=model,
                        code="""
            //alert("callback");
            var startStation = selectSS.get('value');
            var endStation = selectES.get('value');
            var startDate = startDP.get('value');
            
            if ( typeof(startDate) !== "number")
                startDate = startDate.getTime();
                
            var endDate = endDP.get('value');
            
            if ( typeof(endDate) !== "number")
                endDate = endDate.getTime();            
            
            var binSize = binSize.get('value');
            //alert(startStation + " " + endStation + " " + startDate + " " + endDate + " " + binSize);
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        var temp=[];
                        
                        for(var date in result.x) {
                            temp.push(new Date(result.x[date]));
                        }
                        
                        data['xs'].push(temp);
                        data['ys'].push(result.y);
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {ss:startStation, es:endStation, sd:startDate, ed:endDate, bs: binSize};
        url = "/histogram?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)

    AddButton.callback = callback
    #DeleteButton.on_click(callback1)
    layout1 = vform(startDP, endDP, binSize)
    layout2 = vform(plot, DeleteButton, data_table)
    layout3 = vform(selectSS, selectES, selectUT, selectGender, sliderAge,
                    AddButton)
    layout = hplot(layout1, layout2, layout3)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
Ejemplo n.º 15
0
# Data source dropdown widget
#files = [x for x in os.listdir('data') if x.split('.')[-1] == 'csv']
files = ['data.csv', 'data2.csv']
data_source_menu = Select(options=files, value='data.csv', title='Select data source:')
data_source_menu.on_change('value', on_change_data_source)

# Table widget
num_format = NumberFormatter()
num_format.format = '0.00000'
metrics_columns = [
    TableColumn(field='method', title='Source'),
    TableColumn(field='mean', title='Mean', formatter=num_format),
    TableColumn(field='sd', title='Std Dev', formatter=num_format),
    TableColumn(field='loc', title='Loc Param', formatter=num_format),
    TableColumn(field='scale', title='Scale Param', formatter=num_format),
    TableColumn(field='shape', title='Shape Param', formatter=num_format),
    TableColumn(field='aic', title='AIC', formatter=num_format),
]
metrics_table = DataTable(source=metrics_source, columns=metrics_columns, height=100)

# Text input widget
loc_val_input = TextInput(title='Specify distribution location value:', placeholder='none', value='')
loc_val_input.on_change('value', on_dist_change)

# Format app layout
widgets = widgetbox(metrics_table, dist_menu, data_source_menu, loc_val_input, width=400)
grid = gridplot([hist, cdf],
                [pp, qq],
                [widgets, None])
curdoc().add_root(grid)
Ejemplo n.º 16
0
 def make_stock_return_table_2(stock_return_table_2_source):
     columns = []
     for colnames in ['tse_industry_name','company','company_abbreviation','index_factor','yearly_return']:
         columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))
     stock_return_table_2 = DataTable(source=stock_return_table_2_source, columns=columns, height = 500)
     return (stock_return_table_2)
Ejemplo n.º 17
0
customer_widgets = Panel(child=column(widgetbox(select_cid),
                                      widgetbox(cid_filter),
                                      widgetbox(bt, height=25, width=300)),
                         title='Customer Widgets')

df_rentals = df.groupby('customer_id').agg({
    'object_data-fare': 'sum',
    'vehicle_id': 'count'
}).reset_index()
df_rentals.columns = ['customer_id', 'total_fare', 'number_of_rentals']
data_table_Columns = [
    TableColumn(field=Ci, title=Ci) for Ci in df_rentals.columns
]  # bokeh columns
data_table_source = ColumnDataSource(df_rentals)
data_table = DataTable(columns=data_table_Columns,
                       source=data_table_source,
                       width=800)  # bokeh table

download_button = Button(label="Download", button_type="success")
download_button.js_on_click(
    CustomJS(args=dict(source=data_table_source),
             code=open(join(dirname(__file__), "download.js")).read()))

data_table = Panel(child=column(row(data_table), row(download_button)),
                   title='Data Table')

main_tab = Tabs(
    tabs=[base_widgets, visibility_widgets, customer_widgets, data_table])

hovertool_widget = RadioButtonGroup(labels=["No Hover tool", "Hover tool"],
                                    active=0)
Ejemplo n.º 18
0
    def create_mcmc_fit_figures(self, run_fitting_button):
        self_ = self
        initial_fit_figure = Figure(x_axis_label='Folded time (days)',
                                    y_axis_label='Relative flux',
                                    title=f'Initial fit')
        parameters_table_columns = [
            TableColumn(field=column, title=column)
            for column in ['parameter', 'mean', 'sd', 'r_hat']
        ]
        parameters_table = DataTable(source=self.parameters_table_data_source,
                                     columns=parameters_table_columns,
                                     editable=True)
        initial_fit_data_source = self.initial_fit_data_source
        bokeh_document = self.bokeh_document

        @gen.coroutine
        def update_initial_fit_figure(fluxes, gp_pred, inds, lc_pred, map_soln,
                                      relative_times, times, x_fold):
            initial_fit_data_source.data['Time (BTJD)'] = times
            initial_fit_data_source.data['Time (days)'] = relative_times
            initial_fit_data_source.data['Folded time (days)'] = x_fold
            initial_fit_data_source.data[
                'Relative flux'] = fluxes - gp_pred - map_soln["mean"]
            initial_fit_data_source.data[
                'Fit'] = lc_pred[inds] - map_soln["mean"]
            initial_fit_data_source.data['Fit time'] = x_fold[
                inds]  # TODO: This is terrible, you should be able to line them up *afterward* to not make a duplicate time column

        @gen.coroutine
        @without_document_lock
        def fit(self, map_soln, model):
            with model:
                trace = pm.sample(
                    tune=2000,
                    draws=2000,
                    start=map_soln,
                    chains=4,
                    step=xo.get_dense_nuts_step(target_accept=0.9),
                )
            trace_summary = pm.summary(
                trace, round_to='none'
            )  # Not a typo. PyMC3 wants 'none' as a string here.
            epoch = round(
                trace_summary['mean']['Transit epoch (BTJD)'],
                3)  # Round the epoch differently, as BTJD needs more digits.
            trace_summary['mean'] = self_.round_series_to_significant_figures(
                trace_summary['mean'], 5)
            trace_summary['mean']['Transit epoch (BTJD)'] = epoch
            self.bokeh_document.add_next_tick_callback(
                partial(self.update_parameters_table, trace_summary))
            with pd.option_context('display.max_columns', None,
                                   'display.max_rows', None):
                print(trace_summary)
                print(f'Star radius: {self.star_radius}')
            # TODO: This should not happen automatically. Only after a button click.
            # scopes = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
            # credentials = Credentials.from_service_account_file(
            #     'ramjet/analysis/google_spreadsheet_credentials.json', scopes=scopes)
            # gc = gspread.authorize(credentials)
            # sh = gc.open('Ramjet transit candidates shared for vetting')
            # worksheet = sh.get_worksheet(0)
            # # Find first empty row.
            # empty_row_index = 1
            # for row_index in itertools.count(start=1):
            #     row_values = worksheet.row_values(row_index)
            #     if len(row_values) == 0:
            #         empty_row_index = row_index
            #         break
            # worksheet.update_cell(empty_row_index, 1, self_.tic_id)
            # worksheet.update_cell(empty_row_index, 2, str(self_.sectors).replace('[', '').replace(']', '')),
            # worksheet.update_cell(empty_row_index, 3, trace_summary['mean']['Transit epoch (BTJD)'])
            # worksheet.update_cell(empty_row_index, 4, trace_summary['mean']['period'])
            # worksheet.update_cell(empty_row_index, 5, trace_summary['mean']['Transit depth (relative flux)'])
            # worksheet.update_cell(empty_row_index, 6, trace_summary['mean']['Transit duration (days)'])
            # worksheet.update_cell(empty_row_index, 7, self_.star_radius)
            # worksheet.update_cell(empty_row_index, 8, trace_summary['mean']['Planet radius (solar radii)'] * self_.star_radius)

        @gen.coroutine
        @without_document_lock
        def run_fitting():
            times = self.light_curve_data_source.data['Time (BTJD)'].astype(
                np.float32)
            flux_errors = self.light_curve_data_source.data[
                'Normalized PDCSAP flux error']
            fluxes = self.light_curve_data_source.data[
                'Normalized PDCSAP flux']
            relative_times = self.light_curve_data_source.data['Time (days)']
            nan_indexes = np.union1d(
                np.argwhere(np.isnan(fluxes)),
                np.union1d(np.argwhere(np.isnan(times)),
                           np.argwhere(np.isnan(flux_errors))))
            fluxes = np.delete(fluxes, nan_indexes)
            flux_errors = np.delete(flux_errors, nan_indexes)
            times = np.delete(times, nan_indexes)
            relative_times = np.delete(relative_times, nan_indexes)
            with pm.Model() as model:
                # Stellar parameters
                mean = pm.Normal("mean", mu=0.0, sigma=10.0 * 1e-3)
                u = xo.distributions.QuadLimbDark("u")
                star_params = [mean, u]

                # Gaussian process noise model
                sigma = pm.InverseGamma("sigma",
                                        alpha=3.0,
                                        beta=2 * np.nanmedian(flux_errors))
                log_Sw4 = pm.Normal("log_Sw4", mu=0.0, sigma=10.0)
                log_w0 = pm.Normal("log_w0",
                                   mu=np.log(2 * np.pi / 10.0),
                                   sigma=10.0)
                kernel = xo.gp.terms.SHOTerm(log_Sw4=log_Sw4,
                                             log_w0=log_w0,
                                             Q=1.0 / 3)
                noise_params = [sigma, log_Sw4, log_w0]

                # Planet parameters
                log_ror = pm.Normal("log_ror",
                                    mu=0.5 * np.log(self_.depth),
                                    sigma=10.0 * 1e-3)
                ror = pm.Deterministic("ror", tt.exp(log_ror))
                depth = pm.Deterministic('Transit depth (relative flux)',
                                         tt.square(ror))
                planet_radius = pm.Deterministic('Planet radius (solar radii)',
                                                 ror * self_.star_radius)

                # Orbital parameters
                log_period = pm.Normal("log_period",
                                       mu=np.log(self_.period),
                                       sigma=1.0)
                t0 = pm.Normal('Transit epoch (BTJD)',
                               mu=self_.transit_epoch,
                               sigma=1.0)
                log_dur = pm.Normal("log_dur", mu=np.log(0.1), sigma=10.0)
                b = xo.distributions.ImpactParameter("b", ror=ror)

                period = pm.Deterministic('Transit period (days)',
                                          tt.exp(log_period))
                dur = pm.Deterministic('Transit duration (days)',
                                       tt.exp(log_dur))

                # Set up the orbit
                orbit = xo.orbits.KeplerianOrbit(period=period,
                                                 duration=dur,
                                                 t0=t0,
                                                 b=b,
                                                 r_star=self.star_radius)

                # We're going to track the implied density for reasons that will become clear later
                pm.Deterministic("rho_circ", orbit.rho_star)

                # Set up the mean transit model
                star = xo.LimbDarkLightCurve(u)

                def lc_model(t):
                    return mean + tt.sum(star.get_light_curve(
                        orbit=orbit, r=ror * self.star_radius, t=t),
                                         axis=-1)

                # Finally the GP observation model
                gp = xo.gp.GP(kernel,
                              times, (flux_errors**2) + (sigma**2),
                              mean=lc_model)
                gp.marginal("obs", observed=fluxes)

                # Double check that everything looks good - we shouldn't see any NaNs!
                print(model.check_test_point())

                # Optimize the model
                map_soln = model.test_point
                map_soln = xo.optimize(map_soln, [sigma])
                map_soln = xo.optimize(map_soln, [log_ror, b, log_dur])
                map_soln = xo.optimize(map_soln, noise_params)
                map_soln = xo.optimize(map_soln, star_params)
                map_soln = xo.optimize(map_soln)

            with model:
                gp_pred, lc_pred = xo.eval_in_model(
                    [gp.predict(), lc_model(times)], map_soln)

            x_fold = (times - map_soln['Transit epoch (BTJD)'] +
                      0.5 * map_soln['Transit period (days)']
                      ) % map_soln['Transit period (days)'] - 0.5 * map_soln[
                          'Transit period (days)']
            inds = np.argsort(x_fold)
            bokeh_document.add_next_tick_callback(
                partial(update_initial_fit_figure, fluxes, gp_pred, inds,
                        lc_pred, map_soln, relative_times, times, x_fold))

            self.bokeh_document.add_next_tick_callback(
                partial(fit, self, map_soln, model))

        run_fitting_button.on_click(run_fitting)
        self.plot_folding_colored_light_curve_source(
            initial_fit_figure,
            self.initial_fit_data_source,
            time_column_name='Folded time (days)',
            flux_column_name='Relative flux')
        initial_fit_figure.line('Fit time',
                                'Fit',
                                source=self.initial_fit_data_source,
                                color='black',
                                line_width=3)
        initial_fit_figure.sizing_mode = 'stretch_width'

        return initial_fit_figure, parameters_table
Ejemplo n.º 19
0
p3.xaxis.formatter = DatetimeTickFormatter(seconds=["%H:%M:%S"],
                                           minsec=["%H:%M:%S"],
                                           minutes=["%H:%M:%S"],
                                           hourmin=["%H:%M"],
                                           hours=["%H:%M"],
                                           days=['%d/%m'])

#creation des tableaux d'affichage
columns = [
    TableColumn(field="strdate", title="Date", width=140),
    TableColumn(field="close", title="prix", width=60)
]

data_table1 = DataTable(source=source,
                        columns=columns,
                        index_position=None,
                        width=200,
                        height=500,
                        selectable=False)

columns2 = [
    TableColumn(field="strdate", title="Date", width=130),
    TableColumn(field="prix", title="Prix", width=50),
    TableColumn(field="decision", title="Decision", width=50),
    TableColumn(field="stocks", title="Qte Stocks", width=50)
]
data_table2 = DataTable(source=sourceTrans,
                        columns=columns2,
                        index_position=None,
                        width=280,
                        height=300,
                        selectable=False)
Ejemplo n.º 20
0
#no way to read this from imax only shows up in set up packet
select_cycles = Select(title = "Cycles", value ="1", options = [str(i) for i in range(1,6)])
def select_cycles_handler(attr, old, new):
  settings['cycles'] = new
select_cycles.on_change('value', select_cycles_handler)

text_input = TextInput(value="Enter run information", title="Run Info::")
def text_input_handler(attr, old, new):
  settings['run_text'] = new
text_input.on_change("value", text_input_handler)

textsource = ColumnDataSource(data=dict(time = [],msg = []))
columns = [ 
  TableColumn(field="time", title="Time"), 
  TableColumn(field="msg", title="Msg", width = 600)]
data_table = DataTable(source=textsource, columns=columns, width=600) 

button_save = Button(label="Save Run", button_type = 'warning')
def button_save_handler():
  global read_data
  print('button save worked')
  run_modes= {'bat_type':settings['bat_type'], 'chrg_type':settings['chrg_type'], 'nominal_mah':settings['nominal_mah'], 
              'DC_or_CD':settings['DC_or_CD'], 'cycles':settings['cycles'], 'cells':settings['cells'], 'run_text':settings['run_text']}
  excel_out = imax_0.write_excel_file(run_modes, settings['final_read'], read_data, settings['settings_dict'])
  msg = 'Data saved to: ' + excel_out
  print(msg)
  text_update(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), msg)     
button_save.on_click(button_save_handler)

def text_update(t, msg):
  global data_table
Ejemplo n.º 21
0
    def modify_doc(doc):
        im_num = [
            0,
        ]

        images = [
            np.pad(im, ((max_height - im.shape[0], 0),
                        (0, max_width - im.shape[1])), 'constant')
            for im in ims
        ]

        plot, source = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]],
                                                       return_im=True)
        source = source.data_source

        columns = [
            TableColumn(field='type', title='type'),
            TableColumn(field='frame', title='frame')
        ]
        table = DataTable(source=frame_labels,
                          columns=columns,
                          editable=True,
                          height=200)
        plot.add_tools(CrosshairTool(line_alpha=0.5))

        def callback(attr, old, new):
            im_num.append(int(new))
            temp_plot, data = bootcamp_utils.viz.bokeh_imshow(images[int(new)],
                                                              return_im=True)
            data = data.data_source
            source.data = data.data
            plot.x_range.end = temp_plot.x_range.end
            #plot.plot_width = temp_plot.plot_width
            #layout.children[1] = plot

        def callback_button(direction):
            if (((len(images) - 2) < im_num[-1] and direction == 1)
                    or (im_num[-1] == 0 and direction == -1)):
                return None
            _, data = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1] +
                                                             direction],
                                                      return_im=True)
            im_num.append(im_num[-1] + direction)
            data = data.data_source
            source.data = data.data
            callback_point_view('tap')

        def callback_label_button(value):
            new_data = {'type': [value], 'frame': [im_num[-1]]}
            frame_labels.stream(new_data)

            if (len(images) - 2) < im_num[-1]:
                return None
            _, data = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1] + 1],
                                                      return_im=True)
            im_num.append(im_num[-1] + 1)
            data = data.data_source
            source.data = data.data

        slider = Slider(start=0,
                        end=len(images) - 1,
                        value=0,
                        step=1,
                        title="Frame Number")
        slider.on_change('value', callback)

        button_back = Button(label='back', button_type="success")
        button_back.on_click(partial(callback_button, direction=-1))

        button_forward = Button(label='forward', button_type="success")
        button_forward.on_click(partial(callback_button, direction=1))

        label_buttons = [
            Button(label=value, button_type='success')
            for value in button_values
        ]
        [
            button.on_click(partial(callback_label_button, value=value))
            for button, value in zip(label_buttons, button_values)
        ]

        #for a grid layout of the buttons, we need to pad the list with an empty spot if the button count is not even
        if not np.isclose(len(label_buttons) % 2, 0):
            label_buttons.append(Button(label=''))
        buttons = np.reshape(label_buttons, (-1, 2))
        buttons = buttons.tolist()

        layout_list = [[slider], [plot], [button_back, button_forward]]
        [layout_list.append(button) for button in buttons]
        layout_list.append([table])

        doc.add_root(layout(layout_list))
Ejemplo n.º 22
0
def process_data_samples__tabular(options,
                                  name,
                                  data,
                                  data_types,
                                  type_categories,
                                  title,
                                  with_column_title_rotation=True):
    """
    Create a tabular panel of the data & types

    Args:
        options:
        data: a dictionary of (key, values)
        data_types: a dictionary of (key, type) indicating special type of ``key``
        title: the title of the panel to be displayed

    Returns:
        a panel
    """
    image_style = """
                img
                { 
                    height:%dpx; 
                    width:%dpx;
                } 
                """ % (options.image_size, options.image_size)

    template = f"""
                <div>
                <style>
                {image_style}
                </style>
                <img
                    src=<%= value %>
                ></img>
                </div>
                """

    with_images = False
    columns = []
    for key in data.keys():
        type = data_types.get(key)
        if type is not None and 'BLOB_IMAGE' in type:
            with_images = True
            c = TableColumn(field=key,
                            title=key,
                            formatter=HTMLTemplateFormatter(template=template))
        else:
            type_category = type_categories[key]
            table_kargs = {}
            if type_category == DataCategory.Continuous:
                table_kargs['formatter'] = NumberFormatter(format='0,0[.000]')

            c = TableColumn(field=key, title=key, **table_kargs)
        columns.append(c)

    # filter out data
    filtered_data = filter_large_data(options, data)
    data_source = ColumnDataSource(filtered_data)

    if with_column_title_rotation:
        # custom CSS to slightly rotate the column header
        # and draw text outside their respective columns
        # to improve readability. TODO That could be improved
        div = Div(text=f"""
        <style>
        .trw_reporting_table_{name} .slick-header-column {{
                background-color: transparent;
                background-image: none !important;
                transform: 
                    rotate(-10deg)
              }}
    
        .bk-root .slick-header-column.ui-state-default {{
            height: 40px;
            overflow: visible;
            vertical-align: bottom;
            line-height: 4.4;
        }}
        </style>
        """)
        div.visible = False  # hide the div to avoid position issues
    else:
        div = Div()

    row_height = options.font_size
    if with_images:
        row_height = options.image_size
    data_table = DataTable(
        source=data_source,
        columns=columns,
        row_height=row_height,
        #fit_columns=True,
        css_classes=[f"trw_reporting_table_{name}"])

    return Panel(child=column(data_table, div, sizing_mode='stretch_both'),
                 title=title), data_table
Ejemplo n.º 23
0
ra_box = VBox(ra_input,width=150,height=50)
dec_input = TextInput(value="", title="Declination:",width=120)
dec_box = VBox(dec_input,width=150,height=50)
ra_format = RadioButtonGroup(labels=["hours","degrees"],active=0,width=220)
clearbtn = Button(label='clear',width=80)
clearbtn.on_click(clearfields)
search_button = Button(label='Search and Download Nearest Object',width=300)
search_button.on_click(search)

#Initialize data source and plot
source,cols = get_dataset(targets[target])
plot = make_plot(source, title="PTF light curve for " + target)

#Initialize table
datacolumns = []
for field in cols:
    datacolumns.append(TableColumn(field=field,title=field,width=150))
data_table = DataTable(source=source, columns=datacolumns, width=800, height=300, 
                       fit_columns=False, selectable=True)

#Set up layout
datacontrols = column(target_select,row(prevtarg,nexttarg))
coords_in = row(ra_box,dec_box,width=300)
search_in = column(targ_input,coords_in,row(ra_format,clearbtn),search_button)

sep = Div(text="",width=100)
header = row(div,sep,search_in)

curdoc().add_root(column(header,datacontrols, plot, data_table))
curdoc().title = "PTF Viewer"
def create():
    doc = curdoc()
    det_data = {}
    cami_meta = {}

    def proposal_textinput_callback(_attr, _old, new):
        nonlocal cami_meta
        proposal = new.strip()
        for zebra_proposals_path in pyzebra.ZEBRA_PROPOSALS_PATHS:
            proposal_path = os.path.join(zebra_proposals_path, proposal)
            if os.path.isdir(proposal_path):
                # found it
                break
        else:
            raise ValueError(f"Can not find data for proposal '{proposal}'.")

        file_list = []
        for file in os.listdir(proposal_path):
            if file.endswith(".hdf"):
                file_list.append((os.path.join(proposal_path, file), file))
        file_select.options = file_list

        cami_meta = {}

    proposal_textinput = TextInput(title="Proposal number:", width=210)
    proposal_textinput.on_change("value", proposal_textinput_callback)

    def upload_button_callback(_attr, _old, new):
        nonlocal cami_meta
        with io.StringIO(base64.b64decode(new).decode()) as file:
            cami_meta = pyzebra.parse_h5meta(file)
            file_list = cami_meta["filelist"]
            file_select.options = [(entry, os.path.basename(entry))
                                   for entry in file_list]

    upload_div = Div(text="or upload .cami file:", margin=(5, 5, 0, 5))
    upload_button = FileInput(accept=".cami", width=200)
    upload_button.on_change("value", upload_button_callback)

    def update_image(index=None):
        if index is None:
            index = index_spinner.value

        current_image = det_data["data"][index]
        proj_v_line_source.data.update(x=np.arange(0, IMAGE_W) + 0.5,
                                       y=np.mean(current_image, axis=0))
        proj_h_line_source.data.update(x=np.mean(current_image, axis=1),
                                       y=np.arange(0, IMAGE_H) + 0.5)

        image_source.data.update(
            h=[np.zeros((1, 1))],
            k=[np.zeros((1, 1))],
            l=[np.zeros((1, 1))],
        )
        image_source.data.update(image=[current_image])

        if main_auto_checkbox.active:
            im_min = np.min(current_image)
            im_max = np.max(current_image)

            display_min_spinner.value = im_min
            display_max_spinner.value = im_max

            image_glyph.color_mapper.low = im_min
            image_glyph.color_mapper.high = im_max

        if "mf" in det_data:
            metadata_table_source.data.update(mf=[det_data["mf"][index]])
        else:
            metadata_table_source.data.update(mf=[None])

        if "temp" in det_data:
            metadata_table_source.data.update(temp=[det_data["temp"][index]])
        else:
            metadata_table_source.data.update(temp=[None])

        gamma, nu = calculate_pol(det_data, index)
        omega = np.ones((IMAGE_H, IMAGE_W)) * det_data["omega"][index]
        image_source.data.update(gamma=[gamma], nu=[nu], omega=[omega])

    def update_overview_plot():
        h5_data = det_data["data"]
        n_im, n_y, n_x = h5_data.shape
        overview_x = np.mean(h5_data, axis=1)
        overview_y = np.mean(h5_data, axis=2)

        overview_plot_x_image_source.data.update(image=[overview_x],
                                                 dw=[n_x],
                                                 dh=[n_im])
        overview_plot_y_image_source.data.update(image=[overview_y],
                                                 dw=[n_y],
                                                 dh=[n_im])

        if proj_auto_checkbox.active:
            im_min = min(np.min(overview_x), np.min(overview_y))
            im_max = max(np.max(overview_x), np.max(overview_y))

            proj_display_min_spinner.value = im_min
            proj_display_max_spinner.value = im_max

            overview_plot_x_image_glyph.color_mapper.low = im_min
            overview_plot_y_image_glyph.color_mapper.low = im_min
            overview_plot_x_image_glyph.color_mapper.high = im_max
            overview_plot_y_image_glyph.color_mapper.high = im_max

        frame_range.start = 0
        frame_range.end = n_im
        frame_range.reset_start = 0
        frame_range.reset_end = n_im
        frame_range.bounds = (0, n_im)

        scan_motor = det_data["scan_motor"]
        overview_plot_y.axis[1].axis_label = f"Scanning motor, {scan_motor}"

        var = det_data[scan_motor]
        var_start = var[0]
        var_end = var[-1] + (var[-1] - var[0]) / (n_im - 1)

        scanning_motor_range.start = var_start
        scanning_motor_range.end = var_end
        scanning_motor_range.reset_start = var_start
        scanning_motor_range.reset_end = var_end
        # handle both, ascending and descending sequences
        scanning_motor_range.bounds = (min(var_start,
                                           var_end), max(var_start, var_end))

    def file_select_callback(_attr, old, new):
        nonlocal det_data
        if not new:
            # skip empty selections
            return

        # Avoid selection of multiple indicies (via Shift+Click or Ctrl+Click)
        if len(new) > 1:
            # drop selection to the previous one
            file_select.value = old
            return

        if len(old) > 1:
            # skip unnecessary update caused by selection drop
            return

        det_data = pyzebra.read_detector_data(new[0])

        if cami_meta and "crystal" in cami_meta:
            det_data["ub"] = cami_meta["crystal"]["UB"]

        index_spinner.value = 0
        index_spinner.high = det_data["data"].shape[0] - 1
        index_slider.end = det_data["data"].shape[0] - 1

        zebra_mode = det_data["zebra_mode"]
        if zebra_mode == "nb":
            metadata_table_source.data.update(geom=["normal beam"])
        else:  # zebra_mode == "bi"
            metadata_table_source.data.update(geom=["bisecting"])

        update_image(0)
        update_overview_plot()

    file_select = MultiSelect(title="Available .hdf files:",
                              width=210,
                              height=250)
    file_select.on_change("value", file_select_callback)

    def index_callback(_attr, _old, new):
        update_image(new)

    index_slider = Slider(value=0, start=0, end=1, show_value=False, width=400)

    index_spinner = Spinner(title="Image index:", value=0, low=0, width=100)
    index_spinner.on_change("value", index_callback)

    index_slider.js_link("value_throttled", index_spinner, "value")
    index_spinner.js_link("value", index_slider, "value")

    plot = Plot(
        x_range=Range1d(0, IMAGE_W, bounds=(0, IMAGE_W)),
        y_range=Range1d(0, IMAGE_H, bounds=(0, IMAGE_H)),
        plot_height=IMAGE_PLOT_H,
        plot_width=IMAGE_PLOT_W,
        toolbar_location="left",
    )

    # ---- tools
    plot.toolbar.logo = None

    # ---- axes
    plot.add_layout(LinearAxis(), place="above")
    plot.add_layout(LinearAxis(major_label_orientation="vertical"),
                    place="right")

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

    # ---- rgba image glyph
    image_source = ColumnDataSource(
        dict(
            image=[np.zeros((IMAGE_H, IMAGE_W), dtype="float32")],
            h=[np.zeros((1, 1))],
            k=[np.zeros((1, 1))],
            l=[np.zeros((1, 1))],
            gamma=[np.zeros((1, 1))],
            nu=[np.zeros((1, 1))],
            omega=[np.zeros((1, 1))],
            x=[0],
            y=[0],
            dw=[IMAGE_W],
            dh=[IMAGE_H],
        ))

    h_glyph = Image(image="h", x="x", y="y", dw="dw", dh="dh", global_alpha=0)
    k_glyph = Image(image="k", x="x", y="y", dw="dw", dh="dh", global_alpha=0)
    l_glyph = Image(image="l", x="x", y="y", dw="dw", dh="dh", global_alpha=0)
    gamma_glyph = Image(image="gamma",
                        x="x",
                        y="y",
                        dw="dw",
                        dh="dh",
                        global_alpha=0)
    nu_glyph = Image(image="nu",
                     x="x",
                     y="y",
                     dw="dw",
                     dh="dh",
                     global_alpha=0)
    omega_glyph = Image(image="omega",
                        x="x",
                        y="y",
                        dw="dw",
                        dh="dh",
                        global_alpha=0)

    plot.add_glyph(image_source, h_glyph)
    plot.add_glyph(image_source, k_glyph)
    plot.add_glyph(image_source, l_glyph)
    plot.add_glyph(image_source, gamma_glyph)
    plot.add_glyph(image_source, nu_glyph)
    plot.add_glyph(image_source, omega_glyph)

    image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh")
    plot.add_glyph(image_source, image_glyph, name="image_glyph")

    # ---- projections
    proj_v = Plot(
        x_range=plot.x_range,
        y_range=DataRange1d(),
        plot_height=150,
        plot_width=IMAGE_PLOT_W,
        toolbar_location=None,
    )

    proj_v.add_layout(LinearAxis(major_label_orientation="vertical"),
                      place="right")
    proj_v.add_layout(LinearAxis(major_label_text_font_size="0pt"),
                      place="below")

    proj_v.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    proj_v.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    proj_v_line_source = ColumnDataSource(dict(x=[], y=[]))
    proj_v.add_glyph(proj_v_line_source,
                     Line(x="x", y="y", line_color="steelblue"))

    proj_h = Plot(
        x_range=DataRange1d(),
        y_range=plot.y_range,
        plot_height=IMAGE_PLOT_H,
        plot_width=150,
        toolbar_location=None,
    )

    proj_h.add_layout(LinearAxis(), place="above")
    proj_h.add_layout(LinearAxis(major_label_text_font_size="0pt"),
                      place="left")

    proj_h.add_layout(Grid(dimension=0, ticker=BasicTicker()))
    proj_h.add_layout(Grid(dimension=1, ticker=BasicTicker()))

    proj_h_line_source = ColumnDataSource(dict(x=[], y=[]))
    proj_h.add_glyph(proj_h_line_source,
                     Line(x="x", y="y", line_color="steelblue"))

    # add tools
    hovertool = HoverTool(tooltips=[
        ("intensity", "@image"),
        ("gamma", "@gamma"),
        ("nu", "@nu"),
        ("omega", "@omega"),
        ("h", "@h"),
        ("k", "@k"),
        ("l", "@l"),
    ])

    box_edit_source = ColumnDataSource(dict(x=[], y=[], width=[], height=[]))
    box_edit_glyph = Rect(x="x",
                          y="y",
                          width="width",
                          height="height",
                          fill_alpha=0,
                          line_color="red")
    box_edit_renderer = plot.add_glyph(box_edit_source, box_edit_glyph)
    boxedittool = BoxEditTool(renderers=[box_edit_renderer], num_objects=1)

    def box_edit_callback(_attr, _old, new):
        if new["x"]:
            h5_data = det_data["data"]
            x_val = np.arange(h5_data.shape[0])
            left = int(np.floor(new["x"][0]))
            right = int(np.ceil(new["x"][0] + new["width"][0]))
            bottom = int(np.floor(new["y"][0]))
            top = int(np.ceil(new["y"][0] + new["height"][0]))
            y_val = np.sum(h5_data[:, bottom:top, left:right], axis=(1, 2))
        else:
            x_val = []
            y_val = []

        roi_avg_plot_line_source.data.update(x=x_val, y=y_val)

    box_edit_source.on_change("data", box_edit_callback)

    wheelzoomtool = WheelZoomTool(maintain_focus=False)
    plot.add_tools(
        PanTool(),
        BoxZoomTool(),
        wheelzoomtool,
        ResetTool(),
        hovertool,
        boxedittool,
    )
    plot.toolbar.active_scroll = wheelzoomtool

    # shared frame ranges
    frame_range = Range1d(0, 1, bounds=(0, 1))
    scanning_motor_range = Range1d(0, 1, bounds=(0, 1))

    det_x_range = Range1d(0, IMAGE_W, bounds=(0, IMAGE_W))
    overview_plot_x = Plot(
        title=Title(text="Projections on X-axis"),
        x_range=det_x_range,
        y_range=frame_range,
        extra_y_ranges={"scanning_motor": scanning_motor_range},
        plot_height=400,
        plot_width=IMAGE_PLOT_W - 3,
    )

    # ---- tools
    wheelzoomtool = WheelZoomTool(maintain_focus=False)
    overview_plot_x.toolbar.logo = None
    overview_plot_x.add_tools(
        PanTool(),
        BoxZoomTool(),
        wheelzoomtool,
        ResetTool(),
    )
    overview_plot_x.toolbar.active_scroll = wheelzoomtool

    # ---- axes
    overview_plot_x.add_layout(LinearAxis(axis_label="Coordinate X, pix"),
                               place="below")
    overview_plot_x.add_layout(LinearAxis(axis_label="Frame",
                                          major_label_orientation="vertical"),
                               place="left")

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

    # ---- rgba image glyph
    overview_plot_x_image_source = ColumnDataSource(
        dict(image=[np.zeros((1, 1), dtype="float32")],
             x=[0],
             y=[0],
             dw=[IMAGE_W],
             dh=[1]))

    overview_plot_x_image_glyph = Image(image="image",
                                        x="x",
                                        y="y",
                                        dw="dw",
                                        dh="dh")
    overview_plot_x.add_glyph(overview_plot_x_image_source,
                              overview_plot_x_image_glyph,
                              name="image_glyph")

    det_y_range = Range1d(0, IMAGE_H, bounds=(0, IMAGE_H))
    overview_plot_y = Plot(
        title=Title(text="Projections on Y-axis"),
        x_range=det_y_range,
        y_range=frame_range,
        extra_y_ranges={"scanning_motor": scanning_motor_range},
        plot_height=400,
        plot_width=IMAGE_PLOT_H + 22,
    )

    # ---- tools
    wheelzoomtool = WheelZoomTool(maintain_focus=False)
    overview_plot_y.toolbar.logo = None
    overview_plot_y.add_tools(
        PanTool(),
        BoxZoomTool(),
        wheelzoomtool,
        ResetTool(),
    )
    overview_plot_y.toolbar.active_scroll = wheelzoomtool

    # ---- axes
    overview_plot_y.add_layout(LinearAxis(axis_label="Coordinate Y, pix"),
                               place="below")
    overview_plot_y.add_layout(
        LinearAxis(
            y_range_name="scanning_motor",
            axis_label="Scanning motor",
            major_label_orientation="vertical",
        ),
        place="right",
    )

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

    # ---- rgba image glyph
    overview_plot_y_image_source = ColumnDataSource(
        dict(image=[np.zeros((1, 1), dtype="float32")],
             x=[0],
             y=[0],
             dw=[IMAGE_H],
             dh=[1]))

    overview_plot_y_image_glyph = Image(image="image",
                                        x="x",
                                        y="y",
                                        dw="dw",
                                        dh="dh")
    overview_plot_y.add_glyph(overview_plot_y_image_source,
                              overview_plot_y_image_glyph,
                              name="image_glyph")

    roi_avg_plot = Plot(
        x_range=DataRange1d(),
        y_range=DataRange1d(),
        plot_height=150,
        plot_width=IMAGE_PLOT_W,
        toolbar_location="left",
    )

    # ---- tools
    roi_avg_plot.toolbar.logo = None

    # ---- axes
    roi_avg_plot.add_layout(LinearAxis(), place="below")
    roi_avg_plot.add_layout(LinearAxis(major_label_orientation="vertical"),
                            place="left")

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

    roi_avg_plot_line_source = ColumnDataSource(dict(x=[], y=[]))
    roi_avg_plot.add_glyph(roi_avg_plot_line_source,
                           Line(x="x", y="y", line_color="steelblue"))

    cmap_dict = {
        "gray": Greys256,
        "gray_reversed": Greys256[::-1],
        "plasma": Plasma256,
        "cividis": Cividis256,
    }

    def colormap_callback(_attr, _old, new):
        image_glyph.color_mapper = LinearColorMapper(palette=cmap_dict[new])
        overview_plot_x_image_glyph.color_mapper = LinearColorMapper(
            palette=cmap_dict[new])
        overview_plot_y_image_glyph.color_mapper = LinearColorMapper(
            palette=cmap_dict[new])

    colormap = Select(title="Colormap:",
                      options=list(cmap_dict.keys()),
                      width=210)
    colormap.on_change("value", colormap_callback)
    colormap.value = "plasma"

    STEP = 1

    def main_auto_checkbox_callback(state):
        if state:
            display_min_spinner.disabled = True
            display_max_spinner.disabled = True
        else:
            display_min_spinner.disabled = False
            display_max_spinner.disabled = False

        update_image()

    main_auto_checkbox = CheckboxGroup(labels=["Main Auto Range"],
                                       active=[0],
                                       width=145,
                                       margin=[10, 5, 0, 5])
    main_auto_checkbox.on_click(main_auto_checkbox_callback)

    def display_max_spinner_callback(_attr, _old_value, new_value):
        display_min_spinner.high = new_value - STEP
        image_glyph.color_mapper.high = new_value

    display_max_spinner = Spinner(
        low=0 + STEP,
        value=1,
        step=STEP,
        disabled=bool(main_auto_checkbox.active),
        width=100,
        height=31,
    )
    display_max_spinner.on_change("value", display_max_spinner_callback)

    def display_min_spinner_callback(_attr, _old_value, new_value):
        display_max_spinner.low = new_value + STEP
        image_glyph.color_mapper.low = new_value

    display_min_spinner = Spinner(
        low=0,
        high=1 - STEP,
        value=0,
        step=STEP,
        disabled=bool(main_auto_checkbox.active),
        width=100,
        height=31,
    )
    display_min_spinner.on_change("value", display_min_spinner_callback)

    PROJ_STEP = 0.1

    def proj_auto_checkbox_callback(state):
        if state:
            proj_display_min_spinner.disabled = True
            proj_display_max_spinner.disabled = True
        else:
            proj_display_min_spinner.disabled = False
            proj_display_max_spinner.disabled = False

        update_overview_plot()

    proj_auto_checkbox = CheckboxGroup(labels=["Projections Auto Range"],
                                       active=[0],
                                       width=145,
                                       margin=[10, 5, 0, 5])
    proj_auto_checkbox.on_click(proj_auto_checkbox_callback)

    def proj_display_max_spinner_callback(_attr, _old_value, new_value):
        proj_display_min_spinner.high = new_value - PROJ_STEP
        overview_plot_x_image_glyph.color_mapper.high = new_value
        overview_plot_y_image_glyph.color_mapper.high = new_value

    proj_display_max_spinner = Spinner(
        low=0 + PROJ_STEP,
        value=1,
        step=PROJ_STEP,
        disabled=bool(proj_auto_checkbox.active),
        width=100,
        height=31,
    )
    proj_display_max_spinner.on_change("value",
                                       proj_display_max_spinner_callback)

    def proj_display_min_spinner_callback(_attr, _old_value, new_value):
        proj_display_max_spinner.low = new_value + PROJ_STEP
        overview_plot_x_image_glyph.color_mapper.low = new_value
        overview_plot_y_image_glyph.color_mapper.low = new_value

    proj_display_min_spinner = Spinner(
        low=0,
        high=1 - PROJ_STEP,
        value=0,
        step=PROJ_STEP,
        disabled=bool(proj_auto_checkbox.active),
        width=100,
        height=31,
    )
    proj_display_min_spinner.on_change("value",
                                       proj_display_min_spinner_callback)

    def hkl_button_callback():
        index = index_spinner.value
        h, k, l = calculate_hkl(det_data, index)
        image_source.data.update(h=[h], k=[k], l=[l])

    hkl_button = Button(label="Calculate hkl (slow)", width=210)
    hkl_button.on_click(hkl_button_callback)

    def events_list_callback(_attr, _old, new):
        doc.events_list_spind.value = new

    events_list = TextAreaInput(rows=7, width=830)
    events_list.on_change("value", events_list_callback)
    doc.events_list_hdf_viewer = events_list

    def add_event_button_callback():
        diff_vec = []
        p0 = [1.0, 0.0, 1.0]
        maxfev = 100000

        wave = det_data["wave"]
        ddist = det_data["ddist"]

        gamma = det_data["gamma"][0]
        omega = det_data["omega"][0]
        nu = det_data["nu"][0]
        chi = det_data["chi"][0]
        phi = det_data["phi"][0]

        scan_motor = det_data["scan_motor"]
        var_angle = det_data[scan_motor]

        x0 = int(np.floor(det_x_range.start))
        xN = int(np.ceil(det_x_range.end))
        y0 = int(np.floor(det_y_range.start))
        yN = int(np.ceil(det_y_range.end))
        fr0 = int(np.floor(frame_range.start))
        frN = int(np.ceil(frame_range.end))
        data_roi = det_data["data"][fr0:frN, y0:yN, x0:xN]

        cnts = np.sum(data_roi, axis=(1, 2))
        coeff, _ = curve_fit(gauss,
                             range(len(cnts)),
                             cnts,
                             p0=p0,
                             maxfev=maxfev)

        m = cnts.mean()
        sd = cnts.std()
        snr_cnts = np.where(sd == 0, 0, m / sd)

        frC = fr0 + coeff[1]
        var_F = var_angle[math.floor(frC)]
        var_C = var_angle[math.ceil(frC)]
        frStep = frC - math.floor(frC)
        var_step = var_C - var_F
        var_p = var_F + var_step * frStep

        if scan_motor == "gamma":
            gamma = var_p
        elif scan_motor == "omega":
            omega = var_p
        elif scan_motor == "nu":
            nu = var_p
        elif scan_motor == "chi":
            chi = var_p
        elif scan_motor == "phi":
            phi = var_p

        intensity = coeff[1] * abs(
            coeff[2] * var_step) * math.sqrt(2) * math.sqrt(np.pi)

        projX = np.sum(data_roi, axis=(0, 1))
        coeff, _ = curve_fit(gauss,
                             range(len(projX)),
                             projX,
                             p0=p0,
                             maxfev=maxfev)
        x_pos = x0 + coeff[1]

        projY = np.sum(data_roi, axis=(0, 2))
        coeff, _ = curve_fit(gauss,
                             range(len(projY)),
                             projY,
                             p0=p0,
                             maxfev=maxfev)
        y_pos = y0 + coeff[1]

        ga, nu = pyzebra.det2pol(ddist, gamma, nu, x_pos, y_pos)
        diff_vector = pyzebra.z1frmd(wave, ga, omega, chi, phi, nu)
        d_spacing = float(pyzebra.dandth(wave, diff_vector)[0])
        diff_vector = diff_vector.flatten() * 1e10
        dv1, dv2, dv3 = diff_vector

        diff_vec.append(diff_vector)

        if events_list.value and not events_list.value.endswith("\n"):
            events_list.value = events_list.value + "\n"

        events_list.value = (
            events_list.value +
            f"{x_pos} {y_pos} {intensity} {snr_cnts} {dv1} {dv2} {dv3} {d_spacing}"
        )

    add_event_button = Button(label="Add spind event")
    add_event_button.on_click(add_event_button_callback)

    metadata_table_source = ColumnDataSource(
        dict(geom=[""], temp=[None], mf=[None]))
    num_formatter = NumberFormatter(format="0.00", nan_format="")
    metadata_table = DataTable(
        source=metadata_table_source,
        columns=[
            TableColumn(field="geom", title="Geometry", width=100),
            TableColumn(field="temp",
                        title="Temperature",
                        formatter=num_formatter,
                        width=100),
            TableColumn(field="mf",
                        title="Magnetic Field",
                        formatter=num_formatter,
                        width=100),
        ],
        width=300,
        height=50,
        autosize_mode="none",
        index_position=None,
    )

    # Final layout
    import_layout = column(proposal_textinput, upload_div, upload_button,
                           file_select)
    layout_image = column(
        gridplot([[proj_v, None], [plot, proj_h]], merge_tools=False))
    colormap_layout = column(
        colormap,
        main_auto_checkbox,
        row(display_min_spinner, display_max_spinner),
        proj_auto_checkbox,
        row(proj_display_min_spinner, proj_display_max_spinner),
    )

    layout_controls = column(
        row(metadata_table, index_spinner,
            column(Spacer(height=25), index_slider)),
        row(add_event_button, hkl_button),
        row(events_list),
    )

    layout_overview = column(
        gridplot(
            [[overview_plot_x, overview_plot_y]],
            toolbar_options=dict(logo=None),
            merge_tools=True,
            toolbar_location="left",
        ), )

    tab_layout = row(
        column(import_layout, colormap_layout),
        column(layout_overview, layout_controls),
        column(roi_avg_plot, layout_image),
    )

    return Panel(child=tab_layout, title="hdf viewer")
            ]
else:
    columns = [
        TableColumn(field="Term", title="Term"),
        TableColumn(field="Score1", title="Score 1")
        ]
    if args.importance:
        columns = [
            TableColumn(field="Term", title="Term"),
            TableColumn(field="Score1", title="Score 1"),
            TableColumn(field="Importance", title="Importance")
            ]

#Call function tapped when something is changed in the node source
source.on_change('selected', tapped)
data_table = DataTable(source=source, columns=columns, width=300, height=560)

#Create boxplot with performance difference vs layer
dfbox = df.loc[df['Score1'] != 0]
dfbox['Layer'] = df['Layer'].astype(int)
groups = dfbox.groupby('Layer')
q1 = groups.quantile(q=0.25)
q2 = groups.quantile(q=0.5)
q3 = groups.quantile(q=0.75)
iqr = q3 - q1
upper = q3 + 1.5*iqr
lower = q1 - 1.5*iqr
out = groups.apply(outliers).dropna()
layers = list(groups.groups.keys())
layers.sort(key=int)
if not out.empty:
Ejemplo n.º 26
0
def generate_results_table(yd_results, yd_fastest_lap_data, year_results,
                           year_fastest_lap_data, driver_id):
    """
    Table of results at each race, including quali position, finish position (or reason for DNF), time, gap to leader,
    fastest lap time and gap to fastest lap (of all drivers), average lap time and gap to fastest average lap time
    (of all drivers)
    :param yd_results: YD results
    :param yd_fastest_lap_data: YD fastest lap data
    :param year_results: Year results
    :param year_fastest_lap_data: Year fastest lap data
    :param driver_id: Driver ID
    :return: Results table
    """
    logging.info("Generating results table")
    source = pd.DataFrame(columns=[
        "race_name", "constructor_name", "quali_pos_str", "finish_pos_str",
        "time_str", "fastest_lap_time_str", "avg_lap_time_str"
    ])
    for idx, results_row in yd_results.iterrows():
        rid = results_row["raceId"]
        race_results = year_results[year_results["raceId"] == rid]
        race_fastest_lap_data = year_fastest_lap_data[
            year_fastest_lap_data["raceId"] == rid]
        race_driver_fastest_lap_data = yd_fastest_lap_data[
            yd_fastest_lap_data["raceId"] == rid]
        race_name = get_race_name(rid)
        constructor_name = get_constructor_name(results_row["constructorId"])
        quali_pos_str = int_to_ordinal(results_row["grid"])
        finish_pos = str(results_row["positionOrder"])
        status_id = results_row["statusId"]
        finish_pos_str, finish_pos = result_to_str(finish_pos, status_id)
        classification = get_status_classification(status_id)
        time = results_row["milliseconds"]
        winner = race_results[race_results["positionOrder"] == 1]
        if winner.shape[0] > 0 and winner["driverId"].values[0] != driver_id \
                and not np.isnan(time) and not np.isnan(results_row["position"]):
            time_gap = millis_to_str(time - winner["milliseconds"].values[0])
            time_str = millis_to_str(time) + " (+" + time_gap + ")"
            if status_id != 1 and classification == "finished":
                time_str = millis_to_str(
                    time) + " (+" + time_gap + ", " + status.loc[
                        status_id, "status"] + ")"
        elif finish_pos == 1:
            time_str = millis_to_str(time)
        else:
            time_str = "~"
        if race_driver_fastest_lap_data.shape[0] > 0:
            fastest_lap_time = race_driver_fastest_lap_data[
                "fastest_lap_time_millis"].values[0]
            fastest_lap_time_str = millis_to_str(fastest_lap_time)
            if race_driver_fastest_lap_data["rank"].values[0] == " 1":
                fastest_lap_time_str = fastest_lap_time_str + " (Fastest)"
            else:
                fastest_time = race_fastest_lap_data[
                    race_fastest_lap_data["rank"] ==
                    " 1"]["fastest_lap_time_millis"]
                if fastest_time.shape[0] > 0 and not np.isnan(
                        fastest_lap_time):
                    fastest_time = fastest_time.values[0]
                    fastest_gap = millis_to_str(fastest_lap_time -
                                                fastest_time)
                    fastest_lap_time_str = millis_to_str(
                        fastest_lap_time) + " (+" + fastest_gap + ")"
            if fastest_lap_time_str == "":
                fastest_lap_time_str = "~"
            fastest_avg_idx = race_fastest_lap_data[
                "avg_lap_time_millis"].idxmin()
            avg_lap_time = race_driver_fastest_lap_data[
                "avg_lap_time_millis"].values[0]
            if np.isnan(avg_lap_time):
                avg_lap_time_str = "~"
            elif race_fastest_lap_data.loc[
                    fastest_avg_idx,
                    "driver_id"] == driver_id or np.isnan(avg_lap_time):
                avg_lap_time_str = millis_to_str(
                    avg_lap_time) + " (Fastest Avg.)"
            else:
                fastest_avg_time = race_fastest_lap_data.loc[
                    fastest_avg_idx, "avg_lap_time_millis"]
                avg_gap = millis_to_str(avg_lap_time - fastest_avg_time)
                avg_lap_time_str = millis_to_str(
                    avg_lap_time) + " (+" + avg_gap + ")"
        else:
            fastest_lap_time_str = "~"
            avg_lap_time_str = "~"
        source = source.append(
            {
                "race_name": race_name,
                "constructor_name": constructor_name,
                "quali_pos_str": quali_pos_str,
                "finish_pos_str": finish_pos_str,
                "time_str": time_str,
                "fastest_lap_time_str": fastest_lap_time_str,
                "avg_lap_time_str": avg_lap_time_str
            },
            ignore_index=True)

    results_columns = [
        TableColumn(field="race_name", title="Race Name", width=100),
        TableColumn(field="constructor_name", title="Constructor", width=100),
        TableColumn(field="quali_pos_str", title="Grid Pos.", width=75),
        TableColumn(field="finish_pos_str", title="Finish Pos.", width=75),
        TableColumn(field="time_str", title="Time", width=100),
        TableColumn(field="fastest_lap_time_str",
                    title="Fastest Lap Time",
                    width=75),
        TableColumn(field="avg_lap_time_str", title="Avg. Lap Time", width=75),
    ]
    results_table = DataTable(source=ColumnDataSource(data=source),
                              columns=results_columns,
                              index_position=None,
                              height=27 * yd_results.shape[0])
    title = Div(
        text=
        f"<h2><b>Results for each race</b></h2><br><i>The fastest lap time and average lap time gaps "
        f"shown are calculated based on the gap to the fastest of all drivers and fastest average of "
        f"all drivers in that race respectively.</i>")
    return column(
        [title, row([results_table], sizing_mode="stretch_width")],
        sizing_mode="stretch_width")
Ejemplo n.º 27
0
'''
-------------------------- panel 0 --------------------------
'''
tab0_Div_title = Div(text="""
<p><b>Welcome to Event Browser. Select one solar event to process. Have fun!</b></p>""",
                     width=config['plot_config']['tab1']['StrID_DataTb_wdth'])

tab0_SRC_Tb_EvtID = ColumnDataSource(EvtID_list)
tab0_TbCols2 = [
    TableColumn(field="event_id", title="EvtID"),
    TableColumn(field="timeran", title="Time Range"),
    TableColumn(field="freqran", title="Freq Range"),
]
tab0_DataTb_evt = DataTable(
    source=tab0_SRC_Tb_EvtID,
    columns=tab0_TbCols2,
    width=config['plot_config']['tab1']['StrID_DataTb_wdth'],
    height=config['plot_config']['tab1']
    ['StrID_DataTb_hght'])  # , editable=True)
tab0_Div_Tb = Div(text=""" """,
                  width=config['plot_config']['tab1']['StrID_DataTb_wdth'])
tab0_Div_exit = Div(text="""
<p><b>Warning</b>: 1. Click the <b>Exit EvtBrowser</b> first before closing the tab</p>
<p><b>Warning</b>: 2. <b>QLook</b> <b>FSview</b> or <b>FSview2CASA</b> tabs will disconnect if <b>Exit EvtBrowser is clicked</b></p>""",
                    width=150)

port = 5010
ports = []
ports.append(port)

tab0_selected_EvtID_entry = None
Ejemplo n.º 28
0
        }
    elif field == "Comments":
        strfmt_in = {}
    else:
        strfmt_in = {"text_align": "right"}
    columns_changed.append(
        TableColumn(field=field,
                    title=title,
                    width=width,
                    formatter=StringFormatter(**strfmt_in)))

data_table = DataTable(
    source=src_table,
    columns=columns,
    index_width=20,
    width=480 + 20,  # sum of col widths + idx width
    height=600,
    editable=True,
    fit_columns=True,
    sortable=False,
)
data_table_changed = DataTable(
    source=src_table_changes,
    columns=columns_changed,
    index_width=20,
    width=480 + 20,  # sum of col widths + idx width
    height=200,
    editable=False,
    fit_columns=True,
    sortable=False,
)
data_table_title = Div(text="""<b>All Station Data:</b>""",
Ejemplo n.º 29
0
def plot_pca(read_counting_table, pca_result, url_link, output_file_):
    read_counting_table["PCA-component_1"] = [pos[0] for pos in pca_result]
    read_counting_table["PCA-component_2"] = [pos[1] for pos in pca_result]

    read_counting_table["Attributes_split"] = \
        read_counting_table["Attributes"].apply(lambda attr: dict(
            [key_value_pair.split("=")
             for key_value_pair in attr.split(";")]))

    hower_data = dict(
        x=read_counting_table["PCA-component_1"],
        y=read_counting_table["PCA-component_2"],
        feature=read_counting_table["Feature"],
        cluster_label=read_counting_table["Cluster_label"],
        gene=read_counting_table["Gene"],
        attribute=read_counting_table["Attributes"])

    source = ColumnDataSource(hower_data)
    hover = HoverTool(tooltips=[
        ("Gene", "@gene"),
        ("Feature", "@feature"),
        ("Cluster label", "@cluster_label")])

    plot = figure(plot_width=900, plot_height=900,
                  tools=[hover, BoxZoomTool(), ResetTool(), PanTool(),
                         WheelZoomTool(), "lasso_select", "tap"],
                  output_backend="webgl", lod_threshold=100,
                  title="Grad-Seq PCA RNA-Seq")
    plot.toolbar.logo = None
    plot.circle("x", "y", source=source, size=7, alpha=3, line_color="grey", color="grey")
    plot.yaxis.axis_label_text_font_size = "15pt"
    plot.xaxis.axis_label_text_font_size = "15pt"
    plot.title.text_font_size = '15pt'
    url = url_link
    taptool = plot.select(type=TapTool)
    taptool.callback = OpenURL(url=url)
    taptool = plot.select(type=TapTool)
    taptool.callback = OpenURL(url=url)

    plot.xaxis.axis_label = "Component 1"
    plot.yaxis.axis_label = "Component 2"
    source2 = ColumnDataSource(data=dict(x=[], y=[]))
    plot2 = figure(plot_width=300, plot_height=300,
                   tools="", title="Zoom", output_backend="webgl", lod_threshold=100)
    plot2.toolbar.logo = None
    plot2.circle('x', 'y', source=source2, alpha=0.6)
    columns = [
        TableColumn(field="gene", title="Genes"),
        TableColumn(field="feature", title="Feature"),
        TableColumn(field="attribute", title="Attributes")
    ]
    data_table = DataTable(source=source, columns=columns, width=450, height=800, fit_columns=True)
    savebutton = Button(label="Save", button_type="success")
    source.selected.js_on_change('indices', CustomJS(args=dict(s1=source, s2=source2), code="""
            var inds = cb_obj.indices;
            var d1 = s1.data;
            var d2 = s2.data;
            d2['x'] = []
            d2['y'] = []
            for (var i = 0; i < inds.length; i++) {
                d2['x'].push(d1['x'][inds[i]])
                d2['y'].push(d1['y'][inds[i]])
            }
            s2.change.emit();
        """)
                                 )

    savebutton.callback = CustomJS(args=dict(source_data=source), code="""
        var inds = source_data.selected['1d'].indices;
        var data = source_data.data;
        console.log("inds", inds);
        console.log("data", data);
        var out = "Features\\tGene\\tAttributes + \\n";
        for (i = 0; i < inds.length; i++) {
                 out += data['feature'][inds[i]] + "\\t" + data['gene'][inds[i]] + "\\t" +  
                 data['attribute'][inds[i]] + "\\n";
        }
        var file = new Blob([out], {type: 'text/plain'});
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(file);
        elem.download = 'selected-data.csv';
        document.body.appendChild(elem);
        elem.click();
        document.body.removeChild(elem);
        """)

    output_file(output_file_ + ".html", title="Grad-seq PCA")
    layout = row(plot, data_table, column(plot2, savebutton))
    show(layout)
Ejemplo n.º 30
0
    source1.data = {
        'school' : current.school,
        'sex'    : current.sex,
        'age'    : current.age,
        'G3'     : current.G3
    }

columns = [
    TableColumn(field="school", title="School Name"),
    TableColumn(field="sex", title="Gender"),
    TableColumn(field="age", title="Age (years)"),
    TableColumn(field="G3", title="Grade")
]

update()
data_table = DataTable(source=source1, columns=columns,width=1000)
##########################################################################################################
#Create Chart for displaying the Frquency of Reason

radio_group = RadioGroup(
        labels=["GP", "MS"], active=0)


tempData = df[(df['school']== 'GP')]
dfReason = tempData.groupby('reason').size().reset_index(name='counts')        
x1 = dfReason['reason']
y1 = dfReason['counts']

dataSource = ColumnDataSource(data=dict(x1=x1,y1=y1,data=dfReason))

def make_plot(attr,old,new):