Exemplo n.º 1
0
        def modify_doc(doc):
            p1 = Plot(plot_height=400,
                      plot_width=400,
                      x_range=Range1d(0, 1),
                      y_range=Range1d(0, 1),
                      min_border=10)
            p2 = Plot(plot_height=400,
                      plot_width=400,
                      x_range=Range1d(0, 1),
                      y_range=Range1d(0, 1),
                      min_border=10)
            button = Button(css_classes=['foo'])
            layout = column(p1, button)

            def cb(event):
                if p2 not in layout.children:
                    layout.children = [p1, button, p2]

            button.on_event('button_click', cb)

            def iw(attr, old, new):
                data['iw'] = (old, new)

            def ih(attr, old, new):
                data['ih'] = (old, new)

            p2.on_change('inner_width', iw)
            p2.on_change('inner_height', ih)
            doc.add_root(layout)
Exemplo n.º 2
0
def main():
    plots = [
        figure(title='Styles Demo {i}'.format(i=i + 1),
               plot_width=200,
               plot_height=200,
               tools='') for i in range(9)
    ]
    [plot.line(np.arange(10), np.random.random(10)) for plot in plots]

    button_bokeh = Button(label="Custom Style: Bokeh Button",
                          css_classes=['custom_button_bokeh'])
    button_bokeh.name = 'button_text'
    button_bokeh.on_event(ButtonClick, on_button_click_event_callback)
    curdoc().add_root(button_bokeh)
    curdoc().add_root(gridplot(children=[plot for plot in plots], ncols=3))

    cur_doc = curdoc()
    # cur_doc.on_event(DocumentUpdate, on_document_update_event_callback)
    cur_doc.on_event(DocumentPatchedEvent, on_document_patch_event_callback)

    cur_doc.theme = Theme(
        filename=
        "G:\\dt-boot\\dt-data-analysis-visual\\app\\api\\server_visual\\timeseries-multi\\dark-theme.yaml"
    )
    cur_doc.on_session_destroyed(on_session_destroyed)
    # cur_doc.add_periodic_callback(on_periodic_callback, 1000)
    cur_doc.add_next_tick_callback(on_next_tick_callback)
Exemplo n.º 3
0
def test_buttonclick_event_callbacks():
    button = Button()
    test_callback = EventCallback()
    button.on_event(events.ButtonClick, test_callback)
    assert test_callback.event_name == None
    button._trigger_event(events.ButtonClick(button))
    assert test_callback.event_name == events.ButtonClick.event_name
Exemplo n.º 4
0
def hookUpPlots(pCandle, pBuySell, pVolume, divCandle, divText, crosshairTool, pDebug):
    pCandle.x_range = pBuySell.x_range
    pVolume.x_range = pBuySell.x_range
    pCandle.add_tools(crosshairTool)
    pBuySell.add_tools(crosshairTool)
    pVolume.add_tools(crosshairTool)
    pCandle.xaxis.ticker = [8.75, 9, 9.5, 10, 10.5, 11, 11.5, 13, 13.5, 14, 14.5, 14.75]
    pCandle.xaxis.major_label_overrides = {
        8.5:"8:30", 8.75:"8:45", 9:"9:00", 9.5:"9:30", 10:"10:00",
        10.5:"10:30", 11:"11:00", 11.5:"11:30", 13:"13:00",
        13.5:"13:30", 14:"14:00", 14.5:"14:30", 14.75:"14:45"}
    pBuySell.xaxis.ticker = pCandle.xaxis.ticker
    pVolume.xaxis.ticker = pCandle.xaxis.ticker
    pVolume.xaxis.major_label_overrides = pCandle.xaxis.major_label_overrides

    def btnStart_clicked(event):
        btnStart._document.get_model_by_name("btnStart").label = "Started!"
        # activation_function()

    def activation_function():
        btnStart._document.add_periodic_callback(lambda: updateDoc(btnStart._document), 1000)
        btnStart._document.get_model_by_name("btnStart").label = "Started!"
        btnStart.disabled = True

    pLabel = Paragraph(text="Debug information (please ignore): ", width=pDebug.width, height=10, name="pLabel")
    btnStart = Button(label="Start automatic update", button_type="success", name="btnStart")
    btnStart.on_event(ButtonClick, btnStart_clicked)
    return row(column(pCandle, pBuySell, pVolume), column(divCandle, btnStart, divText, pLabel, pDebug)), \
           activation_function
Exemplo n.º 5
0
    def test_event_handles_new_callbacks_in_event_callback(self) -> None:
        from bokeh.models import Button
        d = document.Document()
        button1 = Button(label="1")
        button2 = Button(label="2")

        def clicked_1():
            button2.on_event('button_click', clicked_2)
            d.add_root(button2)

        def clicked_2():
            pass

        button1.on_event('button_click', clicked_1)
        d.add_root(button1)

        decoder = Deserializer(references=[button1])
        event = decoder.decode(
            dict(
                type="event",
                name="button_click",
                values=dict(model=dict(id=button1.id)),
            ))
        try:
            d.callbacks.trigger_event(event)
        except RuntimeError:
            pytest.fail(
                "trigger_event probably did not copy models before modifying")
Exemplo n.º 6
0
def test_buttonclick_event_callbacks():
    button = Button()
    test_callback = EventCallback()
    button.on_event(events.ButtonClick, test_callback)
    assert test_callback.event_name == None
    button._trigger_event(events.ButtonClick(button))
    assert test_callback.event_name == events.ButtonClick.event_name
Exemplo n.º 7
0
def modify(doc):
    button = Button(label="Foo", button_type="success")

    def callback(event):
        print('Python:Click')

    button.on_event(ButtonClick, callback)
    doc.add_root(column(o.plot_BS_Pressure2(), button))
Exemplo n.º 8
0
 def modify_doc(doc):
     source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
     plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
     plot.add_glyph(source, Circle(x='x', y='y', size=20))
     plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
     button = Button(css_classes=['foo'])
     def cb(event):
         source.data=dict(x=[10, 20], y=[10, 10])
     button.on_event('button_click', cb)
     doc.add_root(column(button, plot))
Exemplo n.º 9
0
    def test_event_handles_new_callbacks_in_event_callback(self) -> None:
        from bokeh.models import Button
        d = document.Document()
        button1 = Button(label="1")
        button2 = Button(label="2")
        def clicked_1():
            button2.on_event('button_click', clicked_2)
            d.add_root(button2)
        def clicked_2():
            pass

        button1.on_event('button_click', clicked_1)
        d.add_root(button1)

        event_json = {"event_name": "button_click", "event_values": {"model": {"id": button1.id}}}
        try:
            d.callbacks.trigger_json_event(event_json)
        except RuntimeError:
            pytest.fail("trigger_event probably did not copy models before modifying")
Exemplo n.º 10
0
def initialize():
    text_output = Paragraph(text='Status', width=300, height=100)
    DATA_STORE.update({'text_output': text_output})

    retrieve_data(initial=True)
    df = DATA_STORE['data']

    symbols = sorted(list(set(df.index.get_level_values(level=0))))

    if DATA_STORE['valid_symbols'] is None:
        DATA_STORE.update({'valid_symbols': symbols})

    set_data_symbol()

    menu = [*zip(symbols, symbols)]
    dropdown = Dropdown(label='Select Symbol',
                        button_type='primary',
                        menu=menu)
    dropdown.on_change('value', dropdown_callback)

    bucket_input = TextInput(value='mlsl-mle-ws', title='S3 Bucket:')
    key_input = TextInput(value='training-data/crypto_test_preds.csv',
                          title='S3 Key:')
    profile_input = TextInput(value='kyle_general', title='Boto Profile:')
    text_button = Button(label='Pull Data')
    text_button.on_event(ButtonClick, text_button_callback)
    default_button = Button(label='Reset Defaults')
    default_button.on_event(ButtonClick, default_button_callback)

    DATA_STORE.update({
        'dropdown': dropdown,
        's3_bucket_input': bucket_input,
        's3_key_input': key_input,
        'text_button': text_button,
        'boto_profile_input': profile_input,
        'default_button': default_button
    })
Exemplo n.º 11
0
p = figure(toolbar_location=None, background_fill_color="#fafafa")
p.circle(x=1, y=list(range(0, 11)))
p.line('x', 'y', color="orange", source=source)

slider = Slider(start=0, end=10, step=0.1, value=1)


def scb(attr, old, new):
    source.data['y'] = new * y


slider.on_change('value', scb)

combine = Button(label="hold combine")
combine.on_event(ButtonClick, lambda event: doc.hold("combine"))

collect = Button(label="hold collect")
collect.on_event(ButtonClick, lambda event: doc.hold("collect"))

unhold = Button(label="unhold")
unhold.on_event(ButtonClick, lambda event: doc.unhold())

div = Div(text="""
<p>Bokeh Documents can be configured to "hold" property change events until a
corresponding "unhold" is issued. There are two modes. In "collect" mode, all
held events are replayed in order when "unhold" is called. In "combine" mode,
Bokeh will coalesce events so that at most one event per property is issued.</p>

<p>Click "combine" or "collect" below, and scrub the slider. Then click "unhold"
to see the result.</p>
Exemplo n.º 12
0
# Pan events
p.js_on_event(events.Pan, display_event(div, attributes=pan_attributes))
p.js_on_event(events.PanStart, display_event(div, attributes=point_attributes))
p.js_on_event(events.PanEnd, display_event(div, attributes=point_attributes))

# Pinch events
p.js_on_event(events.Pinch, display_event(div, attributes=pinch_attributes))
p.js_on_event(events.PinchStart, display_event(div,
                                               attributes=point_attributes))
p.js_on_event(events.PinchEnd, display_event(div, attributes=point_attributes))

## Register Python event callbacks

# Button event
button.on_event(events.ButtonClick, print_event())

# LOD events
p.on_event(events.LODStart, print_event())
p.on_event(events.LODEnd, print_event())

# Point events

p.on_event(events.Tap, print_event(attributes=point_attributes))
p.on_event(events.DoubleTap, print_event(attributes=point_attributes))
p.on_event(events.Press, print_event(attributes=point_attributes))

# Mouse wheel event
p.on_event(events.MouseWheel, print_event(attributes=wheel_attributes))

# Mouse move, enter and leave
Exemplo n.º 13
0
                      title='beta (prob of E to quarantine at arrival)')
spinner11 = TextInput(value='0.8',
                      title='tau (prob of I to quarantine at arrival)')
spinner12 = Slider(start=0, end=500, value=20, step=1, title='Bats?')

# Matrix inputs: (Not used yet - just for show)
g1 = TextInput(value='[0, 13056, 5930, 563, 355]', title='Matrix')
g2 = TextInput(value='[6849, 0, 99640, 197190, 49887]')
g3 = TextInput(value='[20,29300, 0, 261774,  66226]')
g4 = TextInput(value='[214, 86535, 419844, 0, 237225]')
g5 = TextInput(value='[153, 21950, 106494, 237846, 0]')
matrix = column(g1, g2, g3, g4, g5)

# Buttons to control updates/resets
button_solve = Button(label="Solve", button_type="success")
button_solve.on_event(ButtonClick,
                      update)  #('value', lambda attr, old, new: update())
button_reset = Button(label="Reset", button_type="warning")
button_reset.on_event(ButtonClick, clear)

# Organize layout
figs = gridplot([fig_init, fig_init2, fig_init3, fig_init4, fig_init5],
                ncols=3,
                plot_width=400,
                plot_height=300)

model_controls = column(spinner1, spinner2, spinner3, button_solve,
                        button_reset)
quarantine_controls = column(spinner4, spinner5, spinner6, spinner7, spinner8)
quarantine_controls2 = column(spinner9, spinner10, spinner11, spinner12)
controls = row(model_controls, quarantine_controls, quarantine_controls2,
               matrix)
Exemplo n.º 14
0
def get_download_widget(datasets,
                        series,
                        session,
                        key_mapper,
                        savepath,
                        export_folder=None,
                        icons=None):
    """Return a download button."""
    def callback_download(event):
        def serie_generator(selected_keylist):
            for key in selected_keylist:
                if key in key_mapper:
                    yield key_mapper.get(key)

        def append_qc_comment(meta):
            time_stamp = get_time_as_format(now=True, fmt='%Y%m%d%H%M')
            meta[
                len(meta) +
                1] = '//COMNT_QC; MANUAL QC PERFORMED BY {}; TIMESTAMP {}'.format(
                    session.settings.user, time_stamp)

        if not len(series.selected.indices):
            message_box("No files where downloaded. Did you select any?",
                        icon_path=icons.get('question'))
            print('No selected series to download')
            print('len(series.selected.indices)', series.selected.indices)
            return

        if export_folder:
            path = export_folder
        else:
            path = get_folder_path_from_user()
        if not path:
            print('No download directory selected! '
                  'Using the system standard download '
                  'folder instead (Hämtade filer)')

        generator = serie_generator(
            [series.data['KEY'][idx] for idx in series.selected.indices])

        datasets_to_update = {}
        for ds_name in generator:
            append_qc_comment(datasets[ds_name]['metadata'])
            datasets_to_update[ds_name] = datasets[ds_name]

        if datasets_to_update:
            selected_path = path or savepath or 'C:/QC_CTD'
            session.save_data(
                [datasets_to_update],
                save_path=selected_path,
                collection_folder=False if path else True,
                writer='ctd_standard_template',
            )
            message_box(
                f"Download completed!\n"
                f"The files are stored under:\n{selected_path}",
                icon_path=icons.get('success'))
        else:
            message_box(
                "No files where downloaded. "
                "A guess: Not able to map between "
                "loaded files and file names.",
                icon_path=icons.get('question'))
            print('No download!')

    button = Button(label="Select directory and download data",
                    button_type="success",
                    width=40)
    button.on_event(ButtonClick, callback_download)
    return button
Exemplo n.º 15
0
    page_change()


def do_prev_page(event):
    pdff.prev_page()
    page_change()


def do_build(even):
    pdfbld.build()
    pdff.switch_preview_source()

    pdff.page_to_gif()
    im_source.data = {'url': [url_formatter(pdff.current_gif)]}


button_next_page = Button(label="Next page")
button_next_page.on_event(ButtonClick, do_next_page)
button_prev_page = Button(label="Previous page")
button_prev_page.on_event(ButtonClick, do_prev_page)

button_build = Button(label="Build")
button_build.on_event(ButtonClick, do_build)

l = layout([[p], [button_next_page], [button_prev_page], [button_build]],
           sizing_mode='fixed')

curdoc().add_root(l)
curdoc().title = "Sign PDF"

# %%
Exemplo n.º 16
0
## Bokeh server for button click

from bokeh.io import curdoc
from bokeh.layouts import row
from bokeh.models import Button, ColumnDataSource
from bokeh.plotting import figure

x=[3,4,6,12,10,1]
y=[7,1,3,4,1,6]

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

plot_figure = figure(height=450, width=600,
              tools="save,reset",
              x_range=[0,14], y_range=[0,12], toolbar_location="below")

plot_figure.scatter('x', 'y', source=source, size=10)

button = Button(label="Click to set plot title", button_type="success")

def button_click():
    plot_figure.title.text = 'Button Clicked'

button.on_event('button_click', button_click)

layout=row(button,plot_figure)

curdoc().add_root(layout)
curdoc().title = "Button Bokeh Server"
Exemplo n.º 17
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
Exemplo n.º 18
0
x = np.linspace(0, 2, 1000)
y = 1 - (x-1)**2

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

p  = figure(title="initial title")
p.circle(x=1, y=list(range(0, 11)))
p.line('x', 'y', color="orange", source=source)

slider = Slider(start=0, end=10, step=0.1, value=1)
def scb(attr, old, new):
    source.data['y'] = new * y
slider.on_change('value', scb)

combine = Button(label="hold combine")
combine.on_event(ButtonClick, lambda event: doc.hold("combine"))

collect = Button(label="hold collect")
collect.on_event(ButtonClick, lambda event: doc.hold("collect"))

unhold = Button(label="unhold")
unhold.on_event(ButtonClick, lambda event: doc.unhold())

doc.add_root(column(p, slider, combine, collect, unhold))

@repeat(np.linspace(0, 10, 100))
def update(v):
    slider.value = v

curdoc().add_periodic_callback(update, 200)
Exemplo n.º 19
0
select = Select(title="Pick a Constituent:",
                value="foo",
                options=list(smilies_dict_select.keys()))
select.on_change('value', change_text)

flavor_select = Select(title="Pick a Flavor:",
                       value="foo",
                       options=list(form_dict_select.keys()))
flavor_select.on_change('value', change_form)

oil_add = Select(title="Add Oil:",
                 value="foo",
                 options=list(oil_dict_select.keys()))
oil_add.on_change('value', add_oil)

button.on_event(ButtonClick, update_title)
button2.on_event(ButtonClick, run_rules)
# Set up layouts and add to document
col1 = column(text, conc, select, oil_add, flavor_select, button, button2)
col2 = column(p)
col3 = column()
layout = layout([[col1, col2, col3]])
slider = None
mol_list = None
data = None
para = None
names = None
sim_tab = None
curdoc().add_root(layout)
curdoc().title = "Conc"
Exemplo n.º 20
0
class Widgets:
    def __init__(self, renderer):
        self.file_input = Dropdown(label="Select dataset", menu=[])
        for dataset_name in SQLDBInformer(DbConn({})).get_all_schemas():
            if dataset_name in set(["information_schema", "performance_schema", "sys", "defaultDB", "mysql"]):
                continue
            if dataset_name[:3] == "pg_":
                continue
            self.file_input.menu.append(dataset_name)
        self.run_id_dropdown = Dropdown(label="select run id here", menu=[])
        self.ground_truth_id_dropdown = Dropdown(label="select ground truth id here", menu=[])
        self.score_slider = RangeSlider(start=0, end=1, value=(0, 1), step=.1, callback_policy='mouseup',
                                        title="score range")
        self.max_elements_slider = Slider(start=1000, end=100000, value=10000, step=1000,
                                          callback_policy='mouseup', title="max render")
        self.range_link_radio = RadioGroup(labels=["Link read plot to x-range", "Link read plot to y-range"],
                                           active=0, orientation="horizontal")
        self.full_render_button = Button(label="render without limit")
        self.render_mems_button = Button(label="render MEMs")
        self.delete_button = Button(label="Delete Dataset")
        self.force_read_id = TextInput(value="", title="Render reads with ids (comma seperated list):")

        self.file_input.on_change("value", lambda x,y,z: self.file_input_change(renderer))
        self.run_id_dropdown.on_change("value", lambda x,y,z: self.run_id_change(renderer))
        self.ground_truth_id_dropdown.on_change("value", lambda x,y,z: self.ground_id_change(renderer))
        self.score_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))
        self.max_elements_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))

        self.full_render_button.on_event(ButtonClick, lambda x: self.full_render(renderer))
        self.render_mems_button.on_event(ButtonClick, lambda x: self.render_mems_button_event(renderer))
        self.delete_button.on_event(ButtonClick, lambda x: self.delete_button_event(renderer))
        self.force_read_id.on_change("value", lambda x,y,z: self.forced_read_ids_change(renderer))

        self.spinner_div = Div(text=html_file("spinner"), sizing_mode="scale_both", visible=False)
        self.condition = threading.Condition()

        self.subset_buttons = CheckboxButtonGroup(labels=["Render false-positives", "Render false-negatives",
                                                          "Render true-positives", "Compute Stats"],
                                                          active=[0, 1, 2])
        self.subset_buttons.on_click(lambda x: self.forced_read_ids_change(renderer))
        self.blur_slider = Slider(start=0, end=500, value=100, step=1, callback_policy='mouseup',
                                        title="Blur")
        self.blur_slider.on_change("value_throttled", lambda x,y,z: self.slider_change(renderer))

    def show_spinner(self, renderer):
        self.spinner_div.visible = True

    def hide_spinner(self, renderer):
        self.spinner_div.visible = False

    def file_input_change(self, renderer):
        with self.condition:
            self.file_input.label = "Selected dataset: " + self.file_input.value
            renderer.setup()

    def run_id_change(self, renderer):
        with self.condition:
            renderer.read_plot.recalc_stat = True
            print("new run_id:", self.run_id_dropdown.value)
            renderer.cached_global_overview = None
            run_table = SvCallerRunTable(renderer.db_conn)
            self.run_id_dropdown.label = "Selected run: " + run_table.getName(int(self.run_id_dropdown.value)) + \
                                            " - " + self.run_id_dropdown.value
            call_table = SvCallTable(renderer.db_conn)
            self.score_slider.end = 0
            if call_table.num_calls(int(self.run_id_dropdown.value), 0) > 0:
                self.score_slider.end = call_table.max_score(int(self.run_id_dropdown.value)) + 1
                self.score_slider.value = (0, self.score_slider.end)
            renderer.render(ignorable=False)

    def ground_id_change(self, renderer):
        with self.condition:
            renderer.read_plot.recalc_stat = True
            run_table = SvCallerRunTable(renderer.db_conn)
            self.ground_truth_id_dropdown.label = "Selected ground truth: " + \
                                                    run_table.getName(int(self.ground_truth_id_dropdown.value)) + \
                                                    " - " + self.ground_truth_id_dropdown.value
            renderer.render(ignorable=False)

    def slider_change(self, renderer):
        renderer.read_plot.recalc_stat = True
        renderer.render(ignorable=False)

    def forced_read_ids_change(self, renderer):
        renderer.render(ignorable=False)

    def full_render(self, renderer):
        renderer.render(render_all=True, ignorable=False)

    def get_blur(self):
        return self.blur_slider.value
    def get_render_f_p(self):
        return 0 in self.subset_buttons.active

    def get_render_f_n(self):
        return 1 in self.subset_buttons.active

    def get_render_t_p(self):
        return 2 in self.subset_buttons.active

    def compute_stats(self):
        return 3 in self.subset_buttons.active

    def get_forced_read_ids(self, renderer):
        if len(self.force_read_id.value) == 0:
            return []
        read_table = ReadTable(renderer.db_conn)
        ret = []
        for id_n_name in self.force_read_id.value.split(";"):
            split = id_n_name.split(":")
            if not len(split) == 2:
                continue
            seq_id, name = split
            idx = read_table.get_read_id(int(seq_id), name)
            if idx == -1:
                print(name, "does not exist in DB")
                continue
            ret.append(idx)
        return ret

    def render_mems_button_event(self, renderer):
        if not renderer.selected_read_id is None:
            read = ReadTable(renderer.db_conn).get_read(renderer.selected_read_id)

            seed_plot_y_s = int(max(renderer.read_plot.plot.y_range.start, 0))
            seed_plot_y_e = int(min(renderer.read_plot.plot.y_range.end, len(read)))
            seed_plot_x_s = int(max(renderer.read_plot.plot.x_range.start, 0))
            seed_plot_x_e = int(min(renderer.read_plot.plot.x_range.end, renderer.pack.unpacked_size_single_strand))

            filtered_mems = compute_seeds_area(renderer.params, seed_plot_x_s,
                                               seed_plot_y_s, seed_plot_x_e-seed_plot_x_s,
                                               seed_plot_y_e-seed_plot_y_s, read, renderer.pack)
            seed_data_new = dict((key, []) for key in renderer.read_plot.seeds.data.keys())
            if len(filtered_mems) > 0:
                max_seed_size = max( seed.size for seed in filtered_mems )
                for idx in range(len(filtered_mems)):
                    add_seed(filtered_mems[idx], seed_data_new, max_seed_size, [], [],
                                0, False, -1, renderer.selected_read_id, idx, read.name)
            renderer.read_plot.seeds.data = seed_data_new

    def delete_button_event(self, renderer):
        print("unimplemented at the moment...")
        #renderer.sv_db.delete_run(renderer.get_run_id())
        renderer.setup()
Exemplo n.º 21
0
    def bkapp(self, doc):
        basePath = self.basePath
        npyPath = self.npyPath
        covMapDict = self.covMapDict

        self.logger.debug('basePath: ' + str(basePath))
        self.logger.debug('npyPath: ' + str(npyPath))
        self.logger.debug('covMapDict: ' + str(covMapDict))

        # Retrieving Data
        #-----------------------------------------------------------------
        # Loading in data
        curPath = os.getcwd()

        # Loading distance difference matrices
        self.logger.info('Reading npy matrices from: ' + str(npyPath))
        npyNameList = [npyFile for npyFile in os.listdir(npyPath) \
                               if (npyFile[-3:] == 'npy') \
                               and ('Minus' in npyFile) \
                               and ('Scaled' not in npyFile)]

        self.logger.debug('npyNameList: ' + str(npyNameList))

        npyList = [None] * len(npyNameList)
        for i, npyName in enumerate(npyNameList):
            npyList[i] = np.load(os.path.join(npyPath, npyName))

        self.logger.debug('npyList: ' + str(npyList))

        # Loading and defining dictionaries to map to and fro residue pairs to
        # the corresponding submatrices
        invCovMapDict = {str(value): key for key, value in covMapDict.items()}

        # Loading Covariance Matrix and helper class to split submatrices
        self.logger.info('Loading CovarianceMatrix.npy')
        covarianceMatrix = np.load(os.path.join(basePath, \
                                                'CovarianceMatrix.npy'))
        self.covSize = covarianceMatrix.shape[0]
        self.logger.info('Loaded CovarianceMatrix.npy')
        cSubmatrix = CovSubmatrix()
        #-----------------------------------------------------------------

        # Interactive Plot Tools
        TOOLS = 'hover,save,pan,box_zoom,reset,wheel_zoom'

        # Defining color values
        vmin = -5
        vmax = 5

        # New Color Map Bokeh
        blueRedColors = [
            '#FF0000', '#FF1111', '#FF2222', '#FF3333', '#FF4444', '#FF5555',
            '#FF6666', '#FF7777', '#FF8888', '#FF9999', '#FFAAAA', '#FFBBBB',
            '#FFCCCC', '#FFDDDD', '#FFEEEE', '#FFFFFF', '#EEEEFF', '#DDDDFF',
            '#CCCCFF', '#BBBBFF', '#AAAAFF', '#9999FF', '#8888FF', '#7777FF',
            '#6666FF', '#5555FF', '#4444FF', '#3333FF', '#2222FF', '#1111FF',
            '#0000FF'
        ]

        # Creating list
        axesXMax = npyList[0].shape[0]
        if int(self.scale) != int(npyList[0].shape[0]):
            axesXMax = self.scale
        axesYMax = npyList[0].shape[1]
        if int(self.scale) != int(npyList[0].shape[1]):
            axesYMax = self.scale

        xyPairList = [None] * axesXMax * axesYMax

        for i in range(0, axesXMax):
            for j in range(0, axesYMax):
                xyPairList[i + j * axesXMax] = (i + 1, j + 1)

        self.logger.debug('xyPairList: ' + str(xyPairList))
        self.logger.debug('type: xyPairList: ' + str(type(xyPairList)))

        # Reshaping source values in order to shift indices from starting
        # with 0 to starting with 1
        xVals = np.transpose(xyPairList)[0]
        yVals = np.transpose(xyPairList)[1]
        covVals = npyList[0].flatten()
        self.logger.debug('npyList: ' + str(npyList))
        self.logger.debug('covVals: ' + str(covVals))

        # Checks to see if the specified scale matches
        axesLength = int(np.sqrt(len(covVals)))
        self.indexDict = None
        self.scaledRangeDict = None
        if axesLength != int(self.scale):
            axesLength = self.scale
            newMatrix, self.indexDict = self.rescaleMatrix(covVals, self.scale)
            covVals = newMatrix.flatten()

        # Creating a dictionary mapping the new indices to
        # strings describing the ranges of the original indices
        if self.indexDict is not None:
            self.scaledRangeDict = self.serializeIndexDict(self.indexDict)

            # Saving the scaled index mapping to file
            indexDictFilepath = os.path.join(basePath, 'scaledIndexMap.npy')
            np.save(indexDictFilepath, self.indexDict, allow_pickle=True)
            self.logger.info('Saving the scaled index mapping to: ' \
                             + str(indexDictFilepath))

        self.logger.debug('scaledRangeDict: ' + str(self.scaledRangeDict))

        # Defining fields to be displayed in hover tooltips
        source = ColumnDataSource(
            data={
                'x': xVals.flatten(),
                'y': yVals.flatten(),
                'covValues': covVals.flatten()
            })

        tooltipList = [('xCoord', '@x'), ('yCoord', '@y'),
                       ('Magnitude', '@covValues')]

        # Defining color map
        color_mapper = LinearColorMapper(palette=blueRedColors,
                                         low=vmin,
                                         high=vmax)

        color_bar = ColorBar(color_mapper=color_mapper,
                             label_standoff=12,
                             border_line_color=None, location=(0,0),
                             ticker=BasicTicker(\
                                desired_num_ticks=len(blueRedColors)))

        # Plotting
        self.logger.info('Determining axis scaling.')
        if self.scaledRangeDict is not None:
            plotLabel = FactorRange(
                factors=[i for i in self.scaledRangeDict.values()],
                bounds=(0.5, len(self.scaledRangeDict.keys()) + 0.5),
                factor_padding=0.0,
                range_padding_units="percent",
                range_padding=0)
        else:
            plotLabel = FactorRange(
                            factors=[str(int(i+1)) \
                                     for i in range(axesLength)],
                           bounds=(0.5, axesLength + 0.5))

        self.logger.info('Creating initial figure')
        # Primary display for directly interacting with the matrices
        plot = figure(x_range=plotLabel,
                      y_range=plotLabel,
                      tools=TOOLS,
                      toolbar_location='below',
                      tooltips=tooltipList)

        plot.add_tools(EnhanceTool())

        plot.xaxis.major_label_orientation = math.pi / 2

        self.logger.info('Creating initial primary plot')
        plot.rect(x='x',
                  y='y',
                  width=1,
                  height=1,
                  source=source,
                  fill_color={
                      'field': 'covValues',
                      'transform': color_mapper
                  },
                  line_color=None)

        plot.title = Title(text='Distance Difference Matrix: ' \
                           + npyNameList[0], \
                           align='center')

        plot.add_layout(color_bar, 'right')

        # Secondary display for interacting with queued covariance submatrices
        plot2 = figure(x_range=plotLabel,
                       y_range=plotLabel,
                       tools=TOOLS,
                       toolbar_location='below',
                       tooltips=tooltipList)
        plot2.add_tools(EnhanceTool())
        plot2.xaxis.major_label_orientation = math.pi / 2

        source2 = ColumnDataSource(
            data={
                'x': xVals.flatten(),
                'y': yVals.flatten(),
                'covValues': [0 for i in covVals.flatten()]
            })

        self.logger.info('Creating initial secondary plot')
        plot2.rect(x='x',
                   y='y',
                   width=1,
                   height=1,
                   source=source2,
                   fill_color={
                       'field': 'covValues',
                       'transform': color_mapper
                   },
                   line_color=None)

        plot2.title = Title(text='Queued Covariance Submatrices',
                            align='center')

        plot2.add_layout(color_bar, 'right')

        # Creating a dictionary of distance difference matrices based off of
        # order they are loaded in
        self.logger.debug('Creating distance difference matrix mapping')
        matrixDict = {}
        for i, npy in enumerate(npyList):
            if i not in matrixDict.keys():
                matrixDict[str(i)] = npyList[i].flatten()

        # Python Callbacks
        # ------------------------------------------------------------------

        # Takes a flattened matrix and updates the plot to its values
        def patchMatrixValues(newMatrix, source=source):
            if (int(self.scale) \
                    != int(math.ceil(math.sqrt(newMatrix.shape[0])))):

                newMatrix, indexDict = self.rescaleMatrix(
                    newMatrix, self.scale)
                newMatrix = newMatrix.flatten()
            patch_id = [i for i in range(len(source.data['covValues']))]
            patch = newMatrix
            source.patch({'covValues': list(zip(patch_id, patch))})

        # Slider Callback
        # Changes the distance difference matrix displayed based off of the index
        # that the slider is set to
        def sliderCallback(attr, old, new):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            f = str(new)
            covValues = source.data['covValues']
            axesLength = math.sqrt(len(covValues))
            patchMatrixValues(matrixDict[f])
            plot.title.text = 'Distance Difference Matrix: ' + npyNameList[new]

        # Click callback for moving from distance difference matrices to
        # covariance submatrices
        def clickCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            start_time = time.time()
            axesLength = math.sqrt(len(source.data['covValues']))
            xCoord = math.floor(event.x - 0.5)
            yCoord = math.floor(event.y - 0.5)

            # Only accessing covariance submatrix if the click is not along
            # the diagonal
            if ((xCoord != yCoord) and (xCoord >= 0)
                    and (xCoord < axesLength + 1) and (yCoord >= 0)
                    and (yCoord < axesLength + 1)):
                # Handles coordinates "mirrored" across the diagonal
                if (xCoord > yCoord):
                    temp = xCoord
                    xCoord = yCoord
                    yCoord = temp
                coordString = '(' + str(xCoord) + ', ' + str(yCoord) + ')'
                # Handles submatrix access for non-scaled indices
                subMatrix = None
                if self.indexDict is None:
                    covIndex = invCovMapDict[coordString]
                    resPairString = '[' + coordString + ']'
                    subMatrix = cSubmatrix.generateSubmatrix(
                        covarianceMatrix,
                        covMapDict,
                        residuePairList=resPairString,
                        allResidues=False,
                        baseDirectory=None).flatten()
                    self.logger.debug('Submatrix for x=' + str(xCoord) \
                                       + ', y=' + str(yCoord) + ': ' \
                                       + str(subMatrix))
                # Handles submatrix access for scaled/mapped indices/ranges
                else:
                    resPairString = ''
                    for xIndex in self.indexDict[xCoord]:
                        for yIndex in self.indexDict[yCoord]:
                            if len(resPairString) > 0:
                                resPairString += ','
                            resPairString += '(' + str(xIndex) \
                                             + ', ' + str(yIndex) + ')'
                    resPairString = '[' + resPairString + ']'
                    if self.queueState == False:
                        subMatrixList = cSubmatrix.generateSubmatrix(
                            covarianceMatrix,
                            covMapDict,
                            residuePairList=resPairString,
                            allResidues=False,
                            baseDirectory=None,
                            scale=self.scale)
                        subMatrixArray = np.array(subMatrixList)
                        # Multiple submatrices case, takes the average of
                        # given submatrices
                        if len(subMatrixArray.shape) >= 3:
                            subMatrix = np.average(subMatrixArray, axis=0)
                        else:
                            subMatrix = subMatrixList
                    else:
                        self.logger.debug('Appending ' + str(resPairString) \
                                          + ' to queueList')
                        self.queueList.append([
                            int(xCoord + 1),
                            int(yCoord + 1),
                            str(resPairString)
                        ])
                        toQueueDiv.text += ' (' + str(xCoord+1) + ','\
                                        + str(yCoord+1)+'),'

                if self.queueState == False:
                    patchMatrixValues(subMatrix)

                    # Changing plot title name to reflect the covariance pair
                    # with which the covariance submatrix is plotted in respect to
                    xCoord += 1
                    yCoord += 1
                    displayString = '(' + str(xCoord) + ', ' + str(
                        yCoord) + ')'
                    plot.title.text = 'Covariance Submatrix: Residue Pair: ' \
                                      + displayString

            # TODO: When speed comparisons are done, remove the time printouts
            print('Time to compute submatrix: ' +
                  str(time.time() - start_time))

        # Distance Difference Matrix Display Callback
        # Shows current distance difference matrix if not already shown
        def ddCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            f = str(slider.value)
            patchMatrixValues(matrixDict[f])
            plot.title.text = 'Distance Difference Matrix: ' \
                              + npyNameList[int(f)]

        # Reset Button Callback
        # Resets display to the 0th index distance difference matrix
        def resetCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            slider.value = 0
            f = str(slider.value)
            patchMatrixValues(matrixDict[f])
            plot.title.text = 'Distance Difference Matrix: ' \
                              + npyNameList[0]

        # Forward Button Callback
        # Moves DD Index forward by 1 and displays DD matrix
        def forwardCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            if slider.value < len(matrixDict.keys()) - 1:
                slider.value = slider.value + 1
                f = str(slider.value)
                patchMatrixValues(matrixDict[f])
                plot.title.text = 'Distance Difference Matrix: ' \
                                  + npyNameList[int(f)]

        # Backward Button Callback
        # Moves DD Index backward by 1 and displays DD matrix
        def backwardCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            if slider.value > 0:
                slider.value = slider.value - 1
                f = str(slider.value)
                patchMatrixValues(matrixDict[f])
                plot.title.text = 'Distance Difference Matrix: ' + npyNameList[
                    int(f)]

        # Forward Queue Callback
        # Moves down the queue to display the next covariance submatrix
        def forwardQCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            if ((self.curQueue is None) and (len(self.queueMatrices) == 0)):
                return
            elif ((self.curQueue is None) and (len(self.queueMatrices) >= 0)):
                self.curQueue = 0
                patchMatrixValues(self.queueMatrices[self.curQueue], source2)
                plot2.title.text = 'Queued Covariance Submatrices: '\
                                   + 'Residue Pair: ' \
                                   + self.queueNameList[self.curQueue]
                indexDiv.text = 'Index: ' + str(self.curQueue)
            elif (self.curQueue >= len(self.queueMatrices)):
                return
            elif (self.curQueue < (len(self.queueMatrices) - 1)):
                self.curQueue += 1
                print('Acessing curQueue: ' + str(self.curQueue))
                print('len(self.queueMatrices): ' +
                      str(len(self.queueMatrices)))
                patchMatrixValues(self.queueMatrices[self.curQueue], source2)
                plot2.title.text = 'Queued Covariance Submatrices: '\
                                   + 'Residue Pair: ' \
                                   + self.queueNameList[self.curQueue]
                indexDiv.text = 'Index: ' + str(self.curQueue)

        # Backward Queue Callback
        # Moves up the queue to display the previous covariance submatrix
        def backwardQCallback(event):
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            plot.x_range.factors = [
                str(i) for i in self.scaledRangeDict.values()
            ]
            if ((self.curQueue is None) and (len(self.queueMatrices) == 0)):
                return
            elif ((self.curQueue is None) and (len(self.queueMatrices) >= 0)):
                self.curQueue = 0
                patchMatrixValues(self.queueMatrices[self.curQueue], source2)
                plot2.title.text = 'Queued Covariance Submatrices: '\
                                   + 'Residue Pair: ' \
                                   + self.queueNameList[self.curQueue]
                indexDiv.text = 'Index: ' + str(self.curQueue)
            elif (self.curQueue >= len(self.queueMatrices)):
                return
            elif (self.curQueue > 0):
                self.curQueue -= 1
                self.logger.debug('Accessing curQueue: ' + str(self.curQueue))
                self.logger.debug('len(self.queueMatrices): ' \
                                  + str(len(self.queueMatrices)))
                patchMatrixValues(self.queueMatrices[self.curQueue], source2)
                plot2.title.text = 'Queued Covariance Submatrices: '\
                                   + 'Residue Pair: ' \
                                   + self.queueNameList[self.curQueue]
                indexDiv.text = 'Index: ' + str(self.curQueue)

        # Queue Button Callback
        # Toggles queueing mode for residue pairs/ranges
        def queueCallback(event):
            # Turning on queuing
            if self.queueState == False:
                self.queueState = True
                toQueueDiv.text = 'Queued Covariance Submatrices:'
                statusDiv.text = 'Status: Queuing residue pairs'
            # Turning off queuing and then patching the covariance submatrices
            # to secondary plot
            else:
                self.queueState = False
                qList = self.queueList
                self.queueList = []
                # TODO: Bokeh doesn't update display until after loop runs
                statusDiv.text = 'Status: Computing covariance submatrices'
                for matrixPak in qList:
                    xCoord = int(matrixPak[0])
                    yCoord = int(matrixPak[1])
                    resPairString = str(matrixPak[2])
                    subMatrixArray = np.array(
                        cSubmatrix.generateSubmatrix(
                            covarianceMatrix,
                            covMapDict,
                            residuePairList=resPairString,
                            allResidues=False,
                            baseDirectory=None,
                            scale=self.scale))
                    # Multiple submatrices case, takes the average of
                    # given submatrices
                    if len(subMatrixArray.shape) >= 3:
                        subMatrix = np.average(subMatrixArray, axis=0)
                    else:
                        subMatrix = subMatrixList

                    self.queueMatrices.append(subMatrix)
                    patchMatrixValues(subMatrix, source2)

                    # Changing plot title name to reflect the covariance pair
                    # with which the covariance submatrix is plotted in respect
                    # to
                    xCoord += 1
                    yCoord += 1
                    displayString = '(' + str(xCoord) + ', ' + str(
                        yCoord) + ')'
                    self.queueNameList.append(displayString)
                    plot2.title.text = 'Queued Covariance Submatrix: ' \
                                      + 'Residue Pair: ' \
                                      + displayString
                    computedDiv.text = 'Computed Submatrices: ' \
                                       + str(sorted(set(self.queueNameList)))
                    totalNumberDiv.text = '/' + str(len(self.queueMatrices))
                statusDiv.text = 'Status: Submatrix computation complete. Idling'

        # "Enhances" the selected region by taking the range of residues and
        # redisplays the plot so it shows only this range of residues at the
        # given resolution
        def zoomSelectCallback(event, matrixType="dd"):
            geometry = event.geometry
            f = str(slider.value)
            # Retrieving the boundaries of the rectangular selection
            # The -0.5 offset accounts for the offset of each square from
            # the original axis
            x0 = math.floor(geometry['x0'] - 0.5)
            x1 = math.floor(geometry['x1'] - 0.5)
            y0 = math.floor(geometry['y0'] - 0.5)
            y1 = math.floor(geometry['y1'] - 0.5)

            # Retrieving the boundaries of the current matrix
            # (in terms of currently displayed coordinates)
            sourceDF = source.to_df()
            xi = min(sourceDF['x'])
            xf = max(sourceDF['x'])
            yi = min(sourceDF['y'])
            yf = max(sourceDF['y'])

            width = x1 - x0
            height = y1 - y0

            # Use these values to get information about what scale
            # the matrix is and is going to be
            # self.scale
            # self.covSize -> need to find size for distance difference
            #                 matrices and make a separate case for them?
            # Also need to figure out how to deal with asymmetric boundaries
            # where width/height are not equal
            # binSize - the number of units in a given bin
            axesSize = int(math.sqrt(len(list(matrixDict.values())[0])))
            if ((matrixType == "dd") or (matrixType is None)):
                matrix = matrixDict[str(slider.value)].reshape(
                    axesSize, axesSize)
            elif (matrixType == "covMatrix"):
                indexDiv = int(self.curQueue)
                matrix = self.queueMatrices[indexDiv].reshape(
                    axesSize, axesSize)

            binSize = int(math.ceil(axesSize / self.scale))
            if ((x0 + max(width, height)) <= axesSize / binSize):
                xUpperBound = x0 + max(width, height)
                xLowerBound = x0
            else:
                if ((x1 - max(width, height)) >= 0):
                    xUpperBound = x1
                    xLowerBound = x1 - max(width, height)
                else:
                    xUpperBound = int(axesSize / binSize)
                    xLowerBound = int(axesSize / binSize - x1)

            if ((y0 + max(width, height)) <= axesSize / binSize):
                yUpperBound = y0 + max(width, height)
                yLowerBound = y0
            else:
                if ((y1 - max(width, height)) >= 0):
                    yUpperBound = y1
                    yLowerBound = y1 - max(width, height)
                else:
                    yUpperBound = int(axesSize / binSize)
                    yLowerBound = int(axesSize / binSize - y1)

            if ((xUpperBound - xLowerBound) > (yUpperBound - yLowerBound)):
                yUpperBound = xUpperBound
                yLowerBound = xLowerBound
            if ((xUpperBound - xLowerBound) < (yUpperBound - yLowerBound)):
                xUpperBound = yUpperBound
                xLowerBound = yLowerBound

            zoomedMatrix = matrix[xLowerBound * binSize:xUpperBound * binSize,
                                  yLowerBound * binSize:yUpperBound * binSize]

            # Modifying axes labels to reflect the zoomedMatrix
            # Parsing the boundaries to determine the raw index range
            xIndexMax = int(self.scaledRangeDict[xUpperBound].split('-')[1])
            xIndexMin = int(self.scaledRangeDict[xLowerBound].split('-')[0])
            yIndexMax = int(self.scaledRangeDict[yUpperBound].split('-')[1])
            yIndexMin = int(self.scaledRangeDict[yLowerBound].split('-')[0])

            # Partitioning the elements into self.scale number of bins
            numElements = xIndexMax - xIndexMin
            xIndexDict = self.partitionIndices(numElements,
                                               self.scale,
                                               offset=xIndexMin)
            yIndexDict = self.partitionIndices(numElements,
                                               self.scale,
                                               offset=yIndexMin)

            xRangeDict = self.serializeIndexDict(xIndexDict)
            yRangeDict = self.serializeIndexDict(yIndexDict)

            plot.x_range.factors = [i for i in xRangeDict.values()]
            plot.y_range.factors = [i for i in yRangeDict.values()]

            zoomedMatrix = zoomedMatrix.flatten()
            patchMatrixValues(zoomedMatrix, source)

        # ------------------------------------------------------------------

        # Creating buttons and linking them to their corresponding callbacks

        # Buttons to navigate distance difference matrices
        buttonBack = Button(label="Back", button_type="success")
        buttonBack.on_event(ButtonClick, backwardCallback)
        buttonDD = Button(label="Show Distance Difference",
                          button_type="success")
        buttonDD.on_event(ButtonClick, ddCallback)
        buttonForward = Button(label="Forward", button_type="success")
        buttonForward.on_event(ButtonClick, forwardCallback)

        buttonBar = row(buttonBack, buttonDD, buttonForward)

        buttonReset = Button(label="Reset", button_type="success")
        buttonReset.on_event(ButtonClick, resetCallback)

        # Slider to also navigate distance difference matrices
        slider = Slider(start=0,
                        end=len(npyList) - 1,
                        value=0,
                        step=1,
                        title="index")
        slider.on_change('value', sliderCallback)

        # Zoom button for distance difference matrices/non-queued
        # covariance submatrices
        plot.on_event(SelectionGeometry, zoomSelectCallback)
        plot2.on_event(SelectionGeometry, zoomSelectCallback)

        # Creating a layout from plot elements
        self.queueList = []
        self.queueState = False
        self.curQueue = None
        self.queueMatrices = []
        self.queueNameList = []
        plot.on_event('tap', clickCallback)

        # Queue Buttons
        queueButton = Button(label="Queue", button_type="success")
        queueButton.on_event(ButtonClick, queueCallback)
        qBar = row(queueButton)

        # Buttons to navigate queued covariance submatrices
        qButtonBack = Button(label="Back", button_type="success")
        qButtonBack.on_event(ButtonClick, backwardQCallback)

        qButtonForward = Button(label="Forward", button_type="success")
        qButtonForward.on_event(ButtonClick, forwardQCallback)
        qNavBar = row(qButtonBack, qButtonForward)

        # Div Widgets to show which submatrix is displayed
        indexDiv = Div(text="""Index: N/A""", \
                           width=70, height=25)
        totalNumberDiv = Div(text="""/0""",\
                             width=100, height=25)
        indexDivBar = row(indexDiv, totalNumberDiv)

        # Div Widget to show which residue pairs are queued
        toQueueDiv = Div(text="""Queued Covariance Submatrices:""", \
                      width=600, height=50)

        # Div Widget to show which residue pairs are computed
        computedDiv = Div(text="""Computed Submatrices:""", \
                       width=600, height=50)

        # Div Widget to show
        statusDiv = Div(text="""Status: Nothing Queued""", \
                        width=600, height=25)

        testTitle = Title(text='Test Title', align='center')

        layout = row(
            column(plot, qBar, buttonBar, slider, buttonReset),
            column(plot2, qNavBar, statusDiv, indexDivBar, toQueueDiv,
                   computedDiv))

        # Adding the plot to the server's document
        server_doc = doc
        server_doc.add_root(layout)
        server_doc.title = "Distance Difference App"
Exemplo n.º 22
0
    else:
        return byRow(source.data['ID'].iloc[source.selected.indices[0]])
        
    

menu = [('Publication Paper', 'pub'), ('Dataset', 'data'), ('All', '')]
nmenu = RadioButtonGroup(labels=['Publication', 'Dataset', 'Keyword'], active=0)
how = ['Jaccard', 'Cosine', 'Hopcroft', 'Adamic-Adar']
nhow = RadioButtonGroup(labels=['Jaccard', 'Cosine', 'Hopcroft', 'Adamic-Adar'], active=0)
nhow.on_change('active', lambda attr, old, new: cHow())

search = TextInput(title="Search Archive")
rs_search = AutocompleteInput(title="Recommend by Keyword", completions=all_keywords)

button = Button(label="Search", button_type="warning")
button.on_event(ButtonClick, update)
rs_button = Button(label="Recommend", button_type="success")
rs_button.on_event(ButtonClick, rs_update)

columns = [
    TableColumn(field="ID", title="ID", width=20),
    TableColumn(field="title", title="Title", width=300, formatter=HTMLTemplateFormatter(template=template)),
    TableColumn(field="description", title="Description", width=200, formatter=HTMLTemplateFormatter(template=template))
]
data_table = DataTable(source=source, columns=columns, width=800)
rs_columns = [
    TableColumn(field="data_set_id", title="Data ID", width=20),
    TableColumn(field="rs_score", title="RS Score", width=20),
    TableColumn(field="rs_title", title="Data Title", width=300, formatter=HTMLTemplateFormatter(template=template)),
    TableColumn(field="rs_description", title="Data Description", width=100, formatter=HTMLTemplateFormatter(template=template))
]
from bokeh.events import ButtonClick
from bokeh.models import Button

button = Button()


def callback(event):
    print('Python:Click')


print('in here')
button.on_event(ButtonClick, callback)
Exemplo n.º 24
0
    mapplot.min_border_top = 0
    mapplot.sizing_mode = 'scale_both'
    layout1.children = [
        column(row(widgetbox(button), widgetbox(chance_text)),
               row(widgetbox(text_input), widgetbox(country_text)),
               row(widgetbox(pre), mapplot, widgetbox(pre)))
                    ]
    layout2 = tab2_plotting()

    tabs.tabs = [Panel(child=layout1, title='My luck'),
                 Panel(child=layout2, title='My life')]


### WIDGETS
button = Button(label="How lucky am I", width=130)
button.on_event(ButtonClick, luck)

text_input = TextInput(value="I was born in", title="", width=130)
world = data_model.return_world()
mapplot = world[world.name == 'Japan'].plot_bokeh(
    figsize=(900, 600),
    simplify_shapes=5000,
    xlim=(-170, 170),
    ylim=(-40, 70),
    show_colorbar=False,
    color='white',
    line_color='white',
    tile_provider='CARTODBPOSITRON',
    show_figure=False,
    toolbar_location=None,
    xlabel=None,
Exemplo n.º 25
0
slider = Slider(start=years[0],
                end=years[-1],
                value=years[0],
                step=1,
                title="Year")
slider.on_change('value', slider_update)

callback_id = None


def animate():
    global callback_id
    if button.label == '► Play':
        button.label = '❚❚ Pause'
        callback_id = curdoc().add_periodic_callback(animate_update, 200)
    else:
        button.label = '► Play'
        curdoc().remove_periodic_callback(callback_id)


button = Button(label='► Play', width=60)
button.on_event('button_click', animate)

layout = layout([
    [plot],
    [slider, button],
], sizing_mode='scale_width')

curdoc().add_root(layout)
curdoc().title = "Gapminder"
Exemplo n.º 26
0
"""


def create_hover_tool(list_of_keys):
    tooltips = [('date', '@date{%F %T}')] + [(s, '@' + s)
                                             for s in list_of_keys]
    return HoverTool(tooltips=tooltips,
                     formatters={'@date': 'datetime'},
                     mode='mouse')


remote_ip_text = TextInput(title="Remote IP", value=DEFAULT_REMOTE_IP)
self_ip_text = TextInput(title="Self IP", value=DEFAULT_SELF_IP)

route_button = Button(label="Route telemetry")
route_button.on_event(ButtonClick, route_telemetry_command)

raw_command_text = TextInput(title="Raw command (hex)")

send_raw_command_button = Button(label="Send raw command")
send_raw_command_button.on_event(ButtonClick, send_raw_command)

command_info_div = Div(text="")

command_block = column(remote_ip_text, self_ip_text, route_button,
                       raw_command_text, send_raw_command_button,
                       command_info_div)

gps_info_div = Div(text="")
pps_info_div = Div(text="")
Exemplo n.º 27
0
def main():
    # set up main bokeh figure
    p = figure(x_range=(0, 10),
               y_range=(0, 10),
               tools=[],
               title='Draw points in the network')
    p.background_fill_color = 'lightgrey'

    # start off with sample points and their associated flows
    source = ColumnDataSource({
        'x': [2, 7, 5, 8],
        'y': [2, 2, 6, 1],
        'flow': ['-2', '-5', '8', '-1']
    })

    renderer = p.scatter(x='x', y='y', source=source, color='blue', size=10)
    columns = [
        TableColumn(field="x", title="x"),
        TableColumn(field="y", title="y"),
        TableColumn(field='flow', title='flow')
    ]
    table = DataTable(source=source,
                      columns=columns,
                      editable=True,
                      height=200)

    draw_tool = PointDrawTool(renderers=[renderer], empty_value='1')
    p.add_tools(draw_tool)
    p.toolbar.active_tap = draw_tool

    titletextbox = Div(
        text=
        "<h2>Objective: minimize construction cost of network<p>Construction cost is based on number of pipes and distance between nodes.<br>Additional constraints imposed: flows in network must be balanced.<br></h2>",
        width=1100,
        height=150)
    textbox = Div(text="", width=200, height=100)
    floating = 1.
    fixed = 0.
    button = Button(label='Solve Network')

    button.on_event(
        ButtonClick,
        partial(button_click_event, source=source, textbox=textbox, figure=p))

    p.on_event(
        PanEnd,
        partial(button_click_event, source=source, textbox=textbox, figure=p))

    # set up sliders
    lumpSumCost = Slider(title="Fixed cost pipe",
                         value=0.0,
                         start=0.0,
                         end=500.0,
                         step=50)
    floatingCost = Slider(title="Floating cost pipe",
                          value=1.0,
                          start=0.0,
                          end=500.0,
                          step=10.)

    for w in [lumpSumCost, floatingCost]:
        w.on_change(
            'value',
            partial(update_data,
                    source=source,
                    textbox=textbox,
                    figure=p,
                    lumpSumCost=lumpSumCost,
                    floatingCost=floatingCost))

    # create page layout
    curdoc().add_root(
        Column(
            titletextbox,
            Row(Column(p, table, width=800),
                Column(lumpSumCost, floatingCost, button, textbox,
                       width=300))))
    curdoc().title = "Network"
Exemplo n.º 28
0
# Pan events
p.js_on_event(events.Pan,      display_event(div, attributes=pan_attributes))
p.js_on_event(events.PanStart, display_event(div, attributes=point_attributes))
p.js_on_event(events.PanEnd,   display_event(div, attributes=point_attributes))

# Pinch events
p.js_on_event(events.Pinch,      display_event(div, attributes=pinch_attributes))
p.js_on_event(events.PinchStart, display_event(div, attributes=point_attributes))
p.js_on_event(events.PinchEnd,   display_event(div, attributes=point_attributes))


## Register Python event callbacks

# Button event
button.on_event(events.ButtonClick, print_event())

# LOD events
p.on_event(events.LODStart, print_event())
p.on_event(events.LODEnd,   print_event())

# Point events

p.on_event(events.Tap,       print_event(attributes=point_attributes))
p.on_event(events.DoubleTap, print_event(attributes=point_attributes))
p.on_event(events.Press,     print_event(attributes=point_attributes))

# Mouse wheel event
p.on_event(events.MouseWheel, print_event(attributes=wheel_attributes))

# Mouse move, enter and leave
Exemplo n.º 29
0
    Evalue l'ensemble des filtres actifs
    """
    yearChoose = f_year.active
    etatChoose = f_etat.active
    quartierChoose = f_quartier.active
    df_data.query(yearChoose, etatChoose, quartierChoose)
    bd_source.data.update(df_data.bd.to_dict(orient='list'))
    qt_source.data.update(df_data.qt.to_dict(orient='list'))
    pj_source.data.update(df_data.proj.to_dict(orient='list'))
    et_source.data.update(df_data.etat.to_dict(orient='list'))


f_year.on_change('active', update)
f_etat.on_change('active', update)
f_quartier.on_change('active', update)
f_reset.on_event(ButtonClick, reset)

########################## GRAPHS #########################

g_map = mapPlot(bd_source, qt_source)
g_bar = barPlot(pj_source)
g_stack = stackPlot(et_source)

graphs = column(g_map,
                row(g_bar, g_stack, sizing_mode="stretch_width"),
                sizing_mode="stretch_width")

########################## LAYOUT #########################

layout = column(m_header,
                row(sidebar, graphs, m_blank),