Esempio n. 1
0
    view = data.loc[chosen_timeline == chosen_slider.value]
    print 'Parameter button option ' + str(new) + ' selected.'
    global param_choice
    if str(new) == "0":
        param_choice = data['resolution2']
    if str(new) == "1":
        param_choice = data['percentageofpote1']
    if str(new) == "2":
        param_choice = data['cloud_score_aver2']
    if str(new) == "3":
        param_choice = data['gelbstoffmax0']
    colors = ["#%02x%02x%02x" % (int(255/(r+1)), 100, 100) for r in param_choice]
    x = view['scene_lat']
    y = view['scene_lon']
    source.data = dict(x=x, y=y, c=colors)
param_button_group.on_click(param_radio_handler)

#OK
def time_radio_handler(new):
    global param_choice
    global inputs
    global chosen_slider
    global chosen_timeline
    print 'Time button option ' + str(new) + ' selected.'
    if str(new) == "0":
        chosen_slider = year_slider
        chosen_timeline = data['year']
    if str(new) == "1":
        chosen_slider = month_slider
        chosen_timeline = data['yearmonth']
    if str(new) == "2":
Esempio n. 2
0
def clear_plot():
    source_data.data = dict(x=[], y=[])
    pred_data.data = dict(x=[], y=[])
    source_bars.data = dict(y=[], right=[])
    pred_line.data = dict(y=[], x=[])
    tsne.data = dict(y=[], x=[])


def update_plot_signature(attr, old, new):
    # print(attr, old, new)
    update_plot()


# Disable controls initially
change_model()

plot_run.on_click(update_plot)
plot_clear.on_click(clear_plot)
ctl_model.on_click(change_model)
ctl_feat_reduce.on_click(update_plot)
ctl_kernel.on_click(update_plot)


# Page Layout
col_inputs = column(plot_ctls, ctl_inputs, disp_disclaimer)
row_plots = row(plot_mood_scatter, plot_mood_bar)
row_page = row(col_inputs, column(row_plots, plot_feature_scatter), column(disp_features, disp_score), width=1200)
curdoc().add_root(row_page)
curdoc().title = "Daylio Data Display"
Esempio n. 3
0
    top_five_data_source.data = top_five_dict

    bot_five = df.sort_values(card_type).head(5)[[
        'STATION', card_type, 'LINES'
    ]]
    bot_five_dict = dict(stations=bot_five['STATION'],
                         lines=bot_five['LINES'],
                         percents=bot_five[card_type],
                         rank=list(range(1, 6)))
    bot_five_data_source.data = bot_five_dict


## Add widgets and corresponding callback functions
price_period_buttons = RadioButtonGroup(
    active=0, labels=['Period 1', 'Period 2', 'Period 3', 'Period 4'])
price_period_buttons.on_click(callback_change_dataframe)

metrocard_type_buttons = RadioButtonGroup(
    active=0, labels=['Full Fare', '7-Day Unlimited', '30-Day Unlimited'])
metrocard_type_buttons.on_click(callback_change_dataframe)

line_list = [
    'ALL', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'J', 'L', 'M', 'N', 'Q', 'R',
    'S', 'Z', '1', '2', '3', '4', '5', '6', '7'
]
subway_line_select = Select(title="Subway Line:",
                            value="ALL",
                            options=line_list)
subway_line_select.on_change("value", callback_subway_line_filter)

## Add table showing price hike information
Esempio n. 4
0
                         'Weakness', 'Atrophy', 'Cramps',
                         'Fasciculations', "Gait changes"])

# onset radio button
def onset_loc_handler(new):
    print ('Radio button option' + str(new) + ' selected.')
pp_onset = Paragraph(text="""Onset Neuron Group""", width=250, height=15)
onset_loc = RadioButtonGroup(labels=["Bulbar", "Spinal", "Both", "*Unk"], active=3)
#onset_loc.on_click(onset_loc_handler)

# riluzole radio button
def riluzole_handler(new):
    print ('Radio button option ' + str(new) + ' selected.')
pp_riluzole = Paragraph(text="""Subject used Riluzole""", width=250, height=15)
riluzole = RadioButtonGroup(labels=["No", "Yes", "*Unk"], active=2)
riluzole.on_click(onset_loc_handler)

# caucasian radio button
def caucasian_handler(new):
    print ('Radio button option ' + str(new) + ' selected.')
pp_caucasian = Paragraph(text="""Race Caucasian""", width=250, height=15)
caucasian = RadioButtonGroup(labels=["No", "Yes", "*Unk"], active=2) 
caucasian.on_click(caucasian_handler)

# sex radio button
def sex_handler(new):
    print ('Radio button option ' + str(new) + ' selected.')
pp_sex = Paragraph(text="""Sex""", width=250, height=15)
sex = RadioButtonGroup(labels=["Female", "Male", "*Unk"], active=2)
sex.on_click(sex_handler)
Esempio n. 5
0
plt.legend.label_text_font_size = "18px"
plt.legend.click_policy="mute"

# Make and format tooltip
hover = HoverTool(tooltips=[
			("# of Institutions", '@num_insts')
        ])
plt.add_tools(hover)

# Format axes and labels
plt.xaxis.major_label_orientation = np.pi/4
plt.xaxis.axis_label_text_font_size = "18px"
plt.xaxis.major_label_text_font_size = "18px"

plt.yaxis.axis_label = "Number of Female Students / Institution"
plt.yaxis.axis_label_text_font_size = "18px"
plt.yaxis.major_label_text_font_size = "18px"

# Get rid of stupid Bokeh logo
plt.toolbar.logo = None

# Set callback function for the radio button group
radio_button_group.on_click(gather_data)

# Define layout of glyphs on the page
layout = column(div_title, row(div_RadGroup, radio_button_group), plt, p1, p2, p3)
curdoc().add_root(layout)

# Set title
curdoc().title = "Visualization 3"
Esempio n. 6
0
##### COLOR BAND MAPPINGS

redText = PreText(text="""Red:""", width=60, height=15)
redBandMapping = RadioButtonGroup(labels=possible_bands, active=2, name="Red")
greenText = PreText(text="""Green:""", width=60, height=15)
greenBandMapping = RadioButtonGroup(labels=possible_bands,
                                    active=1,
                                    name="Green")
blueText = PreText(text="""Blue:""", width=60, height=15)
blueBandMapping = RadioButtonGroup(labels=possible_bands,
                                   active=0,
                                   name="Blue")

##### COLOR BAND MAPPING INTERACTIONS

redBandMapping.on_click(change_band_red)
greenBandMapping.on_click(change_band_green)
blueBandMapping.on_click(change_band_blue)

##### BUTTON TO MATERIALISE CHANGES

renderButton = Button(label="Confirm Mappings", button_type="success")
renderButton.on_click(render)

##### TIME SLIDER

time_slider = Slider(start=1,
                     end=12,
                     value=1,
                     step=1,
                     title="Image Number(between 1 and 12)")
Esempio n. 7
0
""")




oo = column(children=[exptime]) 
pp = column(children=[distance, radius, semimajor, exozodi]) 
qq = column(children=[instruction0, text_input, instruction1, format_button_group, instruction2, link_box]) 

observation_tab = Panel(child=oo, title='Observation')
planet_tab = Panel(child=pp, title='Planet')
download_tab = Panel(child=qq, title='Download')

for w in [text_input]: 
    w.on_change('value', change_filename)
format_button_group.on_click(i_clicked_a_button) 


inputs = Tabs(tabs=[ planet_tab, observation_tab, download_tab ])
curdoc().add_root(row(children=[inputs, snr_plot])) 

#curdoc().theme = Theme(json=yaml.load("""
#attrs:
#    Figure:
#        background_fill_color: '#2F2F2F'
#        border_fill_color: '#2F2F2F'
#        outline_line_color: '#444444'
#    Axis:
#        axis_line_color: "white"
#        axis_label_text_color: "white"
#        major_label_text_color: "green"
Esempio n. 8
0
    def do_layout(self):
        """
        generates the overall layout by creating all the widgets, buttons etc and arranges
        them in rows and columns
        :return: None
        """
        self.source = self.generate_source()
        tab_plot = self.generate_plot(self.source)
        multi_select = MultiSelect(title="Option (Multiselect Ctrl+Click):",
                                   value=self.active_country_list,
                                   options=countries,
                                   height=500)
        multi_select.on_change('value', self.update_data)
        tab_plot.on_change('active', self.update_tab)
        radio_button_group_per_capita = RadioButtonGroup(
            labels=["Total Cases", "Cases per Million"],
            active=0 if not self.active_per_capita else 1)
        radio_button_group_per_capita.on_click(self.update_capita)
        radio_button_group_scale = RadioButtonGroup(
            labels=[Scale.log.name.title(),
                    Scale.linear.name.title()],
            active=self.active_y_axis_type.value)
        radio_button_group_scale.on_click(self.update_scale_button)
        radio_button_group_df = RadioButtonGroup(labels=[
            Prefix.confirmed.name.title(),
            Prefix.deaths.name.title(),
            Prefix.recovered.name.title(),
        ],
                                                 active=int(
                                                     self.active_case_type))
        radio_button_group_df.on_click(self.update_data_frame)
        refresh_button = Button(label="Refresh Data",
                                button_type="default",
                                width=150)
        refresh_button.on_click(load_data_frames)
        export_button = Button(label="Export Url",
                               button_type="default",
                               width=150)
        export_button.on_click(self.export_url)
        slider = Slider(start=1,
                        end=30,
                        value=self.active_window_size,
                        step=1,
                        title="Window Size for rolling average")
        slider.on_change('value', self.update_window_size)
        radio_button_average = RadioButtonGroup(
            labels=[Average.mean.name.title(),
                    Average.median.name.title()],
            active=self.active_average)
        radio_button_average.on_click(self.update_average_button)
        plot_variables = [
            self.active_plot_raw, self.active_plot_average,
            self.active_plot_trend
        ]
        plots_button_group = CheckboxButtonGroup(
            labels=["Raw", "Averaged", "Trend"],
            active=[i for i, x in enumerate(plot_variables) if x])
        plots_button_group.on_click(self.update_shown_plots)

        world_map = self.create_world_map()
        link_div = Div(
            name="URL",
            text=
            fr'Link <a target="_blank" href="{self.url}">Link to this Plot</a>.',
            width=300,
            height=10,
            align='center')
        footer = Div(
            text=
            """Covid-19 Dashboard created by Andreas Weichslgartner in April 2020 with python, bokeh, pandas, 
            numpy, pyproj, and colorcet. Source Code can be found at 
            <a href="https://github.com/weichslgartner/covid_dashboard/">Github</a>.""",
            width=1600,
            height=10,
            align='center')
        self.generate_table_cumulative()
        columns = [
            TableColumn(field="name", title="Country"),
            TableColumn(field="number_rolling",
                        title="daily avg",
                        formatter=NumberFormatter(format="0.")),
            TableColumn(field="number_daily",
                        title="daily raw",
                        formatter=NumberFormatter(format="0."))
        ]
        top_top_14_new_header = Div(text="Highest confirmed (daily)",
                                    align='center')
        top_top_14_new = DataTable(source=self.top_new_source,
                                   name="Highest confirmed(daily)",
                                   columns=columns,
                                   width=300,
                                   height=380)
        self.generate_table_new()
        columns = [
            TableColumn(field="name", title="Country"),
            TableColumn(field="number",
                        title="confirmed(cumulative)",
                        formatter=NumberFormatter(format="0."))
        ]

        top_top_14_cum_header = Div(text="Highest confirmed (cumulative)",
                                    align='center')
        top_top_14_cum = DataTable(source=self.top_total_source,
                                   name="Highest confirmed(cumulative)",
                                   columns=columns,
                                   width=300,
                                   height=380)
        self.layout = layout([
            row(
                column(tab_plot, world_map),
                column(top_top_14_new_header, top_top_14_new,
                       top_top_14_cum_header, top_top_14_cum),
                column(link_div, row(refresh_button, export_button),
                       radio_button_group_df, radio_button_group_per_capita,
                       plots_button_group, radio_button_group_scale, slider,
                       radio_button_average, multi_select),
            ),
            row(footer)
        ])

        curdoc().add_root(self.layout)
        curdoc().title = "Bokeh Covid-19 Dashboard"
            for j in gpa_list:
                if j == i and years_list[
                        count_total] == '2017' and dept_student_list[
                            count_total] == new:
                    count_part = count_part + 1
                count_total = count_total + 1
            list_2017_new.append(count_part)
        data = {}
        data['gpa'] = gpa
        data['2015'] = list_2015_new
        data['2016'] = list_2016_new
        data['2017'] = list_2017_new
        source.data = data


btnGroupLetters.on_click(functools.partial(onclick, name='Letters'))
refresh.on_click(functools.partial(onclick, name='refresh'))
btnGroupTitle.on_click(functools.partial(onclick, name='Title'))
btnGroupDept.on_click(functools.partial(onclick, name='Dept'))
dept_select.on_change('value', onTableMasterSelect)

layout_query = layout([
    [widgetbox(btnGroupLetters, width=1000)],
    [widgetbox(btnGroupTitle),
     widgetbox(btnGroupDept)],
    [
        widgetbox(title_input),
        widgetbox(paragraph, optionGroup, width=100),
        widgetbox(dept_input)
    ],
    [widgetbox(refresh, width=100)],
p_title.axis.visible = None

# put Cylance Logo in
# p_logo = figure(toolbar_location=None, tools = "lasso_select", x_range=(0,1), y_range=(0,1), plot_width=520, plot_height=200)
# img = mpimg.imread("cylance_logo.png")
# p_logo.image_url(url=["cylance_logo.png"], x=0, y=0)
# p_logo.background_fill_color = "black"
# p_logo.border_fill_color = "black"
# p_logo.grid.grid_line_color = "black"
# p_logo.outline_line_color = "black"


# radio button group for uploading file
radio_group = RadioButtonGroup(labels=["NO-SPLIT", "SPLIT", "START"], button_type="success")
radio_group.width = 500
radio_group.on_click(_fit_util)

# text for console output
text_input = TextInput(value="", title="CONSOLE")
text_input.width = 500

cluster_stats = Div(
    render_as_text=False,
    text=generate_display_string("", name="Cluster Statistics", height=100)
)
cluster_stats.width = 500
cluster_stats.height = 100

cluster_commonality = Div(
    render_as_text=False,
    text=generate_display_string("")
Esempio n. 11
0
p_title.axis.visible = None

# put Cylance Logo in
# p_logo = figure(toolbar_location=None, tools = "lasso_select", x_range=(0,1), y_range=(0,1), plot_width=520, plot_height=200)
# img = mpimg.imread("cylance_logo.png")
# p_logo.image_url(url=["cylance_logo.png"], x=0, y=0)
# p_logo.background_fill_color = "black"
# p_logo.border_fill_color = "black"
# p_logo.grid.grid_line_color = "black"
# p_logo.outline_line_color = "black"

# radio button group for uploading file
radio_group = RadioButtonGroup(labels=["NO-SPLIT", "SPLIT", "START"],
                               button_type="success")
radio_group.width = 500
radio_group.on_click(_fit_util)

# text for console output
text_input = TextInput(value="", title="CONSOLE")
text_input.width = 500

cluster_stats = Div(render_as_text=False,
                    text=generate_display_string("",
                                                 name="Cluster Statistics",
                                                 height=100))
cluster_stats.width = 500
cluster_stats.height = 100

cluster_commonality = Div(render_as_text=False,
                          text=generate_display_string(""))
cluster_commonality.width = 500
def main():
    """
    The main function only describes both graphical and comunication parts of the app.
    It creates and initializes all necessary widgets. At the end the function calls
    doc.add_root to display the objects on a browser
    :return:
    """

    # Quasi constant
    FrequencyRange = np.logspace(0, 5, 1000)
    doc = curdoc()

    # ========================== GRAPHICAL PART ================================

    # CREATE ALL PLOTS:
    Input = figure(title="", tools="", width=500, height=500)

    Graph = VibroP_GraphObject([
        "Wave Velocities", "Wave Velocities plus Limit Frequencies",
        "Modes in Band", "Modal Density", "Modal Overlap Factor",
        "Maximum Element Size (FEM)"
    ],
                               FrequencyRange,
                               Width=950,
                               Height=650)

    Graph.defineContainers([
        "WaveVelocity", "WaveVElocityLimitFreq", "ModesInBand", "ModalDensity",
        "ModalOverlapFactor", "MaxElementSize"
        "EigenFrequency"
    ])

    # CREATE TABLES:
    # ........................ Elastic Modulus table ...........................
    ELASTIC_MODULUS_TITEL = Div(text="""ELASTIC MODULUS:""")
    ElasticModulus = VibroP_InteractiveTable(TableName="ELASTIC MODULUS",
                                             Rows=1,
                                             Columns=3)

    ElasticModulus.setTitels([[EMODUL_X, EMODUL_Y, EMODUL_Z]])

    OrthotropicData = [["1.10E+10", "3.67E+08", "3.67E+08"]]
    IsotropicData = [["1.10E+10", "1.10E+10", "1.10E+10"]]
    ElasticModulus.setValues(OrthotropicData)
    ElasticModulus.addBuffer(BufferName="DefaultIsotropic",
                             BufferData=IsotropicData)

    ElasticModulus.addBuffer(BufferName="DefaultOrthotropic",
                             BufferData=OrthotropicData)

    ElasticModulus.addBuffer(BufferName="GeneralIsotropic",
                             BufferData=IsotropicData)

    ElasticModulus.addBuffer(BufferName="GeneralOrthotropic",
                             BufferData=OrthotropicData)

    ElasticModulus.addBuffer(BufferName="Input", BufferData=OrthotropicData)

    # ........................ Shear Modulus table .............................
    SHEAR_MODULUS_TITEL = Div(text="""SHEAR MODULUS:""")
    ShearModulus = VibroP_InteractiveTable(TableName="SHEAR MODULUS",
                                           Rows=1,
                                           Columns=3)

    ShearModulus.setTitels([[EMODUL_XY, EMODUL_XZ, EMODUL_YZ]])
    OrthotropicData = [["6.90E+08", "6.90E+08", "6.90E+07"]]
    IsotropicData = [["6.90E+08", "6.90E+08", "6.90E+08"]]

    ShearModulus.setValues(OrthotropicData)

    ShearModulus.addBuffer(BufferName="DefaultIsotropic",
                           BufferData=IsotropicData)

    ShearModulus.addBuffer(BufferName="DefaultOrthotropic",
                           BufferData=OrthotropicData)

    ShearModulus.addBuffer(BufferName="GeneralIsotropic",
                           BufferData=IsotropicData)

    ShearModulus.addBuffer(BufferName="GeneralOrthotropic",
                           BufferData=OrthotropicData)

    ShearModulus.addBuffer(BufferName="Input", BufferData=OrthotropicData)

    # ........................ Poissons ratios ................................
    POISSON_RATIO_TITEL = Div(text="""POISSON'S RATIOS:""")
    PoissonRatios = VibroP_InteractiveTable(TableName="POISSON'S RATIOS",
                                            Rows=2,
                                            Columns=3)

    PoissonRatios.setTitels(
        [[POISSON_RATIO_XY, POISSON_RATIO_XZ, POISSON_RATIO_YZ],
         [
             POISSON_RATIO_YX + "\t(auto)", POISSON_RATIO_ZX + "\t(auto)",
             POISSON_RATIO_ZY + "\t(auto)"
         ]])

    PoissonRatios.setDisabled(1, 0, True)
    PoissonRatios.setDisabled(1, 1, True)
    PoissonRatios.setDisabled(1, 2, True)

    DataIsotropic = [["0.42", "0.42", "0.42"], ["0.42", "0.42", "0.42"]]

    DataOrthotropic = [["0.42", "0.42", "0.3"], ["0.014", "0.014", "0.3"]]

    PoissonRatios.setValues(DataOrthotropic)

    PoissonRatios.addBuffer(BufferName="DefaultIsotropic",
                            BufferData=DataIsotropic)

    PoissonRatios.addBuffer(BufferName="DefaultOrthotropic",
                            BufferData=DataOrthotropic)

    PoissonRatios.addBuffer(BufferName="GeneralIsotropic",
                            BufferData=DataIsotropic)

    PoissonRatios.addBuffer(BufferName="GeneralOrthotropic",
                            BufferData=DataOrthotropic)

    PoissonRatios.addBuffer(BufferName="Input", BufferData=DataOrthotropic)

    # ........................ Material Properties table .......................
    MATERIALS_TITEL = Div(text="""FURTHER MATERIAL PROPERTIES:""")
    MaterialProperties = VibroP_InteractiveTable(
        TableName="MATERIAL PROPERTIES", Rows=1, Columns=2)

    MaterialProperties.setTitels([["Density", "Loss Factor"]])

    Data = [["450.0", "0.012"]]
    MaterialProperties.setValues(Data)

    MaterialProperties.setValues(Data)

    MaterialProperties.addBuffer(BufferName="DefaultIsotropic",
                                 BufferData=Data)

    MaterialProperties.addBuffer(BufferName="DefaultOrthotropic",
                                 BufferData=Data)

    MaterialProperties.addBuffer(BufferName="General", BufferData=Data)

    MaterialProperties.addBuffer(BufferName="Input", BufferData=Data)

    # ........................ Geometry table .......................
    GEOMETRY_TITEL = Div(text="""GEOMETRY:""")
    GeometryProperties = VibroP_InteractiveTable(TableName="GEOMETRY",
                                                 Rows=1,
                                                 Columns=3)

    GeometryProperties.setTitels(
        [["Length", "Width", "Thicknesses of the layers*"]])

    Data = [["2.5", "3.0", "0.027"]]
    GeometryProperties.setValues(Data)

    GeometryProperties.setValues(Data)

    GeometryProperties.addBuffer(BufferName="DefaultIsotropic",
                                 BufferData=Data)

    GeometryProperties.addBuffer(BufferName="DefaultOrthotropic",
                                 BufferData=Data)

    GeometryProperties.addBuffer(BufferName="General", BufferData=Data)

    GeometryProperties.addBuffer(BufferName="Input", BufferData=Data)

    ElasticModulus.fillTableWithBufferData("DefaultOrthotropic")
    ShearModulus.fillTableWithBufferData("DefaultOrthotropic")
    PoissonRatios.fillTableWithBufferData("DefaultOrthotropic")
    MaterialProperties.fillTableWithBufferData("DefaultOrthotropic")
    GeometryProperties.fillTableWithBufferData("DefaultOrthotropic")

    Tables = {
        "ElasticModulus": ElasticModulus,
        "ShearModulus": ShearModulus,
        "PoissonRatios": PoissonRatios,
        "MaterialProperties": MaterialProperties,
        "GeometryProperties": GeometryProperties
    }

    # CREATE BUTTONS:
    SetDefaultButton = Button(label="Default",
                              button_type="success",
                              width=100)

    ApplyButton = Button(label="Apply", button_type="success", width=100)

    # PrintReport = Button( label = "Print Report",
    #                       button_type = "primary",
    #                       width = 100 )

    ShowInput = Button(label="Show Input", button_type="success", width=100)

    ModeRadioButtons = RadioButtonGroup(
        labels=["Orthotropic Material", "Isotropic Material"],
        width=500,
        active=0)

    LayersInfo = VibroP_Message(Color="black",
                                Size=2,
                                MessageHeader="Number of layers: ")

    WarningMessage = VibroP_Message(Color="red",
                                    Size=3,
                                    MessageHeader="Warning: ")

    Info = Div(text="*Thicknesses of top to center layer separated by "
               "semicolon or space: <br>"
               "&nbsp;Symmetric cross section with odd number of layers"
               " and crosswise layup assumed.",
               render_as_text=False,
               width=500,
               height=40)

    Scheme = Div(
        text=
        "<img src='/Vibroacoustic_plates/static/images/scheme.png' width=464 height=220>",
        width=464,
        height=220)

    Description = Div(
        text=
        "The application \"Vibroacoustics of Plates\" can be classified in two steps: <br><br>"
        "<b>1.</b> Insert the physical properties of a homogenous plate or of a single layer"
        "&nbsp;in the case of a layered plate (default values are given) on the left and press <i>'Apply'</i>. <br><br>"
        "<b>Notice</b> that in the case of a layered plate, a symmetric cross section"
        "&nbsp;with an odd number of layers and a crosswise layup is assumed (cf. scheme)."
        "&nbsp;Therefore, the thicknesses of the top to the center layer have to be inserted."
        "&nbsp;The material properties are homogenized through the thickness."
        "&nbsp;Thus, the input data of the single layer"
        "&nbsp;is overwritten by homogenized material parameters of the plate after pressing <i>'Apply'</i>."
        "&nbsp;The input data of the single layers can be checked by pressing the"
        "&nbsp;button <i>'Show Input'</i>. <br><br>"
        "<b>2.</b> On the right, dynamic properties of the plate and of"
        "&nbsp;its wave types are plotted. These can be studied"
        "&nbsp;using e.g. the zoom function and saved as .png.<br><br>"
        "&nbsp;Please refer to the following publication for further explanations and references:<br><br>"
        "&nbsp;Winter, C.: Frequency Dependent Modeling for the Prediction of the Sound Transmission in Timber Constructions. (2018).",
        render_as_text=False,
        width=1000,
        height=50)

    Title = Div(text="<b><h1> Vibroacoustics of Plates</b><h1>",
                render_as_text=False,
                width=900,
                height=80)

    # SPECIFY THE LAYOUT:
    Buttons = row(
        row(Spacer(width=50), ApplyButton, Spacer(width=50), ShowInput,
            Spacer(width=50), SetDefaultButton))

    Headline = row(column(Title, Description), Spacer(width=50), Scheme)

    LeftSide = column(
        ModeRadioButtons,
        Spacer(height=20), ELASTIC_MODULUS_TITEL, ElasticModulus.Table,
        Spacer(height=20), SHEAR_MODULUS_TITEL, ShearModulus.Table,
        Spacer(height=20), POISSON_RATIO_TITEL, PoissonRatios.Table,
        Spacer(height=20), MATERIALS_TITEL, MaterialProperties.Table,
        Spacer(height=20), GEOMETRY_TITEL,
        GeometryProperties.Table, LayersInfo.Widget, Spacer(height=10), Info,
        Spacer(height=20), WarningMessage.Widget)

    RightSide = column(Graph.Widget, Spacer(height=50), Buttons,
                       Spacer(height=100))

    # ========================= COMMUNICATION PART =============================

    # Set up callback function for the "Apply" button
    ApplyButton.on_click(
        partial(updateData, Tables, Graph, LayersInfo, WarningMessage))

    # Set up callback function for all radion buttons that are responsible
    # for changing the mode, namely: Isotropic and Orthotropic material properties
    ModeRadioButtons.on_click(
        partial(updateMode, Tables, WarningMessage, Graph))

    # Set up callback function for all radion buttons that are responsible
    # for plotting different graphs
    Graph.GraphRadioButtons.on_click(partial(updateGraph, Graph))

    # Set up callback function for all the "Default" button that are responsible
    # for assigning the default data to all entries
    SetDefaultButton.on_click(
        partial(setDefaultSettings, Tables, Graph, LayersInfo, WarningMessage))

    ShowInput.on_click(partial(showInput, Tables, LayersInfo))

    # ================= RUN SIMULATION WITH DEFAULT DATA =====================
    updateData(Tables, Graph, LayersInfo, WarningMessage)

    # RUN ALL WIDGETS
    doc.add_root(Headline)
    doc.add_root(
        column(Spacer(height=150),
               row(LeftSide, Spacer(width=50), RightSide, Spacer(width=50))))
Esempio n. 13
0
                                           height=140)
tab_table_monitor_service = Panel(child=spectrum_table_monitor_service,
                                  title="Moitor service")
tabs_monitor_service = Tabs(tabs=[tab_table_monitor_service])

iframe_text_2 = """<iframe src="http://172.16.16.12/WishfulWebPortal/only_usrp.html" height="350" width="1000" scrolling="no" frameBorder="0" ></iframe>"""
div = Div(text=iframe_text_2, width=600, height=270)

div_text = """"""
div_blank = Div(text=div_text, width=600, height=20)

button_group_channel_trace = RadioButtonGroup(
    labels=["OFF", "2.412MHz", "2.437MHz", "2.462MHz", "2.484MHz"],
    active=0,
    width=400)
button_group_channel_trace.on_click(set_channel_trace_channel)
# tab_channel_trace_button = Panel(child=button_group_channel_trace, title="Channel")
# tabs_wifi = Tabs(tabs=[ tab_channel_trace_button ])

l1 = layout([[div_blank, button_group_channel_trace], [div]],
            sizing_mode='fixed')
tab_channel_trace = Panel(child=div, title="Channel Trace")
tabs_channel_trace = Tabs(tabs=[tab_channel_trace])

div_blank_2 = Div(text=div_text, width=100, height=250)

plots = [[[tabs_channel_trace],
          [
              div_blank, button_group_channel_trace, div_blank_2,
              tabs_monitor_service
          ], [tabs_active_networks_table]]]
Esempio n. 14
0
# create buttons and add callbacks
# reset data
button_reset = Button(label='Reset', button_type='primary')
button_reset.on_click(lambda: callbacks.callback_button_reset(source, surface))

# add data on double tap
p.on_event(
    DoubleTap, lambda event: callbacks.callback_add_dot_on_double_tap(
        event, state, source))

# update model
button_update = Button(label='Train model', button_type='success')
button_update.on_click(lambda: callbacks.callback_button_update(
    source, classifiers, state, surface))

# choose class
button_class = RadioButtonGroup(labels=['Class 0', 'Class 1'], active=0)
button_class.on_click(lambda event: callbacks.callback_change_current_state(
    event, state.current_level))

# choose classifier
button_model = RadioButtonGroup(
    labels=['Log. Reg.', 'Naive Bayes', 'SVC', 'RF'], active=0)
button_model.on_click(lambda event: callbacks.callback_change_current_state(
    event, state.current_model))

# create document
curdoc().add_root(
    column(p, row(button_class, button_model), row(button_update,
                                                   button_reset), table))
Esempio n. 15
0
    department=[6, 0, 3, 2],
    credit=[4, 8, 3, 0],
    instructor=[5, 2, 6, 4]
    )
columns = [
        TableColumn(field="course_ID", title="Course ID"),
        TableColumn(field="title", title="Title"),
        TableColumn(field="department", title="Department"),
        TableColumn(field="credit", title="Credit"),
        TableColumn(field="instructor", title="Instructor")
    ]
data_source = ColumnDataSource(table_data)
table1 = DataTable(source=data_source, columns=columns, width=1000, height=1000)

# callbacks
btnGroupPosition1.on_click(partial(onClick, 'Position1'))





## Change Plot -- layout2
# widgets
btnGroupPosition2 = RadioButtonGroup(labels=['All', 'Top', 'Jug', 'Mid', 'ADC', 'Sup'], active=0)
btnGroupType1 = RadioButtonGroup(labels=['Win Rate', 'Pick Rate', 'Ban Rate'], active=0)

# callbacks
btnGroupPosition2.on_click(partial(onClick, 'Position2'))
btnGroupType1.on_click(partial(onClick, 'Type1'))

Esempio n. 16
0
oo = column(children=[
    exptime, diameter, resolution, temperature, ntherm, dtmax, gain,
    ground_based
])
pp = column(children=[template, magnitude])
qq = column(children=[
    instruction0, text_input, instruction1, format_button_group, instruction2,
    link_box
])
#ii = column(children=[inner, outer,  dtmax])
#ee = column(children=[want_snr])

observation_tab = Panel(child=oo, title='Observation')
planet_tab = Panel(child=pp, title='Target')
#instrument_tab = Panel(child=ii, title='Instrumentation')
download_tab = Panel(child=qq, title='Download')

for w in [text_input]:
    w.on_change('value', change_filename)
format_button_group.on_click(i_clicked_a_button)

for ww in [template]:
    ww.on_change('value', update_data)

for gg in [ground_based]:
    gg.on_change('value', update_data)

inputs = Tabs(tabs=[planet_tab, observation_tab, download_tab])

curdoc().add_root(row(inputs, ptabs))
Esempio n. 17
0
def slider_change(attr, old, new):
    global interval
    interval = (10 * max_interval + min_interval + new * (min_interval - max_interval)) / 9
    if play:
        curdoc().remove_periodic_callback(update)
        curdoc().add_periodic_callback(update, interval)


def button_group_click(new):
    global play
    if new == 0: # play
        play = True
        curdoc().add_periodic_callback(update, interval)
    else:
        play = False
        curdoc().remove_periodic_callback(update)

def button_click():
    global X, step
    step = 1
    X = np.copy(X_init)
    redraw()


slider.on_change("value", slider_change)
button_group.on_click(button_group_click)
button.on_click(button_click)

session.show(row(wb, p1, p2))
session.loop_until_closed()
Esempio n. 18
0
class Dashboard:
    """Explorepy dashboard class"""

    def __init__(self, n_chan, mode="signal"):
        self.n_chan = n_chan
        self.y_unit = DEFAULT_SCALE
        self.offsets = np.arange(1, self.n_chan + 1)[:, np.newaxis].astype(float)
        self.chan_key_list = ['Ch' + str(i + 1) for i in range(self.n_chan)]
        self.exg_mode = 'EEG'
        self.rr_estimator = None
        self.win_length = WIN_LENGTH
        self.mode = mode

        # Init ExG data source
        exg_temp = np.zeros((n_chan, 2))
        exg_temp[:, 0] = self.offsets[:, 0]
        exg_temp[:, 1] = np.nan
        init_data = dict(zip(self.chan_key_list, exg_temp))
        init_data['t'] = np.array([0., 0.])
        self.exg_source = ColumnDataSource(data=init_data)

        # Init ECG R-peak source
        init_data = dict(zip(['r_peak', 't'], [np.array([None], dtype=np.double), np.array([None], dtype=np.double)]))
        self.r_peak_source = ColumnDataSource(data=init_data)

        # Init ORN data source
        init_data = dict(zip(ORN_LIST, np.zeros((9, 1))))
        init_data['t'] = [0.]
        self.orn_source = ColumnDataSource(data=init_data)

        # Init table sources
        self.heart_rate_source = ColumnDataSource(data={'heart_rate': ['NA']})
        self.firmware_source = ColumnDataSource(data={'firmware_version': ['NA']})
        self.battery_source = ColumnDataSource(data={'battery': ['NA']})
        self.temperature_source = ColumnDataSource(data={'temperature': ['NA']})
        self.light_source = ColumnDataSource(data={'light': ['NA']})
        self.battery_percent_list = []
        self.server = None

        # Init fft data source
        init_data = dict(zip(self.chan_key_list, np.zeros((self.n_chan, 1))))
        init_data['f'] = np.array([0.])
        self.fft_source = ColumnDataSource(data=init_data)

        # Init impedance measurement source
        init_data = {'channel': [CHAN_LIST[i] for i in range(0, self.n_chan)],
                     'impedance': ['NA' for i in range(self.n_chan)],
                     'row': ['1' for i in range(self.n_chan)],
                     'color': ['black' for i in range(self.n_chan)]}
        self.imp_source = ColumnDataSource(data=init_data)

    def start_server(self):
        """Start bokeh server"""
        validation = validate(False)
        self.server = Server({'/': self._init_doc}, num_procs=1)
        self.server.start()

    def start_loop(self):
        """Start io loop and show the dashboard"""
        self.server.io_loop.add_callback(self.server.show, "/")
        self.server.io_loop.start()

    def _init_doc(self, doc):
        self.doc = doc
        self.doc.title = "Explore Dashboard"
        # Create plots
        self._init_plots()

        # Create controls
        m_widgetbox = self._init_controls()

        # Create tabs
        exg_tab = Panel(child=self.exg_plot, title="ExG Signal")
        orn_tab = Panel(child=column([self.acc_plot, self.gyro_plot, self.mag_plot], sizing_mode='fixed'),
                        title="Orientation")
        fft_tab = Panel(child=self.fft_plot, title="Spectral analysis")
        imp_tab = Panel(child=self.imp_plot, title="Impedance")
        if self.mode == "signal":
            self.tabs = Tabs(tabs=[exg_tab, orn_tab, fft_tab], width=1200)
        elif self.mode == "impedance":
            self.tabs = Tabs(tabs=[imp_tab], width=1200)

        self.doc.add_root(row([m_widgetbox, self.tabs]))
        self.doc.add_periodic_callback(self._update_fft, 2000)
        self.doc.add_periodic_callback(self._update_heart_rate, 2000)


    @gen.coroutine
    def update_exg(self, time_vector, ExG):
        """update_exg()
        Update ExG data in the visualization

        Args:
            time_vector (list): time vector
            ExG (np.ndarray): array of new data

        """
        # Update ExG data
        ExG = self.offsets + ExG / self.y_unit
        new_data = dict(zip(self.chan_key_list, ExG))
        new_data['t'] = time_vector
        self.exg_source.stream(new_data, rollover=2 * EEG_SRATE * WIN_LENGTH)

    @gen.coroutine
    def update_orn(self, timestamp, orn_data):
        """Update orientation data

        Args:
            timestamp (float): timestamp of the sample
            orn_data (float vector): Vector of orientation data with shape of (9,)
        """
        new_data = dict(zip(ORN_LIST, np.array(orn_data)[:, np.newaxis]))
        new_data['t'] = [timestamp]
        self.orn_source.stream(new_data, rollover=2 * WIN_LENGTH * ORN_SRATE)

    @gen.coroutine
    def update_info(self, new):
        """Update device information in the dashboard

        Args:
            new(dict): Dictionary of new values

        """
        for key in new.keys():
            data = {key: new[key]}
            if key == 'firmware_version':
                self.firmware_source.stream(data, rollover=1)
            elif key == 'battery':
                self.battery_percent_list.append(new[key][0])
                if len(self.battery_percent_list) > N_MOVING_AVERAGE:
                    del self.battery_percent_list[0]
                value = int(np.mean(self.battery_percent_list) / 5) * 5
                if value < 1:
                    value = 1
                self.battery_source.stream({key: [value]}, rollover=1)
            elif key == 'temperature':
                self.temperature_source.stream(data, rollover=1)
            elif key == 'light':
                data[key] = [int(data[key][0])]
                self.light_source.stream(data, rollover=1)
            else:
                print("Warning: There is no field named: " + key)

    @gen.coroutine
    def _update_fft(self):
        """ Update spectral frequency analysis plot
        """
        # Check if the tab is active and if EEG mode is active
        if (self.tabs.active != 2) or (self.exg_mode != 'EEG'):
            return

        exg_data = np.array([self.exg_source.data[key] for key in self.chan_key_list])

        # Check if the length of data is enough for FFT
        if exg_data.shape[1] < EEG_SRATE * 4.5:
            return
        fft_content, freq = get_fft(exg_data)
        data = dict(zip(self.chan_key_list, fft_content))
        data['f'] = freq
        self.fft_source.data = data

    @gen.coroutine
    def _update_heart_rate(self):
        """Detect R-peaks and update the plot and heart rate"""
        if self.exg_mode == 'EEG':
            self.heart_rate_source.stream({'heart_rate': ['NA']}, rollover=1)
            return
        if self.rr_estimator is None:
            self.rr_estimator = HeartRateEstimator()
            # Init R-peaks plot
            self.exg_plot.circle(x='t', y='r_peak', source=self.r_peak_source,
                                 fill_color="red", size=8)

        ecg_data = (np.array(self.exg_source.data['Ch1'])[-500:] - self.offsets[0]) * self.y_unit
        time_vector = np.array(self.exg_source.data['t'])[-500:]

        # Check if the peak2peak value is bigger than threshold
        if (np.ptp(ecg_data) < V_TH[0]) or (np.ptp(ecg_data) > V_TH[1]):
            print("P2P value larger or less than threshold!")
            return

        peaks_time, peaks_val = self.rr_estimator.estimate(ecg_data, time_vector)
        peaks_val = (np.array(peaks_val)/self.y_unit) + self.offsets[0]
        if peaks_time:
            data = dict(zip(['r_peak', 't'], [peaks_val, peaks_time]))
            self.r_peak_source.stream(data, rollover=50)

        # Update heart rate cell
        estimated_heart_rate = self.rr_estimator.heart_rate
        data = {'heart_rate': [estimated_heart_rate]}
        self.heart_rate_source.stream(data, rollover=1)

    @gen.coroutine
    def update_imp(self, imp):
        if self.mode == "impedance":
            color = []
            imp_str = []
            for x in imp:
                if x > 500:
                    color.append("black")
                    imp_str.append("Open")
                elif x > 100:
                    color.append("red")
                    imp_str.append(str(round(x, 0))+" K\u03A9")
                elif x > 50:
                    color.append("orange")
                    imp_str.append(str(round(x, 0))+" K\u03A9")
                elif x > 10:
                    color.append("yellow")
                    imp_str.append(str(round(x, 0))+" K\u03A9")
                elif x > 5:
                    imp_str.append(str(round(x, 0)) + " K\u03A9")
                    color.append("green")
                else:
                    color.append("green")
                    imp_str.append("<5K\u03A9")  # As the ADS is not precise in low values.


            data = {"impedance": imp_str,
                    'channel': [CHAN_LIST[i] for i in range(0, self.n_chan)],
                    'row': ['1' for i in range(self.n_chan)],
                    'color': color
                    }
            self.imp_source.stream(data, rollover=self.n_chan)
        else:
            raise RuntimeError("Trying to compute impedances while the dashboard is not in Impedance mode!")


    @gen.coroutine
    def _change_scale(self, attr, old, new):
        """Change y-scale of ExG plot"""
        new, old = SCALE_MENU[new], SCALE_MENU[old]
        old_unit = 10 ** (-old)
        self.y_unit = 10 ** (-new)

        for ch, value in self.exg_source.data.items():
            if ch in CHAN_LIST:
                temp_offset = self.offsets[CHAN_LIST.index(ch)]
                self.exg_source.data[ch] = (value - temp_offset) * (old_unit / self.y_unit) + temp_offset
        self.r_peak_source.data['r_peak'] = (np.array(self.r_peak_source.data['r_peak'])-self.offsets[0]) *\
                                            (old_unit / self.y_unit) + self.offsets[0]


    @gen.coroutine
    def _change_t_range(self, attr, old, new):
        """Change time range"""
        self._set_t_range(TIME_RANGE_MENU[new])

    @gen.coroutine
    def _change_mode(self, new):
        """Set EEG or ECG mode"""
        self.exg_mode = MODE_LIST[new]

    def _init_plots(self):
        """Initialize all plots in the dashboard"""
        self.exg_plot = figure(y_range=(0.01, self.n_chan + 1 - 0.01), y_axis_label='Voltage', x_axis_label='Time (s)',
                               title="ExG signal",
                               plot_height=600, plot_width=1270,
                               y_minor_ticks=int(10),
                               tools=[ResetTool()], active_scroll=None, active_drag=None,
                               active_inspect=None, active_tap=None)

        self.mag_plot = figure(y_axis_label='Magnetometer [mgauss/LSB]', x_axis_label='Time (s)',
                               plot_height=230, plot_width=1270,
                               tools=[ResetTool()], active_scroll=None, active_drag=None,
                               active_inspect=None, active_tap=None)
        self.acc_plot = figure(y_axis_label='Accelerometer [mg/LSB]',
                               plot_height=190, plot_width=1270,
                               tools=[ResetTool()], active_scroll=None, active_drag=None,
                               active_inspect=None, active_tap=None)
        self.acc_plot.xaxis.visible = False
        self.gyro_plot = figure(y_axis_label='Gyroscope [mdps/LSB]',
                                plot_height=190, plot_width=1270,
                                tools=[ResetTool()], active_scroll=None, active_drag=None,
                                active_inspect=None, active_tap=None)
        self.gyro_plot.xaxis.visible = False

        self.fft_plot = figure(y_axis_label='Amplitude (uV)', x_axis_label='Frequency (Hz)', title="FFT",
                               x_range=(0, 70), plot_height=600, plot_width=1270, y_axis_type="log")

        self.imp_plot = self._init_imp_plot()

        # Set yaxis properties
        self.exg_plot.yaxis.ticker = SingleIntervalTicker(interval=1, num_minor_ticks=10)

        # Initial plot line
        for i in range(self.n_chan):
            self.exg_plot.line(x='t', y=CHAN_LIST[i], source=self.exg_source,
                               line_width=1.5, alpha=.9, line_color="#42C4F7")
            self.fft_plot.line(x='f', y=CHAN_LIST[i], source=self.fft_source, legend=CHAN_LIST[i] + " ",
                               line_width=2, alpha=.9, line_color=FFT_COLORS[i])
        for i in range(3):
            self.acc_plot.line(x='t', y=ORN_LIST[i], source=self.orn_source, legend=ORN_LIST[i] + " ",
                               line_width=1.5, line_color=LINE_COLORS[i], alpha=.9)
            self.gyro_plot.line(x='t', y=ORN_LIST[i + 3], source=self.orn_source, legend=ORN_LIST[i + 3] + " ",
                                line_width=1.5, line_color=LINE_COLORS[i], alpha=.9)
            self.mag_plot.line(x='t', y=ORN_LIST[i + 6], source=self.orn_source, legend=ORN_LIST[i + 6] + " ",
                               line_width=1.5, line_color=LINE_COLORS[i], alpha=.9)

        # Set x_range
        self.plot_list = [self.exg_plot, self.acc_plot, self.gyro_plot, self.mag_plot]
        self._set_t_range(WIN_LENGTH)

        self.exg_plot.ygrid.minor_grid_line_color = 'navy'
        self.exg_plot.ygrid.minor_grid_line_alpha = 0.05

        # Set the formatting of yaxis ticks' labels
        self.exg_plot.yaxis[0].formatter = PrintfTickFormatter(format="Ch %i")

        # Autohide toolbar/ Legend location
        for plot in self.plot_list:
            plot.toolbar.autohide = True
            plot.background_fill_color = "#fafafa"
            if len(plot.legend) != 0:
                plot.legend.location = "bottom_left"
                plot.legend.orientation = "horizontal"
                plot.legend.padding = 2

    def _init_imp_plot(self):
        p = figure(plot_width=600, plot_height=200, x_range=CHAN_LIST[0:self.n_chan],
                   y_range=[str(1)], toolbar_location=None)

        p.circle(x='channel', y="row", radius=.3, source=self.imp_source, fill_alpha=0.6, color="color",
                 line_color='color', line_width=2)

        text_props = {"source": self.imp_source, "text_align": "center",
                      "text_color": "black", "text_baseline": "middle", "text_font": "helvetica",
                      "text_font_style": "bold"}

        x = dodge("channel", -0.1, range=p.x_range)

        r = p.text(x=x, y=dodge('row', -.4, range=p.y_range), text="impedance", **text_props)
        r.glyph.text_font_size = "10pt"

        r = p.text(x=x, y=dodge('row', -.3, range=p.y_range), text="channel", **text_props)
        r.glyph.text_font_size = "12pt"

        p.outline_line_color = None
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = None
        p.axis.major_label_standoff = 0
        p.axis.visible = False
        return p

    def _init_controls(self):
        """Initialize all controls in the dashboard"""
        # EEG/ECG Radio button
        self.mode_control = RadioButtonGroup(labels=MODE_LIST, active=0)
        self.mode_control.on_click(self._change_mode)

        self.t_range = Select(title="Time window", value="10 s", options=list(TIME_RANGE_MENU.keys()), width=210)
        self.t_range.on_change('value', self._change_t_range)
        self.y_scale = Select(title="Y-axis Scale", value="1 mV", options=list(SCALE_MENU.keys()), width=210)
        self.y_scale.on_change('value', self._change_scale)

        # Create device info tables
        columns = [TableColumn(field='heart_rate', title="Heart Rate (bpm)")]
        self.heart_rate = DataTable(source=self.heart_rate_source, index_position=None, sortable=False,
                                    reorderable=False,
                                    columns=columns, width=200, height=50)

        columns = [TableColumn(field='firmware_version', title="Firmware Version")]
        self.firmware = DataTable(source=self.firmware_source, index_position=None, sortable=False, reorderable=False,
                                  columns=columns, width=200, height=50)

        columns = [TableColumn(field='battery', title="Battery (%)")]
        self.battery = DataTable(source=self.battery_source, index_position=None, sortable=False, reorderable=False,
                                 columns=columns, width=200, height=50)

        columns = [TableColumn(field='temperature', title="Temperature (C)")]
        self.temperature = DataTable(source=self.temperature_source, index_position=None, sortable=False,
                                     reorderable=False, columns=columns, width=200, height=50)

        columns = [TableColumn(field='light', title="Light (Lux)")]
        self.light = DataTable(source=self.light_source, index_position=None, sortable=False, reorderable=False,
                               columns=columns, width=200, height=50)

        # Add widgets to the doc
        m_widgetbox = widgetbox([self.mode_control, self.y_scale, self.t_range, self.heart_rate,
                                 self.battery, self.temperature, self.light, self.firmware], width=220)
        return m_widgetbox

    def _set_t_range(self, t_length):
        """Change time range of ExG and orientation plots"""
        for plot in self.plot_list:
            self.win_length = int(t_length)
            plot.x_range.follow = "end"
            plot.x_range.follow_interval = t_length
            plot.x_range.range_padding = 0.
            plot.x_range.min_interval = t_length
Esempio n. 19
0
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(lambda value: print('checkbox_group: %s' % value))
checkbox_group.js_on_click(CustomJS(code="console.log('checkbox_group: ' + this.active, this.toString())"))

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(lambda value: print('radio_group: %s' % value))
radio_group.js_on_click(CustomJS(code="console.log('radio_group: ' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(lambda value: print('checkbox_button_group: %s' % value))
checkbox_button_group.js_on_click(CustomJS(code="console.log('checkbox_button_group: ' + this.active, this.toString())"))

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(lambda value: print('radio_button_group: %s' % value))
radio_button_group.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())"))

widgetBox = WidgetBox(children=[
    button, button_disabled,
    toggle_inactive, toggle_active,
    dropdown, dropdown_disabled, #dropdown_split,
    checkbox_group, radio_group,
    checkbox_button_group, radio_button_group,
])

document = curdoc()
document.add_root(widgetBox)

if __name__ == "__main__":
    session = push_session(document)
def createClusterFigure(doc):
    active_gene = None
    print('Starting Document....')

    if doc.session_context.request.arguments is not None:
        args = doc.session_context.request.arguments

    dataPath = doc.session_context.db_path
    if dataPath != 'None':
        dataSet = sc.read_h5ad(dataPath)
    else:
        dataSet = sc.read_h5ad('/app/ProcessedData.h5ad')

    geneList = [(args[x][0].decode())for x in args.keys() if 'Gene' in x]
    if 'None' not in geneList and len(geneList) is not 0:
        print(geneList[0])
        active_gene = geneList[0]

    def makePlot(doc, active_gene, adata):

        cdsDict = {}
        cdsDict['x'] = adata.obsm['X_umap'][:, 0]
        cdsDict['y'] = adata.obsm['X_umap'][:, 1]

        single_gene_colors = []
        # Color by Cluster
        color_Dict = dict(zip(adata.obs['louvain'].cat.categories, adata.uns['louvain_colors']))
        colors = [
            color_Dict[cluster] for cluster in adata.obs['louvain'] if cluster in color_Dict.keys()
        ]
        cdsDict['color'] = colors

        # Color by n_genes
        gene_colors = []
        for x, y, z, _ in 255 * mpl.cm.viridis(mpl.colors.Normalize()(adata.obs['n_genes'].tolist())):
            gene_colors.append("#%02x%02x%02x" % (int(x), int(y), int(z)))

        cdsDict['gene_colors'] = gene_colors

        if active_gene is not None:
            # Sort matrix by gene columnthen normalize the count values
            geneExpression = adata.X[:, adata.var.index == active_gene].flatten()
            single_gene_colors = []
            for x, y, z, _ in 255 * mpl.cm.viridis(mpl.colors.Normalize()(geneExpression)):
                single_gene_colors.append("#%02x%02x%02x" % (int(x), int(y), int(z)))
            if len(single_gene_colors) == 2638:
                cdsDict['single_gene'] = single_gene_colors

        source = ColumnDataSource(cdsDict)
        # source = ColumnDataSource(dict( x=adata.obsm['X_umap'][:, 0], y=adata.obsm['X_umap'][:, 1], color=colors, gene_colors=gene_colors, single_gene=single_gene_colors))
        title = 'T-SNE visualization of sequences'

        geneTitle = 'n_genes'

        plotDict = {}

        plot_lda = figure(plot_width=800, plot_height=600, title=title, tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave", x_axis_type=None, y_axis_type=None, min_border=1)

        plot_lda.scatter(x='x', y='y', legend='label', source=source, color='color',
                         alpha=0.8, size=5)

        plotDict['tsne'] = plot_lda

        genePlot = figure(plot_width=800, plot_height=600, title=geneTitle, tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave", x_axis_type=None, y_axis_type=None, min_border=1)
        genePlot.scatter(x='x', y='y', legend='label', source=source, color='gene_colors',
                         alpha=0.8, size=5)

        plotDict['nGene'] = genePlot

        if 'single_gene' in cdsDict.keys():
            singleGene = figure(plot_width=800, plot_height=600, title=active_gene, tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave", x_axis_type=None, y_axis_type=None, min_border=1)
            singleGene.scatter(x='x', y='y', legend='label', source=source, color='single_gene', alpha=0.8, size=5)

            plotDict['sGene'] = singleGene

        return plotDict

    def update(new):
        active_gene = geneList[new]
        sgCol.children[0] = makePlot(doc, active_gene, dataSet)['sGene']

    plotDict = makePlot(doc, active_gene, dataSet)

    # hover tools
    hover = plotDict['tsne'].select(dict(type=HoverTool))
    hover.tooltips = {"content": "Sequence: @seq, CCS: @ccs, Charge: @charge "}
    plotDict['tsne'].legend.location = "top_left"

    button_group = RadioButtonGroup(labels=geneList)
    button_group.on_click(update)

    tabList = []

    if 'sGene' in plotDict.keys():
        controls = widgetbox([button_group], width=800)
        sgCol = column(plotDict['sGene'], controls)
        sgTab = Panel(child=sgCol, title="Single Gene")
        tabList.append(sgTab)

    tsneTab = Panel(child=plotDict['tsne'], title="Louvain")
    tabList.append(tsneTab)

    nGeneTab = Panel(child=plotDict['nGene'], title="nGene")
    tabList.append(nGeneTab)

    tabs = Tabs(tabs=tabList)

    doc.add_root(tabs)

    return doc
Esempio n. 21
0
# ------------------------------------------------------------------------------
# ------------- Create the gridplot containing 9 sensors scatter plot ----------
# ------------------------------------------------------------------------------

CDSs = []
for i in range(len(sensors)):
    data = {'x': range(2208), 'y': Readings[i][0]}
    for j in range(len(chems)):
        data[chems[j]] = Readings[i][j]
    CDS = ColumnDataSource(data=data)
    CDSs.append(CDS)

# Create 4 panels, each with 9 figures, one for each sensor

chem_select = RadioButtonGroup(labels=chems, active=0)
chem_select.on_click(chem_callback)

figures = []

for j in range(len(sensors)):
    fig = figure(plot_width=300,
                 plot_height=300,
                 y_range=[0, 10],
                 tools=['wheel_zoom', 'pan', 'reset'],
                 title="Sensor " + str(j + 1))
    dots = fig.circle(x='x', y='y', source=CDSs[j])
    fig.xaxis.ticker = []
    fig.xaxis.axis_label = "Time"
    fig.yaxis.axis_label = "Sensor Reading"
    figures.append(fig)
Esempio n. 22
0
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button", type="danger", menu=menu, default_action="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group])

document.add(vbox)
session.store_document(document)

if __name__ == "__main__":
    link = session.object_link(document.context)
    print("Please visit %s to see the plots" % link)
    view(link)
    print("\npress ctrl-C to exit")
    session.poll_document(document)
Esempio n. 23
0
def showall_handler():
    for w in visibility_widgets:
        w.active = list(range(len(w.labels)))
    layout.children[0] = create_figure()

def hideall_handler():
    for w in visibility_widgets:
        w.active = []
    layout.children[0] = create_figure()

modelboxes.on_click(handler)
datasetboxes.on_click(handler)
filterboxes.on_click(handler)
showall.on_click(showall_handler)
hideall.on_click(hideall_handler)
modelsort.on_click(handler)
datasetsort.on_click(handler)
filtersort.on_click(handler)

legendtext = ('\n'*8 + 'Solid: SVM Score\nOutline: RF Score\n\n' +
              'Green: UK\nPink: US\nOrange: Mixed\n' +
              'Purple: Reverse Split\nBlue: Split\n\n' +
              'Circle: Complete\nDiamond: Filtered')
controls = widgetbox([PreText(text='Choose Visible Items')] +
                     visibility_widgets + [showall, hideall] +
                     [PreText(text='Choose What to Sort Kmers by')] +
                      sort_widgets +
                     [PreText(text=legendtext)])
layout = row(create_figure(), controls)

curdoc().add_root(layout)
Esempio n. 24
0
                 default_value="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[
    button, toggle, dropdown, split, checkbox_group, radio_group,
    checkbox_button_group, radio_button_group
])

document = Document()
document.add_root(vbox)
session = push_session(document)
session.show()

if __name__ == "__main__":
    session.loop_until_closed()
readsUpload.on_change('value', upload_reads_data)
fastaUploadTitle = Div(text='Fusion fragments aligned to original reads file (.bed, optional)')
fastaUpload = FileInput(accept=".bed", name='fareads')
informUser = Div(text='updates will appear here', name='informUser')
tableSource.selected.on_change('indices', table_click_callback)
buttonSource = ColumnDataSource(data=dict(press=[0], figs=[2]))

def buttonClick(attr):
	hiddenButtonSource.data.update(ColumnDataSource({"selected":[attr]}).data)
	table_click_callback(0, 0, 0)
def saveClick(attr):
	# currLayout = curdoc().get_model_by_name('mainLayout').children
	# curdoc().get_model_by_name()
	# for i in length of plots:
		# export_png(curdoc().get_model_by_name("p"+string(length)), filename="plot0.png")
	export_png(curdoc().get_model_by_name("p0"), filename="plot0.png")
	export_png(curdoc().get_model_by_name("p1"), filename="plot1.png")
	curdoc().get_model_by_name('informUser').text = 'files saved'

#https://stackoverflow.com/questions/34465697/python-bokeh-radio-button-group
buttons = RadioButtonGroup(labels=['Full View', 'Remapped Alignment View', 'Isoform Full Length View'], active=0)
buttons.on_click(buttonClick)


button = Button(label="Save")
button.on_click(saveClick)

subColumn = column([pageTitle, fusionUploadTitle, fusionUpload, readsUploadTitle, readsUpload, fastaUploadTitle, fastaUpload, buttons, button, informUser, data_table], name='subColumn')
mainLayout = row([subColumn, pl, pr], name='mainLayout')
curdoc().add_root(mainLayout)
Esempio n. 26
0
unload_file_button = Button(label="Unload", button_type="danger", width=50)
unload_file_button.on_click(unload_file)

# files selection box
files_selector = Select(title="Files:", options=[""])
files_selector.on_change('value', change_data_selector)

# data selection box
data_selector = MultiSelect(title="Data:", options=[], size=12)
data_selector.on_change('value', select_data)

# x axis selection box
x_axis_selector_title = Div(text="""X Axis:""", height=10)
x_axis_selector = RadioButtonGroup(labels=x_axis_options, active=0)
x_axis_selector.on_click(change_x_axis)

# toggle second axis button
toggle_second_axis_button = Button(label="Toggle Second Axis", button_type="success")
toggle_second_axis_button.on_click(toggle_second_axis)

# averaging slider
# This data source is just used to communicate / trigger the real callback
averaging_slider_dummy_source = ColumnDataSource(data=dict(value=[]))
averaging_slider_dummy_source.on_change('data', update_averaging)
averaging_slider = Slider(title="Averaging window", start=1, end=101, step=10, callback_policy='mouseup')
averaging_slider.callback = CustomJS(args=dict(source=averaging_slider_dummy_source), code="""
    source.data = { value: [cb_obj.value] }
""")

# group properties checkbox
Esempio n. 27
0
def SIF_Explorer_tab():

    #################################
    # Initialize all layers
    #################################

    # Load from a save file
    if path.exists(LAYERS_FILE):
        with open(LAYERS_FILE, 'rb') as layers_file:
            us_county_layer, us_state_layer, world_grid_2_degree_layer = pickle.load(layers_file)
    # Load from scratch
    else:
        us_county_layer = US_County_Layer()
        us_state_layer = US_State_Layer()
        world_grid_2_degree_layer = US_World_Grid_2_Degree_Layer()
        
        # Save the layers to file
        with open(LAYERS_FILE, 'wb') as layers_file:
            layers = (us_county_layer, \
                        us_state_layer, world_grid_2_degree_layer)
            pickle.dump(layers, layers_file)

    # Want the custom layer to be new every time
    custom_shapes_layer = Custom_Shapes_Layer()
    world_grid_dynamic_layer = World_Grid_Dynamic_Layer()

    # Set the active layer to be the county layer
    active_layer = us_county_layer

    #################################
    # Set up layer selector
    #################################

    # Once a new layer is selected, use that layer to refresh the page
    # and all data
    def refresh_page():
        
        # Get initial map details
        xs, ys, names = active_layer.get_map_details()

        if type(active_layer) != Custom_Shapes_Layer:

            # Obtain and update date boundaries
            start_date, end_date = active_layer.get_date_range()
            date_range_slider.start = start_date
            date_range_slider.end = end_date

            # Unpack the current range
            range_start, range_end = date_range_slider.value

            # Convert to SQL format
            range_start = utc_from_timestamp(range_start)
            range_end = utc_from_timestamp(range_end)

            # Get the initial sif values
            sifs = active_layer.get_data_for_date_range(range_start, 
                                                        range_end)

            # Dictionary to hold the data
            new_source_dict = dict(
                x= xs, y= ys,
                name= np.array(names), sifs= np.array(sifs))
            
            # Update all source data values
            source.data = new_source_dict

            # Turn off custom layer
            custom_data_source.data = dict(x= np.array([]), y= np.array([]), 
                                           name = np.array([]))

        else:

            # Turn off the other layers
            source.data = dict(x= np.array([]), y= np.array([]),
                name= np.array([]), sifs= np.array([]))

            # Safeguard - that at least one custom shape is drawn
            if (xs.size != 0):

                # Dictionary to hold the selected shape data
                new_source_dict = dict(
                    x= xs, y= ys,
                    name = np.array(names))

                custom_data_source.data = new_source_dict


    # Trigger for when a new layer is selected
    def layer_selected(new):

        # We want to modify the overall active layer (not local to this func)
        nonlocal active_layer

        # Simple dictionary to switch out the active layer
        switcher = {
            0 : custom_shapes_layer,
            1 : us_state_layer,
            2 : us_county_layer,
            3 : world_grid_2_degree_layer,
            4 : world_grid_dynamic_layer,
        }

        # Swap out the active layer
        active_layer = switcher.get(new, active_layer) 
            
        # Fetch new dates, shapes, names, etc. and refresh the page
        refresh_page()

    # Define selection labels
    layer_selector = RadioButtonGroup(
        labels=["Custom", "US States", "US Counties", 
                "World", "World (Dynamic)"], active=2)

    # Set up layer selection callback
    layer_selector.on_click(layer_selected)

    #################################
    # Set up date range slider
    #################################

    # Obtain date boundaries
    start_date, end_date = active_layer.get_date_range()

    # create a callback for when the date slider is changed
    def date_range_selected(attr, old, new):

        t0 = time.time()

        # Unpack the new range
        range_start, range_end = new

        # Convert to SQL format
        range_start = utc_from_timestamp(range_start)
        range_end = utc_from_timestamp(range_end)
        
        # Get the new day's data
        sifs = active_layer.get_data_for_date_range(range_start, range_end)

        # Update the sif values
        source.data["sifs"] = np.array(sifs)

        # Set the title of the map to reflect the selected date range
        p.title.text = "SIF Average: %s to %s" % (range_start, range_end)

        print("Took " + str(time.time() - t0) + " seconds to update")

    # Create the date slider
    date_range_slider = DateRangeSlider(title="Date Range: ", 
                                        start=start_date, end=end_date, 
                                        value=(START_DATE_INIT, 
                                            END_DATE_INIT), step=1)

    # Assign the callback for when the date slider changes
    date_range_slider.callback_policy = "throttle"
    date_range_slider.callback_throttle = 200
    date_range_slider.on_change('value_throttled', date_range_selected)

    #################################
    # Set up the map and its source
    #################################

    # Get initial map details
    xs, ys, names = active_layer.get_map_details()

    # Get the initial sif values 
    sifs = active_layer.get_data_for_date_range(START_DATE_INIT, 
                                                END_DATE_INIT)

    # Dictionary to hold the data
    source=ColumnDataSource(data = dict(
        x= np.array(xs),
        y= np.array(ys),
        name= np.array(names),
        sifs= np.array(sifs))
    )

    # Which tools should be available to the user
    TOOLS = "pan,wheel_zoom,reset,hover,save,tap"

    # Obtain map provider
    tile_provider = get_provider(Vendors.CARTODBPOSITRON_RETINA)

    # tile_options = {}
    # tile_options['url'] = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}'
    # tile_options['attribution'] = """
    #     Map tiles by <a href="http://stamen.com">Stamen Design</a>, under
    #     <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.
    #     Data by <a href="http://openstreetmap.org">OpenStreetMap</a>,
    #     under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.
    #     """
    # mq_tile_source = WMTSTileSource(**tile_options)

    # Don't want the map to wrap around
    tile_provider.wrap_around = False

    # Configure the figure
    p = figure(
        title="SIF Average by County: %s" % end_date, tools=TOOLS,
        active_scroll = "wheel_zoom",
        x_axis_location=None, y_axis_location=None,
        tooltips=[
            ("Name", "@name"), 
            ("Average SIF", "@sifs")
        ],
        x_axis_type='mercator',
        y_axis_type='mercator',
        plot_height = 900,
        plot_width = 1100,
        output_backend="webgl",
        x_range=Range1d(-20000000, 20000000, bounds = 'auto'))

    # Add the map!
    p.add_tile(tile_provider)

    p.lod_threshold = None          # No downsampling
    #p.lod_interval = 150
    p.toolbar.logo = None           # No logo
    p.grid.grid_line_color = None   # No grid

    # Policy for hovering
    p.hover.point_policy = "follow_mouse"

    # Color mapper
    color_mapper = LinearColorMapper(palette=palette, 
                                     low = SIF_MIN, high = SIF_MAX)
    color_transform = {'field': 'sifs', 'transform': color_mapper}

    # Patch all the information onto the map
    patch_renderer = p.patches('x', 'y', source=source,
                      fill_color=color_transform,
                      fill_alpha=0.9, line_color="white", line_width=0.1, 
                      selection_fill_alpha = 1.0, 
                      selection_fill_color = color_transform,
                      nonselection_line_color="black",
                      nonselection_fill_alpha=0.7,
                      nonselection_fill_color= color_transform)
    p.title.text_font_size = '16pt'

    # Add a color bar
    ticker = FixedTicker(ticks=[-1,0,1,2])
    color_bar = ColorBar(color_mapper=color_mapper, ticker = ticker,
                     label_standoff=12, border_line_color=None, location=(0,0))
    p.add_layout(color_bar, 'right')

    # Add zoom in / out tools
    zoom_in = ZoomInTool(factor=ZOOM_FACTOR)
    zoom_out = ZoomOutTool(factor=ZOOM_FACTOR)

    def range_changed(param, old, new):
        if (type(active_layer) == World_Grid_Dynamic_Layer):
            x1 = p.x_range.start
            x2 = p.x_range.end
            y1 = p.y_range.start
            y2 = p.y_range.end
            new_x1, new_y1 = to_lat_lon(y1, x1)
            new_x2, new_y2 = to_lat_lon(y2, x2)
            if (active_layer.range_changed(new_x1, new_y1, new_x2, new_y2)):
                refresh_page()
            #convert_shapes_to_mercator(np.array([[x1], [x2]]), 
                                                      #np.array([[y1], [y2]]))

            #print("(%s, %s) to (%s, %s)" % (x1, y1, x2, y2))
            #40000000
            #

    # p.callback_policy = "throttle"
    # p.callback_throttle = 200
    p.x_range.on_change('end', range_changed)

    p.add_tools(zoom_in)
    p.add_tools(zoom_out)

    #################################
    # Set up custom plot data
    #################################

    # Data source for custom shapes
    custom_data_source = ColumnDataSource(data = \
                                        dict(x= np.array([]), y= np.array([]), 
                                        name=np.array([])))

    # Patch the custom data onto the map
    p.patches('x', 'y', source=custom_data_source,
                  line_color="darkslategray", line_width=1, 
                  fill_alpha=0.3, fill_color="lightgray")

    # On geometry selection
    # zoom = WheelZoomTool()
    # p.on_event()
    # p.add_tools(lasso)
    # p.on_event(SelectionGeometry, shape_drawn)

    #################################
    # Set up time series
    #################################

    def color_gen():
        yield from itertools.cycle(time_pltt[10])
    color = color_gen()

    def shape_drawn(event):

        # Check if more than one point
        # Otherwise a tap triggers this function
        if (type(event.geometry['x']) != float):

            # Notify the custom selection layer that this
            # shape was selected and obtain relevant info
            # custom_shapes_layer.patch_selected(event)

            # Change to the custom layer
            layer_selector.active = 0
            layer_selected(0)

            # Notify the layer that this patch was created. 
            active_layer.patch_created(event)

            # Clear all time series
            sif_series.renderers = []

            # Update the title and get new data from the active layer
            sif_series.title.text, time_srs_src_list, names = \
                                active_layer.patch_clicked(source, None)

            # Plot each series returned
            for i in range(len(time_srs_src_list)):
                sif_series.scatter('date', 'sif', 
                                    source=time_srs_src_list[i], 
                                    color=time_pltt[10][i])
            # Make sure the current shape is drawn
            refresh_page()

    def patch_clicked(event):
        """ When a patch is clicked, update the time series chart. """

        # Clear all time series
        sif_series.renderers = []

        # Update the title and get new data from the active layer
        sif_series.title.text, time_srs_src_list, names = \
                            active_layer.patch_clicked(source, event)

        # Plot each series returned
        for i in range(len(time_srs_src_list)):
            sif_series.scatter('date', 'sif', 
                                source=time_srs_src_list[i], 
                                color=time_pltt[10][i])

    # Which tools should be available to the user for the timer series
    TOOLS = "pan,wheel_zoom,reset,hover,save"

    # Figure that holds the time-series
    sif_series = figure(plot_width=750, plot_height=400, x_axis_type='datetime',
                        tools=TOOLS, 
                        title= "SIF Time-Series (Select a county...)",
                        active_scroll = "wheel_zoom",
                        tooltips=[
                            ("Day", "@date"), 
                            ("Average SIF", "@sif")
                        ],
                        x_axis_label = 'Date',
                        y_axis_label = 'SIF Average',
                        y_range = (SIF_MIN, SIF_MAX))

    # Some font choices
    sif_series.title.text_font_size = '16pt'
    sif_series.xaxis.axis_label_text_font_size = "12pt"
    sif_series.yaxis.axis_label_text_font_size = "12pt"

    # Policy for hovering
    sif_series.hover.point_policy = "follow_mouse"

    # No logo
    sif_series.toolbar.logo = None

    # When a patch is selected, trigger the patch_time_series function
    p.on_event(Tap, patch_clicked)
    
    # On geometry selection
    lasso = LassoSelectTool(select_every_mousemove = False)
    p.add_tools(lasso)
    p.on_event(SelectionGeometry, shape_drawn)

    #################################
    # TODO: Set up download area
    #################################
    # def save_data():
    #     active_layer.save_data()
    #     print("Button Clicked")

    # callback = active_layer.get_save_data_js_callback()

    button = Button(label="Save Data", button_type="success")
    # button.on_click(active_layer.save_data)
    #button.js_on_event(ButtonClick, callback)

    #################################
    # Set up tab
    #################################

    # The layout of the view
    layout = row(column(p, date_range_slider, layer_selector), 
                 column(sif_series, row(column(), button)))

    # Create tab using layout
    tab = Panel(child=layout, title = 'US Visualization')

    # Return the created tab
    return tab
Esempio n. 28
0
    CustomJS(
        code="console.log('radio_group: ' + this.active, this.toString())"))

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(
    lambda value: print('checkbox_button_group: %s' % value))
checkbox_button_group.js_on_click(
    CustomJS(
        code=
        "console.log('checkbox_button_group: ' + this.active, this.toString())"
    ))

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(
    lambda value: print('radio_button_group: %s' % value))
radio_button_group.js_on_click(
    CustomJS(
        code=
        "console.log('radio_button_group: ' + this.active, this.toString())"))

widgetBox = WidgetBox(children=[
    button,
    button_disabled,
    toggle_inactive,
    toggle_active,
    dropdown,
    dropdown_disabled,  #dropdown_split,
    checkbox_group,
    radio_group,
    checkbox_button_group,
Esempio n. 29
0
        MessageBox.text = msg
        return
    fpath = os.path.join(fdir, csvfiles[0])


cfg = bu.config()
Config = Paragraph(text=bu.config())
Above = Paragraph(text="You are Here")
Here = Paragraph()
Here.text = CurDir
MessageBox = Paragraph(text="Go")
Timer = Paragraph()
spacer = Paragraph(width=10)
blabels = bu.list_from_path(CurDir)
button_group = RadioButtonGroup(labels=blabels)
button_group.on_click(dir_select)


def dirs_source_callback(attr, old, new):
    global dirs_source
    oldind = old.get('1d', None)
    newind = (new['1d']['indices'][0]
              if len(new['1d']['indices']) > 0 else None)
    if newind is None:
        return
    if dirs_source.data['Name'][newind] == '.':
        return
    newpath = (dirs_source.data['Name'][newind]
               if newind is not None else None)

    newpath = os.path.join(CurDir, newpath)