def __create_widgets(self):
        ignored_y = ['Patient Name', 'Patient ID', 'Plan Date', 'Radiation Dev', 'Energy', 'file_name', 'date_time_obj']
        y_options = [option for option in list(self.data) if option not in ignored_y]
        self.select_y = Select(title='Y-variable:', value='Dose Dev', options=y_options)

        linacs = list(set(self.data['Radiation Dev']))
        linacs.sort()
        linacs.insert(0, 'All')
        linacs.append('None')
        self.select_linac = {grp: Select(title='Linac %s:' % grp, value='All', options=linacs, width=250)
                             for grp in GROUPS}
        self.select_linac[2].value = 'None'

        energies = list(set(self.data['Energy']))
        energies.sort()
        energies.insert(0, 'Any')
        self.select_energies = {grp: Select(title='Energy %s:' % grp, value='Any', options=energies, width=250)
                                for grp in GROUPS}

        self.avg_len_input = TextInput(title='Avg. Len:', value='10', width=100)

        self.percentile_input = TextInput(title='Percentile:', value='90', width=100)

        self.bins_input = TextInput(title='Bins:', value='20', width=100)

        self.start_date_picker = DatePicker(title='Start Date:', value=self.x[0])
        self.end_date_picker = DatePicker(title='End Date:', value=self.x[-1])

        self.gamma_options = ['5.0%/3.0mm', '3.0%/3.0mm', '3.0%/2.0mm', 'Any']
        self.checkbox_button_group = CheckboxButtonGroup(labels=self.gamma_options, active=[3])
 def createButtons(self, figNames):
     buttons = CheckboxButtonGroup(labels=[name for name in figNames],
                                   active=[0, 1, 2])
     buttons.on_click(self.buttonClick)
     for count, name in enumerate(figNames):
         self.buttonToFig[count] = self.figs[name]
     return buttons
Exemple #3
0
def get_select(desc, values, default=None, labels=None):  # pylint: disable=unused-argument
    if default is None:
        # by default, make all selections active
        default = list(range(len(values)))

    if labels is None:
        labels = list(map(str, values))

    # misuse tags to store values without mapping to str
    group = CheckboxButtonGroup(labels=labels, active=default, tags=values)
    group.on_change('active', on_filter_change)

    return group
Exemple #4
0
    def add_specline_toggles(self, viewer_cds, plots):
        #-----
        #- Toggle lines
        self.speclines_button_group = CheckboxButtonGroup(
                labels=["Emission lines", "Absorption lines"], active=[])
        self.majorline_checkbox = CheckboxGroup(
                labels=['Show only major lines'], active=[])

        self.speclines_callback = CustomJS(
            args = dict(line_data = viewer_cds.cds_spectral_lines,
                        lines = plots.speclines,
                        line_labels = plots.specline_labels,
                        zlines = plots.zoom_speclines,
                        zline_labels = plots.zoom_specline_labels,
                        lines_button_group = self.speclines_button_group,
                        majorline_checkbox = self.majorline_checkbox),
            code="""
            var show_emission = false
            var show_absorption = false
            if (lines_button_group.active.indexOf(0) >= 0) {  // index 0=Emission in active list
                show_emission = true
            }
            if (lines_button_group.active.indexOf(1) >= 0) {  // index 1=Absorption in active list
                show_absorption = true
            }

            for(var i=0; i<lines.length; i++) {
                if ( !(line_data.data['major'][i]) && (majorline_checkbox.active.indexOf(0)>=0) ) {
                    lines[i].visible = false
                    line_labels[i].visible = false
                    zlines[i].visible = false
                    zline_labels[i].visible = false
                } else if (line_data.data['emission'][i]) {
                    lines[i].visible = show_emission
                    line_labels[i].visible = show_emission
                    zlines[i].visible = show_emission
                    zline_labels[i].visible = show_emission
                } else {
                    lines[i].visible = show_absorption
                    line_labels[i].visible = show_absorption
                    zlines[i].visible = show_absorption
                    zline_labels[i].visible = show_absorption
                }
            }
            """
        )
        self.speclines_button_group.js_on_click(self.speclines_callback)
        self.majorline_checkbox.js_on_click(self.speclines_callback)
Exemple #5
0
    def __init__(self, sources, time_series, correlation, regression,
                 custom_title, data_tables):
        self.sources = sources
        self.time_series = time_series
        self.correlation = correlation
        self.regression = regression

        self.eud_a_input = TextInput(value='', title='EUD a-value:', width=150)
        self.gamma_50_input = TextInput(value='',
                                        title=u"\u03b3_50:",
                                        width=150)
        self.td_tcd_input = TextInput(value='',
                                      title='TD_50 or TCD_50:',
                                      width=150)
        self.apply_button = Button(label="Apply parameters",
                                   button_type="primary",
                                   width=150)
        self.apply_filter = CheckboxButtonGroup(
            labels=["Group 1", "Group 2", "Selected"], active=[0], width=300)

        self.apply_button.on_click(self.apply_rad_bio_parameters)

        self.layout = column(
            Div(text="<b>DVH Analytics v%s</b>" % options.VERSION),
            row(custom_title['1']['rad_bio'], Spacer(width=50),
                custom_title['2']['rad_bio']),
            Div(text="<b>Published EUD Parameters from Emami"
                " et. al. for 1.8-2.0Gy fractions</b> (Click to apply)",
                width=600), data_tables.emami,
            Div(text="<b>Applied Parameters:</b>", width=150),
            row(self.eud_a_input, Spacer(width=50), self.gamma_50_input,
                Spacer(width=50), self.td_tcd_input, Spacer(width=50),
                self.apply_filter, Spacer(width=50), self.apply_button),
            Div(text="<b>EUD Calculations for Query</b>", width=500),
            data_tables.rad_bio, Spacer(width=1000, height=100))
Exemple #6
0
def get_checkbox(glyph_renderers, labels, max_checkbox_length=None):
    """
    Parameters
    ----------
    glyph_renderers: List[List[Renderer]]
        list of glyph-renderers
    labels: List[str]
        list with strings to be put in checkbox

    Returns
    -------
    checkbox: CheckboxGroup or List[CheckboxGroup]
        checkbox object
    select_all: Button
        button related to checkbox
    select_none: Button
        button related to checkbox
    """
    code, args_checkbox = _prepare_nested_glyphs(glyph_renderers)
    # Toggle all renderers in a subgroup, if their domain is set to active
    code += """
        for (i = 0; i < len_labels; i++) {
            if (cb_obj.active.includes(i)) {
                // console.log('Setting to true: ' + i + '(' + glyph_renderers[i].length + ')')
                for (j = 0; j < glyph_renderers[i].length; j++) {
                    glyph_renderers[i][j].visible = true;
                    // console.log('Setting to true: ' + i + ' : ' + j)
                }
            } else {
                // console.log('Setting to false: ' + i + '(' + glyph_renderers[i].length + ')')
                for (j = 0; j < glyph_renderers[i].length; j++) {
                    glyph_renderers[i][j].visible = false;
                    // console.log('Setting to false: ' + i + ' : ' + j)
                }
            }
        }
        """

    # Create the actual checkbox-widget
    callback = CustomJS(args=args_checkbox, code=code)
    checkbox = CheckboxButtonGroup(labels=labels, active=list(range(len(labels))), callback=callback)

    # Select all/none:
    handle_list_as_string = str(list(range(len(glyph_renderers))))
    code_button_tail = "checkbox.active = labels;" + code.replace('cb_obj', 'checkbox')
    select_all = Button(label="All", callback=CustomJS(args=dict({'checkbox':checkbox}, **args_checkbox),
                                                       code="var labels = {}; ".format(handle_list_as_string) + code_button_tail))
    select_none = Button(label="None", callback=CustomJS(args=dict({'checkbox':checkbox}, **args_checkbox),
                                                       code="var labels = {}; ".format('[]') + code_button_tail))

    if max_checkbox_length is not None and len(glyph_renderers) > max_checkbox_length:
        # Keep all and none buttons, but create new checkboxes and return a list
        slices = list(range(0, len(glyph_renderers), max_checkbox_length)) + [len(glyph_renderers)]
        checkboxes = [get_checkbox(glyph_renderers[s:e], labels[s:e])[0] for s, e in zip(slices[:-1], slices[1:])]
        return checkboxes, select_all, select_none

    return checkbox, select_all, select_none
Exemple #7
0
def build_filter_controls(options):
    server_names = options['server_names']
    server_select = RadioButtonGroup(labels=server_names, active=0)

    year_select = RangeSlider(start=options['year-start'],
                              end=options['year-end'],
                              value=(options['year-start'],
                                     options['year-end']),
                              step=1)  #, title="Year")

    month_select = MultiSelect(title="Month:",
                               value=['0'],
                               options=options['month'])

    day_select = RangeSlider(start=1, end=31, value=(1, 31),
                             step=1)  ###, title="Day")

    day_week_select = CheckboxButtonGroup(  #title='Dia da semana',
        labels=options['day_week'])  #,
    #active=[i for i in range(len(options['day_week']))])

    time_select = RangeSlider(start=0,
                              end=24,
                              value=(0, 24),
                              step=1,
                              title="Period")

    scale_select = RadioButtonGroup(labels=querys.scale, active=0)

    def select_data():
        print('data select')
        server_name = server_names[server_select.active]
        months = month_select.value
        days = day_select.value
        day_week = day_week_select.active
        years = year_select.value
        time = time_select.value
        scale = querys.scale_str[scale_select.active]

        db = database.db

        sql = build_query(server_name, scale, years, months, days, day_week,
                          time)
        print(sql)
        #

        return pd.io.sql.read_sql(sql, db)

    return [
        server_select, scale_select, year_select, month_select, day_select,
        day_week_select, time_select
    ], select_data
Exemple #8
0
    def create_visibility_checkbox(self) -> CheckboxButtonGroup:
        """
        Toggles crosshair and axes visiblity on or off.

        Returns
        -------
        CheckboxButtonGroup
            A button group to change the visibility of the crosshair and axes
            in the figures.
        """

        visibility_checkbox = CheckboxButtonGroup(
            labels=self.CHECKBOX_LABELS, active=[0, 2]
        )
        # visibility_checkbox.on_change("active", handle_checkbox)
        return visibility_checkbox
    def make_inputs(self):
        columns = [
            TableColumn(field='x', title='x'),
            TableColumn(field='y', title='y'),
            TableColumn(field='device', title='device'),
            TableColumn(field='platform', title='platform')
        ]

#        obj.data_display0 = DataTable(source=obj.source2, columns=columns)
#        obj.data_display1 = DataTable(source=obj.source3, columns=columns)

        # setup user input
        self.x_axis_options = Select(title="X:", value='size', options=axis_options)
        self.y_axis_options = Select(title="Y:", value='throughput [1/sec]', options=axis_options)
        self.benchmarks = Select(title="Benchmark:", value=benchmark_names[0],
            options=benchmark_names)
        self.device_names = CheckboxGroup(labels=device_names, active=[0])
        self.platform_names = CheckboxButtonGroup(labels=platform_names, active=[0])
Exemple #10
0
def set_globals(parsed_result):
    global button_generate, buttons_toggle_x, dropdown_eval_method, slider_n_points, max_pars, source, old_active_list
    global result, x_eval_selectors, layout, x_eval_selectors_values, button_partial_dependence, y_value, button_color_map, colorbar, button_draw_confidence

    # Here we se the values of the global variables and create the layout
    result = parsed_result
    x_eval_selectors_values = copy.copy(result.x)
    max_pars = len(result.space.dimensions)

    # Layout
    button_generate = Button(label="Generate", button_type="success")
    button_generate.on_click(lambda: handle_button_generate(layout, result))
    buttons_toggle_x = CheckboxButtonGroup(
        labels=['x ' + str(s) for s in range(max_pars)], active=[])
    button_partial_dependence = Toggle(label="Use partial dependence",
                                       button_type="default")
    button_color_map = Toggle(label="Use same color map",
                              button_type="default")
    button_draw_confidence = Toggle(label="Draw upper confidence limit",
                                    button_type="default")
    dropdown_eval_method = Select(
        title="Evaluation method:",
        value='Result',
        options=['Result', 'Exp min', 'Exp min rand', 'Sliders'],
        width=200,
        height=40)
    slider_n_points = Slider(start=1,
                             end=20,
                             value=10,
                             step=1,
                             title="n-points",
                             width=200,
                             height=10)
    y_value = Div(text="""""", width=300, height=200)
    colorbar = Div(
    )  # We initiate colorbar as an empty div first and then change it to a plot in case we want to show it
    row_plots = row([])
    row_top = row(button_generate, buttons_toggle_x)
    col_right_side = column(button_partial_dependence, button_color_map,
                            button_draw_confidence, dropdown_eval_method,
                            slider_n_points, y_value, colorbar)
    col_left_side = column(row_top, row_plots)
    layout = row(col_left_side, col_right_side)
Exemple #11
0
    def __init__(self, node_id, dtype, sensor_names, dates):
        """
        :param node_id: str
        :param dtype: str
        :param sensor_names: [str]
        :param dates: str

        DataSet class. This class contains all the data for node and sensor type. node_id is the nodes unique id, dtype is the string
        data type for the node (e.g. 'Temperature', sensor names is the list of sensors with that data type, and date is the date of
        the data in YYYY-MM-DD format.
        """
        self.id = node_id
        self.dtype = dtype
        self.sensor_names = sensor_names
        self.dates = dates
        self.sources = {}
        self.used_sources = {}
        self.null_sources = {}
        self.cbg = CheckboxButtonGroup(labels=self.sensor_names, active=[i for i in range(len(self.sensor_names))])
        self.wb = widgetbox(self.cbg, width=600)
        self.plot = figure(title=self.dtype + ' data from node ' + self.id,
                           x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,save,box_select")
menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button",
                 type="danger",
                 menu=menu,
                 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()
Exemple #13
0
        ("Item 3", "item_3_value")]
dropdown = Dropdown(label="Dropdown button",
                    button_type="warning",
                    menu=menu,
                    default_value="item_1_value")

split_menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None,
              ("Item 3", "item_3_value")]
split = Dropdown(label="Split button", button_type="danger", menu=split_menu)

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

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

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

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

text_input = TextInput(placeholder="Enter value ...")

autocomplete_input = AutocompleteInput()

select = Select(options=["Option 1", "Option 2", "Option 3"])

multi_select = MultiSelect(options=["Option %d" % (i + 1) for i in range(16)],
                           size=6)

slider = Slider(value=10, start=0, end=100)
Exemple #14
0
                               options=FILTER_PROPERTIES[c.AMENITIES])
AMENITIES_SELECT.on_change(c.VALUE, update_data)

PROPERTY_TYPE_SELECT = MultiSelect(title='Property Type:',
                                   value=[],
                                   options=FILTER_PROPERTIES[c.PT])
PROPERTY_TYPE_SELECT.on_change(c.VALUE, update_data)

NEIGHBOURHOOD_SELECT = MultiSelect(title='Neighbourhood:',
                                   value=[],
                                   options=FILTER_PROPERTIES[c.NC])
NEIGHBOURHOOD_SELECT.on_change(c.VALUE, update_data)

# Checkbox Group (Multi Select) Widgets
NG_LIST = FILTER_PROPERTIES[c.NGC]
NEIGHBOURHOOD_GROUP = CheckboxButtonGroup(labels=NG_LIST,
                                          active=list(range(0, len(NG_LIST))))
NEIGHBOURHOOD_GROUP.on_change(c.ACTIVE, update_data)

RT_LIST = FILTER_PROPERTIES[c.RT]
ROOM_TYPE_GROUP = CheckboxButtonGroup(labels=FILTER_PROPERTIES[c.RT],
                                      active=list(range(0, len(RT_LIST))))
ROOM_TYPE_GROUP.on_change(c.ACTIVE, update_data)

# Single Select Widgets
PROPERTY_TYPE_HOST = Select(title='Property Type:',
                            value=c.EMPTY_STRING,
                            options=[c.EMPTY_STRING] + FILTER_PROPERTIES[c.PT])
N_HOST = Select(title='Neighbourhood:',
                value=c.EMPTY_STRING,
                options=[c.EMPTY_STRING] + FILTER_PROPERTIES[c.NC])
NG_HOST = Select(title='Neighbourhood Group:',
Exemple #15
0
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.js_on_click(CustomJS(code="console.log('dropdown: ' + this.value, this.toString())"))

dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", disabled=True, menu=menu)
dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())"))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#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.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.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.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.js_on_click(CustomJS(code="console.log('radio_button_group: ' + this.active, this.toString())"))

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

doc = Document()
doc.add_root(widget_box)
Exemple #16
0
import numpy as np
import h5py

from bokeh.plotting import Figure
from bokeh.models import ColumnDataSource, HBox, VBoxForm
from bokeh.models.widgets import Select, CheckboxButtonGroup
from bokeh.io import curdoc


data_select = Select(title="Output:", value="hip_strength", options=["hip_strength", "knee_strength"])
checkbox_button_group = CheckboxButtonGroup(labels=["option 1", "option 2"], active=[0, 1])

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

p = Figure(plot_height=600, plot_width=800, title="", toolbar_location=None)
renderer = p.line(x="x", y="y", alpha=1, source=source)


# Fast direct read from hdf5
def get_data(f, name):
    shape = f[name].shape
    # Empty array
    data = np.empty(shape, dtype=np.float64)
    # read_direct to empty arrays
    f[name].read_direct(data)
    return data


def select_data():
    data_val = data_select.value
    with h5py.File('demo_data.hdf5', 'r') as f:
Exemple #17
0
    def __init__(self, z, p, retrieval):
        self.z = z
        self.p = p

        y = z

        self.retrieval = retrieval
        self.retrieval_quantities = retrieval.retrieval_quantities

        self.figures = dict([(rq,
                              ProfilePlot(self.z,
                                          self.p,
                                          rq.name,
                                          "rq_plot_" + rq.name,
                                          width=400))
                             for rq in self.retrieval_quantities])
        self.status = dict([(rq, True) for rq in self.retrieval_quantities])
        self.sources_x = dict([(rq, []) for rq in self.retrieval_quantities])
        self.sources_xa = dict([(rq, []) for rq in self.retrieval_quantities])
        self.sources_x0 = dict([(rq, []) for rq in self.retrieval_quantities])
        self.lines_x = dict([(rq, []) for rq in self.retrieval_quantities])
        self.lines_xa = dict([(rq, []) for rq in self.retrieval_quantities])
        self.lines_x0 = dict([(rq, []) for rq in self.retrieval_quantities])

        #
        # Get retrieval results as list.
        #
        if type(self.retrieval.results) is list:
            results = self.retrieval.results
        else:
            results = [self.retrieval.results]

        self.colors = Inferno[len(results) + 2][1:-1]

        #
        # Add plots for each retrieval quantity.
        #

        for i, rr in enumerate(self.retrieval.results):
            for rq in self.retrieval_quantities:
                xa = rr.get_result(rq, attribute="xa")
                x = rr.get_result(rq, attribute="x")
                x0 = rr.get_result(rq, attribute="x0")

                if xa is None:
                    continue

                self.sources_x[rq] += [ColumnDataSource(data=dict(x=x, y=y))]
                self.sources_xa[rq] += [ColumnDataSource(data=dict(x=xa, y=y))]
                self.sources_x0[rq] += [ColumnDataSource(data=dict(x=x0, y=y))]

                fig = self.figures[rq]
                fig.add_quantity(x,
                                 line_kwargs=dict(line_color=self.colors[i],
                                                  line_width=2))
                if i == 0:
                    fig.add_quantity(xa,
                                     line_kwargs=dict(
                                         line_dash="dashed",
                                         line_color=self.colors[i],
                                         line_width=2))
                #fig.add_quantity(x0, line_kwargs = dict(line_dash  = "dashdot",
                #                                        line_color = self.colors[i],
                #                                        line_width = 2))

        self.plots = row(*[self.figures[k].doc for k in self.figures],
                         name="retrieval_quantities")

        def update_plots(attrname, old, new):
            state = self.checks.active
            plots = curdoc().get_model_by_name('retrieval_quantities')

            print(state)
            for i, rq in enumerate(self.retrieval_quantities):
                if i in state:
                    if self.status[rq] == True:
                        continue
                    else:
                        self.status[rq] = True
                        plots.children.append(self.figures[rq].doc)
                else:
                    if self.status[rq] == False:
                        continue
                    else:
                        fig = curdoc().get_model_by_name("rq_plot_" + rq.name)
                        self.status[rq] = False
                        plots.children.remove(fig)

            print(plots.children)
            print(self.status)

        #
        # Checkbox button to hide plots
        #

        labels = [rq.name for rq in self.retrieval.retrieval_quantities]
        active = list(range(len(labels)))
        self.checks = CheckboxButtonGroup(labels=labels, active=active)
        self.checks.on_change("active", update_plots)
Exemple #18
0
button.on_click(animate)

team_Blue = plot.patch('xc',
                       'yc',
                       source=source2,
                       alpha=0,
                       line_width=3,
                       fill_color='dodgerblue')
team_red = plot.patch('ax',
                      'ay',
                      source=source3,
                      alpha=0,
                      line_width=3,
                      fill_color='orangered')

checkbox_blue = CheckboxButtonGroup(labels=["Team Blue"],
                                    button_type="primary")
checkbox_red = CheckboxButtonGroup(labels=["Team Red"], button_type="primary")

checkbox_blue.callback = CustomJS(args=dict(l0=team_Blue,
                                            checkbox=checkbox_blue),
                                  code="""
l0.visible = 0 in checkbox.active;
l0.glyph.fill_alpha = 0.3;
""")
checkbox_red.callback = CustomJS(args=dict(l0=team_red, checkbox=checkbox_red),
                                 code="""
l0.visible = 0 in checkbox.active;
l0.glyph.fill_alpha = 0.3;
""")

p = Paragraph(text="""Select team  to plot convex hull""", width=200)
Exemple #19
0
class Interface:
    def __init__(self):

        self.grepolis = Grepolis()

        imgRessource = []
        for v in ["Bois", "Pierre", "Argent"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgRessource.append(Image(d))
        colRess = column(*[img.figure for img in imgRessource])
        self.inputRess = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Bois", "Pierre", "Argent"]
        ]
        colinputRess = column(*self.inputRess)

        imgDieu = []
        for v in ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDieu.append(Image(d, multiplier=3))
        rowDieu = [HFill(5)]
        for img in imgDieu:
            rowDieu.append(HFill(5))
            rowDieu.append(img.figure)
        rowDieu = row(*rowDieu)

        imgAtt = []
        for v in ["Att_hack", "Att_sharp", "Att_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgAtt.append(Image(d))
        colAtt = column(*[img.figure for img in imgAtt])
        self.inputAtt = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        colinputAtt = column(*self.inputAtt)

        imgDef = []
        for v in ["Def_hack", "Def_sharp", "Def_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDef.append(Image(d))
        colDef = column(*[img.figure for img in imgDef])

        self.inputDef = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        rowinputDef = column(*self.inputDef)

        imgOther = []
        for v in ["Vitesse", "Butin", "Faveur"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgOther.append(Image(d))

        colOther = column(*[img.figure for img in imgOther])

        self.inputFavBut = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Vitesse", "Butin", "Faveur"]
        ]
        self.inputOther = column(*self.inputFavBut)

        self.imgUnit = []
        for v in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
        ]:
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit.append(Image(d, multiplier=2))
        rowUnit = row(HFill(10), *[img.figure for img in self.imgUnit])

        imgDefAtt = []
        for v in ["Pop", "Attaque", "Defense"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDefAtt.append(Image(d))

        rowInputUnit = [HFill(10)]
        self.unitInput = [
            TextInput(value="", title=el + " :", width=80) for el in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
            ]
        ]
        for inp in self.unitInput:
            rowInputUnit.append(inp)
            rowInputUnit.append(HFill(30))
        rowInputUnit = row(HFill(10), *rowInputUnit)

        self.selectUnit = CheckboxButtonGroup(labels=[
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye", "Centaure", "Pegase"
        ],
                                              active=[i for i in range(9)])
        self.selectUnit.on_change("active", self.updateSelectUnit)
        self.Dieu = RadioButtonGroup(
            labels=["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"],
            active=0,
            width=1110)
        self.Dieu.on_change('active', self.updateUnit)

        self.attdef = RadioButtonGroup(labels=["Attaque", "Defense"],
                                       active=0,
                                       width=200)
        self.attdef.on_change('active', self.switchAttDef)

        self.typeAtt = RadioGroup(
            labels=["Armes Contondantes", "Armes Blanches", "Armes de Jet"],
            active=0,
            width=150)
        self.typeAtt.on_change('active', self.process2)
        self.imgFaveur = Image(dict(url=["static/" + "Faveur" + ".png"]))

        self.launch = Button(label="Lancer")
        self.launch.on_click(self.process)

        self.inputPop = TextInput(value="1500",
                                  title="Population : ",
                                  width=120)
        self.inputPop.on_change("value", self.process2)

        self.inputFav = TextInput(value="1500",
                                  title="Faveur Max : ",
                                  width=120)
        self.inputFav.on_change("value", self.process2)

        rowPop = row(HFill(10), self.typeAtt, imgDefAtt[1].figure, self.attdef,
                     HFill(30), imgDefAtt[2].figure, HFill(50),
                     imgDefAtt[0].figure, self.inputPop, HFill(50),
                     self.imgFaveur.figure, self.inputFav, HFill(50))
        self.doc = column(
            rowDieu, self.Dieu, VFill(20), rowPop, VFill(20), self.selectUnit,
            rowUnit, rowInputUnit, VFill(20),
            row(HFill(50), colRess, colinputRess,
                HFill(40), colAtt, colinputAtt, HFill(40), colDef, rowinputDef,
                HFill(40), colOther, self.inputOther))
        #curdoc().add_root(column(rowDieu,self.Dieu,VFill(20),rowPop,VFill(20),self.selectUnit,rowUnit,rowInputUnit,VFill(20),row(HFill(50),colRess,colinputRess,HFill(40),colAtt,colinputAtt,HFill(40),colDef,rowinputDef,HFill(40),colOther,self.inputOther)))
        self.process(None)
        #curdoc().title = "Grepolis"

    def updateUnit(self, attrname, old, new):
        L = ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]
        print(self.selectUnit.active)
        if L[new] == "Poseidon":
            self.imgUnit[-1].figure.visible = False
            self.unitInput[-1].visible = False
            self.selectUnit.active = [1, 2, 3, 4, 5, 6, 7]
        else:
            self.imgUnit[-1].figure.visible = True
            self.unitInput[-1].visible = True
            self.selectUnit.active = [1, 2, 3, 4, 5, 6, 7, 8]
        self.grepolis.setDieu(L[new])
        unit = Add(L[new])
        self.selectUnit.labels = [
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye"
        ] + unit
        for i, v in enumerate(unit):
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit[-2 + i].update(d)
            self.unitInput[-2 + i].title = v + " : "
        self.process(None)

    def process2(self, attrname, old, new):
        self.process(None)

    def switchAttDef(self, attrname, old, new):
        if self.attdef.active == 0:
            self.typeAtt.disabled = False
        else:
            self.typeAtt.disabled = True
        self.process(None)

    def updateSelectUnit(self, attrname, old, new):
        N = len(self.selectUnit.labels)
        active = self.selectUnit.active
        zeros = [i for i in range(N) if i not in active]
        for inp in [self.unitInput[i] for i in zeros]:
            inp.value = str(0)
        self.process(None)

    def process(self, attrname):
        try:
            pop = int(self.inputPop.value)
            favmax = int(self.inputFav.value)
            active = self.selectUnit.active
            type = self.typeAtt.active
            if self.attdef.active == 0:
                X, Att, Def, Prix, Speed, Pops, butin = self.grepolis.optimAttaque(
                    pop=pop, favmax=favmax, active=active, type=type)

            else:
                X, Att, Def, Prix, Speed, Pops, butin = self.grepolis.optimDefense(
                    pop=pop, favmax=favmax, active=active)
            for v, inp in zip(X, [self.unitInput[i] for i in active]):
                inp.value = str(v)
            for v, inp in zip(Att, self.inputAtt):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for v, inp in zip(Def, self.inputDef):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for v, inp in zip(Prix, self.inputRess):
                inp.value = str(v) + " /u - " + str(int(v * pop))
            for i, (v, inp) in enumerate(
                    zip([Speed, butin, Prix[3]], self.inputFavBut)):
                #add = ""
                #if i > 0:
                #    add = + " /u - " +str(int(v*pop))
                #print(v,add)
                inp.value = str(v) + " /u - " + str(int(
                    v * pop)) if i != 0 else str(v)
        except:
            pass
from bokeh.plotting import figure
from bokeh.palettes import RdBu3

x=[3,4,6,12,10,1]
y=[7,1,3,4,1,6]
z=['red','red','red','blue','blue','blue']

source = ColumnDataSource(data=dict(x=x, y=y,z=z))
color_mapper = CategoricalColorMapper(factors=['red','blue'], palette=[RdBu3[2], RdBu3[0]])

plot_figure = figure(title='Checkbox Button Group',plot_height=450, plot_width=600,
              tools="save,reset", toolbar_location="below")

plot_figure.scatter('x', 'y', source=source, size=10,color={'field': 'z', 'transform': color_mapper})

checkbox_button = CheckboxButtonGroup(labels=['Show x-axis label','Show y-axis label'])

def checkbox_button_click(attr,old,new):
    active_checkbox=checkbox_button.active ##Getting checkbox value in list

    ## Get first checkbox value and show x-axis label

    if len(active_checkbox)!=0 and (0 in active_checkbox):
        plot_figure.xaxis.axis_label='X-Axis'
    else:
        plot_figure.xaxis.axis_label = None

    ## Get second checkbox value and show y-axis label

    if len(active_checkbox)!=0 and (1 in active_checkbox):
        plot_figure.yaxis.axis_label='Y-Axis'
Exemple #21
0
)

menu = [("Item 1", "1"), ("Item 2", "2"), ("Item 3", "3")]

layout = column(
    Button(label="Default Button 1", button_type="default"),
    Button(label="Primary Button 2", button_type="primary"),
    Button(label="Success Button 3", button_type="success"),
    Toggle(label="Default Toggle 1", button_type="default"),
    Toggle(label="Primary Toggle 2", button_type="primary"),
    Toggle(label="Success Toggle 3", button_type="success"),
    Dropdown(label="Default Dropdown 1", button_type="default", menu=menu),
    Dropdown(label="Primary Dropdown 2", button_type="primary", menu=menu),
    Dropdown(label="Success Dropdown 3", button_type="success", menu=menu),
    CheckboxButtonGroup(
        labels=["Checkbox Option 1", "Checkbox Option 2", "Checkbox Option 3"],
        button_type="default",
        active=[0, 1]),
    CheckboxButtonGroup(
        labels=["Checkbox Option 4", "Checkbox Option 5", "Checkbox Option 6"],
        button_type="primary",
        active=[1, 2]),
    CheckboxButtonGroup(
        labels=["Checkbox Option 7", "Checkbox Option 8", "Checkbox Option 9"],
        button_type="success",
        active=[0, 2]),
    RadioButtonGroup(
        labels=["Radio Option 1", "Radio Option 2", "Radio Option 3"],
        button_type="default",
        active=0),
    RadioButtonGroup(
        labels=["Radio Option 4", "Radio Option 5", "Radio Option 6"],
def density_tab(flights):

    # Dataset for density plot based on carriers, range of delays,
    # and bandwidth for density estimation
    def make_dataset(carrier_list, range_start, range_end, bandwidth):

        xs = []
        ys = []
        colors = []
        labels = []

        for i, carrier in enumerate(carrier_list):
            subset = flights[flights['name'] == carrier]
            subset = subset[subset['arr_delay'].between(
                range_start, range_end)]
            kde = gaussian_kde(subset['arr_delay'], bw_method=bandwidth)

            # Evenly space x values
            x = np.linspace(range_start, range_end, 100)
            # Evaluate pdf at every value of x
            y = kde.pdf(x)

            # Append the values to plot
            xs.append(list(x))
            ys.append(list(y))

            # Append the colors and label
            colors.append(airline_colors[i])
            labels.append(carrier)

        new_src = ColumnDataSource(data={
            'x': xs,
            'y': ys,
            'color': colors,
            'label': labels
        })
        return new_src

    def make_plot(src):
        p = figure(plot_width=700,
                   plot_height=700,
                   title='Density Plot of Arrival Delays by Airline',
                   x_axis_label='Delay (min)',
                   y_axis_label='Density')
        p.multi_line('x',
                     'y',
                     color='color',
                     legend='label',
                     line_width=3,
                     source=src)

        # Hover tool with next line policy
        hover = HoverTool(tooltips=[('Carrier', '@label'), ('Delay', '$x'),
                                    ('Density', '$y')],
                          line_policy='next')

        # Add the hover tool and styling
        p.add_tools(hover)

        p = style(p)

        return p

    def update(attr, old, new):
        # List of carriers to plot
        carriers_to_plot = [
            carrier_selection.labels[i] for i in carrier_selection.active
        ]

        # If no bandwidth is selected, use the default value
        if bandwidth_choose.active == []:
            bandwidth = None
        # If the bandwidth select is activated, use the specified bandwith
        else:
            bandwidth = bandwidth_select.value

        new_src = make_dataset(carriers_to_plot,
                               range_start=range_select.value[0],
                               range_end=range_select.value[1],
                               bandwidth=bandwidth)
        src.data.update(new_src.data)

    def style(p):
        # Title
        p.title.align = 'center'
        p.title.text_font_size = '20pt'
        p.title.text_font = 'serif'

        # Axis titles
        p.xaxis.axis_label_text_font_size = '14pt'
        p.xaxis.axis_label_text_font_style = 'bold'
        p.yaxis.axis_label_text_font_size = '14pt'
        p.yaxis.axis_label_text_font_style = 'bold'

        # Tick labels
        p.xaxis.major_label_text_font_size = '12pt'
        p.yaxis.major_label_text_font_size = '12pt'

        return p

    # Carriers and colors
    available_carriers = sorted(set(flights['name']))

    airline_colors = Category20_16
    airline_colors.sort()

    # Carriers to plot
    carrier_selection = CheckboxGroup(labels=available_carriers, active=[0, 1])
    carrier_selection.on_change('active', update)

    # Range to plot
    range_select = RangeSlider(start=-60,
                               end=180,
                               value=(-60, 120),
                               step=5,
                               title='Delay Range (min)')
    range_select.on_change('value', update)

    # Initial carriers and data source
    initial_carriers = [
        carrier_selection.labels[i] for i in carrier_selection.active
    ]

    # Bandwidth of kernel
    bandwidth_select = Slider(start=0.1,
                              end=5,
                              step=0.1,
                              value=0.5,
                              title='Bandwidth for Density Plot')
    bandwidth_select.on_change('value', update)

    # Whether to set the bandwidth or have it done automatically
    bandwidth_choose = CheckboxButtonGroup(
        labels=['Choose Bandwidth (Else Auto)'], active=[])
    bandwidth_choose.on_change('active', update)

    # Make the density data source
    src = make_dataset(initial_carriers,
                       range_start=range_select.value[0],
                       range_end=range_select.value[1],
                       bandwidth=bandwidth_select.value)

    # Make the density plot
    p = make_plot(src)

    # Add style to the plot
    p = style(p)

    # Put controls in a single element
    controls = WidgetBox(carrier_selection, range_select, bandwidth_select,
                         bandwidth_choose)

    # Create a row layout
    layout = row(controls, p)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Density Plot')

    return tab
Exemple #23
0
    def _get_widgets(self, all_glyphs, overtime_groups, run_groups, slider_labels=None):
        """Combine timeslider for quantiles and checkboxes for individual runs in a single javascript-snippet

        Parameters
        ----------
        all_glyphs: List[Glyph]
            togglable bokeh-glyphs
        overtime_groups, run_groups: Dicŧ[str -> List[int]
            mapping labels to indices of the all_glyphs-list
        slider_labels: Union[None, List[str]]
            if provided, used as labels for timeslider-widget

        Returns
        -------
        time_slider, checkbox, select_all, select_none: Widget
            desired interlayed bokeh-widgets
        checkbox_title: Div
            text-element to "show title" of checkbox
        """
        aliases = ['glyph' + str(idx) for idx, _ in enumerate(all_glyphs)]
        labels_overtime = list(overtime_groups.keys())
        labels_runs = list(run_groups.keys())

        code = ""
        # Define javascript variable with important arrays
        code += "var glyphs = [" + ", ".join(aliases) + "];"
        code += "var overtime = [" + ','.join(['[' + ','.join(overtime_groups[l]) + ']' for l in labels_overtime]) + '];'
        code += "var runs = [" + ','.join(['[' + ','.join(run_groups[l]) + ']' for l in labels_runs]) + '];'
        # Deactivate all glyphs
        code += """
        glyphs.forEach(function(g) {
          g.visible = false;
        })"""
        # Add function for array-union (to combine all relevant glyphs for the different runs)
        code += """
        // union function
        function union_arrays(x, y) {
          var obj = {};
          for (var i = x.length-1; i >= 0; -- i)
             obj[x[i]] = x[i];
          for (var i = y.length-1; i >= 0; -- i)
             obj[y[i]] = y[i];
          var res = []
          for (var k in obj) {
            if (obj.hasOwnProperty(k))  // <-- optional
              res.push(obj[k]);
          }
          return res;
        }"""
        # Add logging
        code += """
        console.log("Timeslider: " + time_slider.value);
        console.log("Checkbox: " + checkbox.active);"""
        # Set timeslider title (to enable log-scale and print wallclocktime-labels)
        if slider_labels:
            code += "var slider_labels = " + str(slider_labels) + ";"
            code += "console.log(\"Detected slider_labels: \" + slider_labels);"
            code += "time_slider.title = \"Until wallclocktime \" + slider_labels[time_slider.value - 1] + \". Step no.\"; "
            title = "Until wallclocktime " + slider_labels[-1] + ". Step no. "
        else:
            title = "Quantile on {} scale".format("logarithmic" if self.timeslider_log else "linear")
            code += "time_slider.title = \"{}\";".format(title);
        # Combine checkbox-arrays, intersect with time_slider and set all selected glyphs to true
        code += """
        var activate = [];
        // if we want multiple checkboxes at the same time, we need to combine the arrays
        checkbox.active.forEach(function(c) {
          activate = union_arrays(activate, runs[c]);
        })
        // now the intersection of timeslider-activated and checkbox-activated
        activate = activate.filter(value => -1 !== overtime[time_slider.value - 1].indexOf(value));
        activate.forEach(function(idx) {
          glyphs[idx].visible = true;
        })
        """

        num_quantiles = len(overtime_groups)
        if num_quantiles > 1:
            timeslider = Slider(start=1, end=num_quantiles, value=num_quantiles, step=1, title=title)
        else:
            timeslider = Slider(start=1, end=2, value=1)
        labels_runs = [label.replace('_', ' ') if label.startswith('budget') else label for label in labels_runs]
        checkbox = CheckboxButtonGroup(labels=labels_runs, active=list(range(len(labels_runs))))

        args = {name: glyph for name, glyph in zip(aliases, all_glyphs)}
        args['time_slider'] = timeslider
        args['checkbox'] = checkbox
        callback = CustomJS(args=args, code=code)
        timeslider.js_on_change('value', callback)
        checkbox.callback = callback
        checkbox_title = Div(text="Showing only configurations evaluated in:")

        # Add all/none button to checkbox
        code_all  = "checkbox.active = " + str(list(range(len(labels_runs)))) + ";" + code
        code_none = "checkbox.active = [];" + code
        select_all  = Button(label="All", callback=CustomJS(args=args, code=code_all))
        select_none = Button(label="None", callback=CustomJS(args=args, code=code_none))

        return timeslider, checkbox, select_all, select_none, checkbox_title
Exemple #24
0
speed_source = ColumnDataSource(data=gen_dict(speed))
drunk_source = ColumnDataSource(data=gen_dict(drunk))

other_circles = fig.circle(source=other_source, x="x", y="y", radius="r", fill_color="gray",
            fill_alpha=.3, line_alpha=0, hover_alpha=1, hover_color="yellow", legend="Other")
speed_circles = fig.circle(source=speed_source, x="x", y="y", radius="r", fill_color="blue",
            fill_alpha=.3, line_alpha=0, hover_alpha=1, hover_color="yellow", legend="Speeding")
drunk_circles = fig.circle(source=drunk_source, x="x", y="y", radius="r", fill_color="red",
            fill_alpha=.3, line_alpha=0, hover_alpha=1, hover_color="yellow", legend="Drunk")

dot_tooltips = [("Date", "@MONTH/@DAY/@YEAR"), ("Fatalities", "@FATALS"), ("Drunk", "@DRUNK_DR"),
                ("Speeding", "@SP"), ("Weather", "@WEATHER")]

fig.add_tools(HoverTool(renderers=[other_circles, speed_circles, drunk_circles], tooltips=dot_tooltips))

button_group = CheckboxButtonGroup(
        labels=["Other", "Speeding", "Drunk"], active=[0, 1, 2], width=200)

toggle = Toggle(label="Sort by Hour", button_type="default")

slider = Slider(title="Hour (Military Time)", start=0, end=23, value=0, step=1)

empty_dict = dict(
        x=np.array([]),
        y=np.array([]),
        r=np.array([]),
        MONTH=np.array([]),
        DAY=np.array([]),
        YEAR=np.array([]),
        FATALS=np.array([]),
        DRUNK_DR=np.array([]),
        SP=np.array([]),
class BenchmarkApp(HBox):
    """An example of a browser-based, interactive plot with slider controls."""

    extra_generated_classes = [["BenchmarkApp", "BenchmarkApp", "HBox"]]

    inputs = Instance(VBoxForm)

    # widgets
    benchmarks = Instance(Select)
    x_axis_options = Instance(Select)
    y_axis_options = Instance(Select)
    # TODO: Convert this to a MultiSelect once it is fixed
    # https://github.com/bokeh/bokeh/issues/2495
    device_names = Instance(CheckboxGroup)
    platform_names = Instance(CheckboxButtonGroup)
    # data displays, not enabled by default
    data_display0 = Instance(DataTable)
    data_display1 = Instance(DataTable)

    # plot and interaction
    plot = Instance(Plot)
    hover = Instance(HoverTool)
    # data
    source0 = Instance(ColumnDataSource)
    source1 = Instance(ColumnDataSource)
    source2 = Instance(ColumnDataSource)
    source3 = Instance(ColumnDataSource)
    source4 = Instance(ColumnDataSource)
    source5 = Instance(ColumnDataSource)
    source6 = Instance(ColumnDataSource)
    source7 = Instance(ColumnDataSource)
    source8 = Instance(ColumnDataSource)
    source9 = Instance(ColumnDataSource)

    def make_source(self):
        # set up the data source
        self.source0 = ColumnDataSource(data=dict())
        self.source1 = ColumnDataSource(data=dict())
        self.source2 = ColumnDataSource(data=dict())
        self.source3 = ColumnDataSource(data=dict())
        self.source4 = ColumnDataSource(data=dict())
        self.source5 = ColumnDataSource(data=dict())
        self.source6 = ColumnDataSource(data=dict())
        self.source7 = ColumnDataSource(data=dict())
        self.source8 = ColumnDataSource(data=dict())
        self.source9 = ColumnDataSource(data=dict())

    def make_inputs(self):
        columns = [
            TableColumn(field='x', title='x'),
            TableColumn(field='y', title='y'),
            TableColumn(field='device', title='device'),
            TableColumn(field='platform', title='platform')
        ]

#        obj.data_display0 = DataTable(source=obj.source2, columns=columns)
#        obj.data_display1 = DataTable(source=obj.source3, columns=columns)

        # setup user input
        self.x_axis_options = Select(title="X:", value='size', options=axis_options)
        self.y_axis_options = Select(title="Y:", value='throughput [1/sec]', options=axis_options)
        self.benchmarks = Select(title="Benchmark:", value=benchmark_names[0],
            options=benchmark_names)
        self.device_names = CheckboxGroup(labels=device_names, active=[0])
        self.platform_names = CheckboxButtonGroup(labels=platform_names, active=[0])

    @classmethod
    def create(cls):
        """One-time creation of app's objects.

        This function is called once, and is responsible for
        creating all objects (plots, datasources, etc)
        """
        obj = cls()

        obj.make_source()
        obj.make_inputs()
        obj.make_plot()
        obj.update_data()
        obj.set_children()

        return obj

    def plot_data(self, source, linecolor, symbolfill):
        self.plot.line(   'x', 'y', source=source, line_color=linecolor,
            line_width=3, line_alpha=0.6)
        self.plot.scatter('x', 'y', source=source, fill_color=symbolfill, size=8)

    def make_plot(self):

        # configure the toolset
        toolset = ['wheel_zoom,save,box_zoom,resize,reset']
        self.hover = BenchmarkApp.make_hovertool()
        toolset.append(self.hover)

        title = self.benchmarks.value + " " + \
            "(" + self.y_axis_options.value + " vs." + self.x_axis_options.value + ")"

        self.plot = figure(title_text_font_size="12pt",
            plot_height=400,
            plot_width=400,
            tools=toolset,
            title=title,
        )
        # remove the logo
        self.plot.logo = None

        # Generate a figure container
        # Plot the line by the x,y values in the source property
        self.plot_data(self.source0, "#F0A3FF", "white")
        self.plot_data(self.source1, "#0075DC", "white")
        self.plot_data(self.source2, "#993F00", "white")
        self.plot_data(self.source3, "#4C005C", "white")
        self.plot_data(self.source4, "#191919", "white")
        self.plot_data(self.source5, "#005C31", "white")
        self.plot_data(self.source6, "#2BCE48", "white")
        self.plot_data(self.source7, "#FFCC99", "white")
        self.plot_data(self.source8, "#808080", "white")
        self.plot_data(self.source9, "#94FFB5", "white")

        # set the x/y axis labels
#        plot.xaxis.axis_label = self.x_axis_options.value
#        plot.yaxis.axis_label = self.y_axis_options.value



    def set_children(self):
        self.inputs = VBoxForm(
            children=[self.benchmarks, self.device_names, self.platform_names,
                self.x_axis_options, self.y_axis_options,
#                self.data_display0, self.data_display1
            ]
        )

        self.children.append(self.inputs)
        self.children.append(self.plot)


    @classmethod
    def make_hovertool(self):
        hover = HoverTool(
            tooltips = [
                ("Device", "@device"),
                ("Backend", "@platform"),
                ("(x,y)", "(@x,@y)")
            ]
        )
        return hover

    def setup_events(self):
        """Attaches the on_change event to the value property of the widget.

        The callback is set to the input_change method of this app.
        """
        super(BenchmarkApp, self).setup_events()
        if not self.benchmarks:
            return

        # Event registration for everything except checkboxes
        self.benchmarks.on_change('value', self, 'benchmark_changed')
        self.x_axis_options.on_change('value', self, 'input_change')
        self.y_axis_options.on_change('value', self, 'input_change')

        # Event registration for checkboxes
        self.device_names.on_click(self.checkbox_handler)
        self.platform_names.on_click(self.checkbox_handler)

    def checkbox_handler(self, active):

        self.update_data()

    def benchmark_changed(self, obj, attrname, old, new):

        self.update_data()
        self.make_plot()
        curdoc().add(self)

    def input_change(self, obj, attrname, old, new):
        """Executes whenever the input form changes.

        It is responsible for updating the plot, or anything else you want.

        Args:
            obj : the object that changed
            attrname : the attr that changed
            old : old value of attr
            new : new value of attr
        """
        self.update_data()
        self.make_plot()
        curdoc().add(self)


    def getXY(self, celero_result, axis_filter):
        """Returns the X or Y value as specified by axis_filter"""

        # TODO: Remove the baseline measurement from the timing results
        if axis_filter == 'size':
            return celero_result['data_sizes']
        elif axis_filter == 'log2(size)':
            return np.log2(celero_result['data_sizes'])
        elif axis_filter == 'log10(size)':
            return np.log10(celero_result['data_sizes'])
        elif axis_filter == 'time [ms]':
            return celero_result['times'] * 1E-3
        elif axis_filter == 'throughput [1/sec]':
            return 1.0 / (celero_result['times'] * 1E-6)
        elif axis_filter == 'throughput [log2(1/sec)]':
            return np.log2(1.0 / (celero_result['times'] * 1E-6))
        elif axis_filter == 'throughput [log10(1/sec)]':
            return np.log10(1.0 / (celero_result['times'] * 1E-6))


    @classmethod
    def make_field_ids(self, id_number):
        """Creates a unique set of named fields for the y, device, and platform"""
        i = str(id_number)
        y_id = 'y' + i
        device_id = 'device' + i
        platform_id = 'platform' + i

        return [y_id, device_id, platform_id]


    def update_data(self):
        """Called each time that any watched property changes.

        This updates the sin wave data with the most recent values of the
        sliders. This is stored as two numpy arrays in a dict into the app's
        data source property.
        """

        # extract the user's input
        benchmark = self.benchmarks.value
        devices = list(device_names[i] for i in self.device_names.active)
        platforms = list(platform_names[i] for i in self.platform_names.active)
        x_axis_label = self.x_axis_options.value
        y_axis_label = self.y_axis_options.value


        # extract only the results which match this group
        filtered_results = filter(lambda x: x['benchmark_name'] == benchmark, celero_results)
        # remove the baseline measurements from the plots
        filtered_results = filter(lambda x: x['benchmark_name'] != "Baseline", filtered_results)

        # select the desired devices
        filtered_results = filter(lambda x: x['extra_data']['AF_DEVICE'] in devices, filtered_results)
        filtered_results = filter(lambda x: x['extra_data']['AF_PLATFORM'] in platforms, filtered_results)

        # extract the data
        sources = dict()
        result_number = 0
        for result in filtered_results:
            # ensure we don't plot too many results
            if result_number > MAX_PLOTS:
                break

            y_id, device_id, platform_id = self.make_field_ids(result_number)

            # Extract the results from the benchmark
            platform = result['extra_data']['AF_PLATFORM']
            device = result['extra_data']['AF_DEVICE']

            x = self.getXY(result, x_axis_label)
            y = self.getXY(result, y_axis_label)

            # store the benchmark results in the self.source object
            # NOTE: we replicate the device and platform data here so that
            # it works correctly with the mouseover/hover
            sources['x'] = x
            sources[y_id] = y
            sources[device_id] = [device] * len(x)
            sources[platform_id] = [platform] * len(x)

            # increment the counter
            result_number += 1

        # assign the data
        self.assign_source(sources, self.source0, 0)
        self.assign_source(sources, self.source1, 1)
        self.assign_source(sources, self.source2, 2)
        self.assign_source(sources, self.source3, 3)
        self.assign_source(sources, self.source4, 4)
        self.assign_source(sources, self.source5, 5)
        self.assign_source(sources, self.source6, 6)
        self.assign_source(sources, self.source7, 7)
        self.assign_source(sources, self.source8, 8)
        self.assign_source(sources, self.source9, 9)

    def assign_source(self, src, dest, index):
        """Assigns the data from src to the dictionary in dest if the
        corresponding data exists in src."""
        y_id, device_id, platform_id = self.make_field_ids(index)

        dest.data = dict()
        if y_id in src:
            dest.data['x'] = src['x']
            dest.data['y'] = src[y_id]
            dest.data['device'] = src[device_id]
            dest.data['platform'] = src[platform_id]
            dest._dirty = True
Exemple #26
0
    def __init__(self):

        self.grepolis = Grepolis()

        imgRessource = []
        for v in ["Bois", "Pierre", "Argent"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgRessource.append(Image(d))
        colRess = column(*[img.figure for img in imgRessource])
        self.inputRess = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Bois", "Pierre", "Argent"]
        ]
        colinputRess = column(*self.inputRess)

        imgDieu = []
        for v in ["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDieu.append(Image(d, multiplier=3))
        rowDieu = [HFill(5)]
        for img in imgDieu:
            rowDieu.append(HFill(5))
            rowDieu.append(img.figure)
        rowDieu = row(*rowDieu)

        imgAtt = []
        for v in ["Att_hack", "Att_sharp", "Att_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgAtt.append(Image(d))
        colAtt = column(*[img.figure for img in imgAtt])
        self.inputAtt = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        colinputAtt = column(*self.inputAtt)

        imgDef = []
        for v in ["Def_hack", "Def_sharp", "Def_distance"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDef.append(Image(d))
        colDef = column(*[img.figure for img in imgDef])

        self.inputDef = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Contondantes", "Blanches", "De Jet"]
        ]
        rowinputDef = column(*self.inputDef)

        imgOther = []
        for v in ["Vitesse", "Butin", "Faveur"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgOther.append(Image(d))

        colOther = column(*[img.figure for img in imgOther])

        self.inputFavBut = [
            TextInput(value="", title=el + " :", width=150)
            for el in ["Vitesse", "Butin", "Faveur"]
        ]
        self.inputOther = column(*self.inputFavBut)

        self.imgUnit = []
        for v in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
        ]:
            r = "static/" + v + ".jpg"
            d = dict(url=[r])
            self.imgUnit.append(Image(d, multiplier=2))
        rowUnit = row(HFill(10), *[img.figure for img in self.imgUnit])

        imgDefAtt = []
        for v in ["Pop", "Attaque", "Defense"]:
            r = "static/" + v + ".png"
            d = dict(url=[r])
            imgDefAtt.append(Image(d))

        rowInputUnit = [HFill(10)]
        self.unitInput = [
            TextInput(value="", title=el + " :", width=80) for el in [
                "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier",
                "Char", "Envoye", "Centaure", "Pegase"
            ]
        ]
        for inp in self.unitInput:
            rowInputUnit.append(inp)
            rowInputUnit.append(HFill(30))
        rowInputUnit = row(HFill(10), *rowInputUnit)

        self.selectUnit = CheckboxButtonGroup(labels=[
            "Combattant", "Frondeur", "Archer", "Hoplite", "Cavalier", "Char",
            "Envoye", "Centaure", "Pegase"
        ],
                                              active=[i for i in range(9)])
        self.selectUnit.on_change("active", self.updateSelectUnit)
        self.Dieu = RadioButtonGroup(
            labels=["Athena", "Artemis", "Hades", "Zeus", "Poseidon", "Hera"],
            active=0,
            width=1110)
        self.Dieu.on_change('active', self.updateUnit)

        self.attdef = RadioButtonGroup(labels=["Attaque", "Defense"],
                                       active=0,
                                       width=200)
        self.attdef.on_change('active', self.switchAttDef)

        self.typeAtt = RadioGroup(
            labels=["Armes Contondantes", "Armes Blanches", "Armes de Jet"],
            active=0,
            width=150)
        self.typeAtt.on_change('active', self.process2)
        self.imgFaveur = Image(dict(url=["static/" + "Faveur" + ".png"]))

        self.launch = Button(label="Lancer")
        self.launch.on_click(self.process)

        self.inputPop = TextInput(value="1500",
                                  title="Population : ",
                                  width=120)
        self.inputPop.on_change("value", self.process2)

        self.inputFav = TextInput(value="1500",
                                  title="Faveur Max : ",
                                  width=120)
        self.inputFav.on_change("value", self.process2)

        rowPop = row(HFill(10), self.typeAtt, imgDefAtt[1].figure, self.attdef,
                     HFill(30), imgDefAtt[2].figure, HFill(50),
                     imgDefAtt[0].figure, self.inputPop, HFill(50),
                     self.imgFaveur.figure, self.inputFav, HFill(50))
        self.doc = column(
            rowDieu, self.Dieu, VFill(20), rowPop, VFill(20), self.selectUnit,
            rowUnit, rowInputUnit, VFill(20),
            row(HFill(50), colRess, colinputRess,
                HFill(40), colAtt, colinputAtt, HFill(40), colDef, rowinputDef,
                HFill(40), colOther, self.inputOther))
        #curdoc().add_root(column(rowDieu,self.Dieu,VFill(20),rowPop,VFill(20),self.selectUnit,rowUnit,rowInputUnit,VFill(20),row(HFill(50),colRess,colinputRess,HFill(40),colAtt,colinputAtt,HFill(40),colDef,rowinputDef,HFill(40),colOther,self.inputOther)))
        self.process(None)
Exemple #27
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=
Exemple #28
0
                           name=dfs.string_widget_names[10])
# range sliders
widget_wavelengths = RangeSlider(start=dfs.default_limits_wavelength[0],
                                 end=dfs.default_limits_wavelength[1],
                                 value=(dfs.default_limits_wavelength),
                                 step=dfs.default_wavelength_step,
                                 title=dfs.string_title[8],
                                 name=dfs.string_widget_names[11])

# other widgets
widget_header = Div(text='<h1>' + dfs.string_header_one + '</h1><h3>' +
                    dfs.string_header_two + '</h3>',
                    width=500,
                    height=70)
widget_plot_types = CheckboxButtonGroup(
    labels=dfs.string_plot_types,
    active=dfs.default_plot_types,
    name=dfs.string_widget_names[12])  # TODO: make double-off == double-on
widget_message_box = Paragraph(text='hello')
widget_plot_step = Slider(start=dfs.default_plot_step[1],
                          end=dfs.default_plot_step[2],
                          value=dfs.default_plot_step[0],
                          step=dfs.default_plot_step_step,
                          title=dfs.string_plot_step)
widget_moon_days_header = Paragraph(text=dfs.string_title[7])
'''
plot it
- figures are the... yeah if you're reading this, then you know what that means
- tabN 'Panels' are panel spaces that are flipped between
- the 'tabs' variable builds the tabs bar and points them toward their respective panels

'''
def density_tab(flights):
	
	# Dataset for density plot based on carriers, range of delays,
	# and bandwidth for density estimation
	def make_dataset(carrier_list, range_start, range_end, bandwidth):

		xs = []
		ys = []
		colors = []
		labels = []

		for i, carrier in enumerate(carrier_list):
			subset = flights[flights['name'] == carrier]
			subset = subset[subset['arr_delay'].between(range_start, 
														range_end)]

			kde = gaussian_kde(subset['arr_delay'], bw_method=bandwidth)
			
			# Evenly space x values
			x = np.linspace(range_start, range_end, 100)
			# Evaluate pdf at every value of x
			y = kde.pdf(x)

			# Append the values to plot
			xs.append(list(x))
			ys.append(list(y))

			# Append the colors and label
			colors.append(airline_colors[i])
			labels.append(carrier)

		new_src = ColumnDataSource(data={'x': xs, 'y': ys, 
								   'color': colors, 'label': labels})

		return new_src

	def make_plot(src):
		p = figure(plot_width = 700, plot_height = 700,
				   title = 'Density Plot of Arrival Delays by Airline',
				   x_axis_label = 'Delay (min)', y_axis_label = 'Density')


		p.multi_line('x', 'y', color = 'color', legend = 'label', 
					 line_width = 3,
					 source = src)

		# Hover tool with next line policy
		hover = HoverTool(tooltips=[('Carrier', '@label'), 
									('Delay', '$x'),
									('Density', '$y')],
						  line_policy = 'next')

		# Add the hover tool and styling
		p.add_tools(hover)

		p = style(p)

		return p
	
	def update(attr, old, new):
		# List of carriers to plot
		carriers_to_plot = [carrier_selection.labels[i] for i in 
							carrier_selection.active]
		
		# If no bandwidth is selected, use the default value
		if bandwidth_choose.active == []:
			bandwidth = None
		# If the bandwidth select is activated, use the specified bandwith
		else:
			bandwidth = bandwidth_select.value
			
		
		new_src = make_dataset(carriers_to_plot,
									range_start = range_select.value[0],
									range_end = range_select.value[1],
									bandwidth = bandwidth)
		
		src.data.update(new_src.data)
		
	def style(p):
		# Title 
		p.title.align = 'center'
		p.title.text_font_size = '20pt'
		p.title.text_font = 'serif'

		# Axis titles
		p.xaxis.axis_label_text_font_size = '14pt'
		p.xaxis.axis_label_text_font_style = 'bold'
		p.yaxis.axis_label_text_font_size = '14pt'
		p.yaxis.axis_label_text_font_style = 'bold'

		# Tick labels
		p.xaxis.major_label_text_font_size = '12pt'
		p.yaxis.major_label_text_font_size = '12pt'

		return p
	
	# Carriers and colors
	available_carriers = list(set(flights['name']))
	available_carriers.sort()

	airline_colors = Category20_16
	airline_colors.sort()

	# Carriers to plot
	carrier_selection = CheckboxGroup(labels=available_carriers, 
									   active = [0, 1])
	carrier_selection.on_change('active', update)
	
	range_select = RangeSlider(start = -60, end = 180, value = (-60, 120),
							   step = 5, title = 'Range of Delays (min)')
	range_select.on_change('value', update)
	
	# Initial carriers and data source
	initial_carriers = [carrier_selection.labels[i] for 
						i in carrier_selection.active]
	
	# Bandwidth of kernel
	bandwidth_select = Slider(start = 0.1, end = 5, 
							  step = 0.1, value = 0.5,
							  title = 'Bandwidth for Density Plot')
	bandwidth_select.on_change('value', update)
	
	# Whether to set the bandwidth or have it done automatically
	bandwidth_choose = CheckboxButtonGroup(
		labels=['Choose Bandwidth (Else Auto)'], active = [])
	bandwidth_choose.on_change('active', update)

	# Make the density data source
	src = make_dataset(initial_carriers, 
						range_start = range_select.value[0],
						range_end = range_select.value[1],
						bandwidth = bandwidth_select.value) 
	
	# Make the density plot
	p = make_plot(src)
	
	# Add style to the plot
	p = style(p)
	
	# Put controls in a single element
	controls = WidgetBox(carrier_selection, range_select, 
						 bandwidth_select, bandwidth_choose)
	
	# Create a row layout
	layout = row(controls, p)
	
	# Make a tab with the layout 
	tab = Panel(child=layout, title = 'Density Plot')

	return tab
Exemple #30
0
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
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")
Exemple #31
0
emptyResult = data=dict(headline=[],prevHeadline=[],symbols=[],gmtstamp=[],ret=[])
searchResultTable = ColumnDataSource(data=emptyResult)
searchResultColumns = [
        TableColumn(field='prevHeadline',title='Past Headline',width=400),
        TableColumn(field='headline',title='Headline',width=400),
        TableColumn(field='sym',title='Symbols',width=70),
        TableColumn(field='gmtstamp',title='GMT Timestamp',formatter=DateFormatter(format="%F %T"),width=180),
        TableColumn(field='date',title='Date',formatter=DateFormatter(format="%Y-%m-%d"),width=120),
        TableColumn(field='ret',title='Daily Return',formatter=NumberFormatter(format='0.00%',text_align='right'),width=80)
        ]
searchResult = DataTable(source=searchResultTable,columns=searchResultColumns,width=2*ww,height=1000)
lineSrc = ColumnDataSource(data={'t':[],'i':[]})
spanSrc = ColumnDataSource(data={'x':[]})
retPlotHover = HoverTool(tooltips=[('headline','@headline')])
retPlot = figure(plot_width=250,plot_height=100,tools=[retPlotHover],x_axis_type='datetime')
solrButton = CheckboxButtonGroup(labels=["solr"], active=[0])
selBox1 = Select(title="Previous Categories:", value="", options=[""])
selBox2 = Select(title="Categories:", value="", options=[""])
if datePick1.value:
    date1 = datePick1.value
    dt1 = DT(date1.year,date1.month,date1.day) - timedelta(days=20)
    retPlot.x_range.start=dt1
if datePick2.value:
    date2 = datePick2.value
    dt2 = DT(date2.year,date2.month,date2.day) + timedelta(days=10)
    retPlot.x_range.end=dt2
retPlot.circle(x='gmtstamp',y='ret',size=7,fill_color='lightskyblue',source=searchResultTable)

# actions
def searchNews1():
    errBox.text = 'Searching...'
Exemple #32
0
    def __init__(self, category, sensor_list, mac_list):
        self.unit = sensor_unit[category]
        self.category = category
        self.sensor_list = sensor_list
        self.mac_list = mac_list

        self.checkbox_list = sensor_list + mac_list
        self.sources = ColumnDataSource()

        self.callback = CustomJS(args=dict(source=self.sources),
                                 code="""
			var data = source.data;
			
			var f = cb_obj.active;
			var list = cb_obj.labels;

			var sensors = []
			var macs = []

			var active_list = []

			for (i = 0; i < list.length; i++) {
				if (f.indexOf(i) != -1) {
					if (list[i].charAt(0) == '_') {
						macs.push(list[i]);
					}
					else {
						sensors.push(list[i]);
					}
				}
			}

			for (i = 0; i < sensors.length;i++) {
				for (j = 0;j < macs.length; j++) {
					active_list.push(sensors[i] + macs[j]);
				}
			}

			var found = false;

			for (name in data) {
				if (name.includes("active") || name.includes("_x")) {
					continue;
				}
				for (i = 0; i < active_list.length; i++) {
					if (name.includes(active_list[i])) {
						name_active = name + "_active";
						data[name] = data[name_active];
						found = true;
						
						break;
					}
				}

				if (found == false) {
					name_inactive = name + "_inactive";
					data[name] = data[name_inactive];
				}
				else {
					found = false;
				}
			}
			source.trigger('change');
			""")

        self.cbg = CheckboxButtonGroup(
            labels=self.checkbox_list,
            active=[i for i in range(len(self.checkbox_list))],
            callback=self.callback)

        self.widget = (widgetbox(self.cbg, width=1000))
        self.plot = figure(
            title=category,
            x_axis_type="datetime",
            x_axis_label="Date and Time",
            y_axis_label=self.unit,
            width=1500,
            height=600,
            tools="pan,wheel_zoom,box_zoom,reset,save,box_select")
Exemple #33
0
dropdown_disabled.on_click(lambda value: print('dropdown_disabled: %s' % value))
dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())"))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value))
#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,
])
Exemple #34
0
def load_page(experiment_df, experiment_db):

    ########## bokeh plots ##########

    # general plot tools
    plot_tools = 'wheel_zoom, pan, reset, save, hover'
    hover = HoverTool(tooltips=[("(x,y)", "($x, $y)")])

    # progress curve plots
    global raw_source
    raw_source = ColumnDataSource(data=dict(x=[], y=[], yr=[], yfit=[]))
    global raw
    raw = figure(title="Initial Rate Fit",
                 x_axis_label="Time",
                 y_axis_label="Signal",
                 plot_width=350,
                 plot_height=300,
                 tools=plot_tools)
    raw.circle('x',
               'y',
               size=2,
               source=raw_source,
               color='gray',
               selection_color="black",
               alpha=0.6,
               nonselection_alpha=0.2,
               selection_alpha=0.6)
    raw.line('x', 'yfit', source=raw_source, color='red')
    global warning_source
    warning_source = ColumnDataSource(data=dict(
        x=[0],
        y=[0],
        t=[
            'Please enter transform equation! \nMust convert signal to [substrate] \nin Schnell-Mendoza mode (e.g. via \nx/6.22/0.45/0.001 for sample data). \nNote: this transform may need \nto be inverted through multiplying \nby -1 when analyzing experiments \nthat measure increasing product \nconcentration over time)'
        ]))
    global warning
    warning = raw.text(x='x',
                       y='y',
                       text='t',
                       text_font_size='12pt',
                       angle=0,
                       source=warning_source)
    warning.visible = False
    global circles_source
    circles_source = ColumnDataSource(
        data=dict(x=[-.05, -.05, 1.6, 1.6], y=[0, 0.6, 0, 0.6]))
    global circles
    circles = raw.circle(x='x', y='y', alpha=0., source=circles_source)
    circles.visible = False
    global resi
    resi = figure(title="Initial Rate Fit Residuals",
                  x_axis_label="Time",
                  y_axis_label="Residual",
                  plot_width=700,
                  plot_height=200,
                  tools='wheel_zoom,pan,reset')
    resi.yaxis.formatter = BasicTickFormatter(precision=2, use_scientific=True)
    resi.circle('x', 'yr', size=5, source=raw_source, color='grey', alpha=0.6)

    # model plot for titration experiments
    global model_data_source
    model_data_source = ColumnDataSource(
        data=dict(xt=[], yt=[], n=[], ct=[], et=[]))
    global model_plot_source
    model_plot_source = ColumnDataSource(
        data=dict(xp=[], yp=[], l=[], u=[], cp=[], ep=[]))
    global model_fit_source
    model_fit_source = ColumnDataSource(data=dict(x=[], y=[]))
    global varea_source
    varea_source = ColumnDataSource(data=dict(x=[], r1=[], r2=[]))
    global model
    model = figure(title='Model Fit',
                   x_axis_label='Concentration',
                   y_axis_label='Rate',
                   plot_width=350,
                   plot_height=300,
                   tools=plot_tools)
    model.circle('xp',
                 'yp',
                 size=8,
                 source=model_plot_source,
                 color='cp',
                 alpha=0.6)
    model.add_layout(
        Whisker(source=model_plot_source, base='xp', upper='u', lower='l'))
    model.line('x',
               'y',
               source=model_fit_source,
               line_width=3,
               color='black',
               alpha=0.8)
    model.varea('x', 'r1', 'r2', source=varea_source, color='grey', alpha=0.3)

    ########## bokeh widgets ##########

    # button for selecting progress curve fitting routine
    global fit_button
    fit_button = RadioButtonGroup(labels=[
        'Maximize Slope Magnitude', 'Linear Fit', 'Logarithmic Fit',
        'Schnell-Mendoza'
    ],
                                  active=0,
                                  width=375)
    fit_button.on_change('active', widget_callback)

    # button for selecting progress curve fitting routine
    global scalex_box
    scalex_box = CheckboxButtonGroup(
        labels=["transform x-axis to Log10 scale"], active=[])
    scalex_box.on_change('active', widget_callback)

    # dropdown menu for selecting titration experiment model
    global model_select
    model_select = Select(
        title='Choose Model',
        value='Michaelis-Menten',
        options=['Michaelis-Menten', 'pEC50/pIC50', 'High-Throughput Screen'],
        width=350)
    model_select.on_change('value', widget_callback)

    # dropdown menu for selecting blank sample to subtract from remaining titration samples
    global subtract_select
    subtract_select = Select(title='Select Blank Sample for Subtraction',
                             value='',
                             options=list(experiment_df)[1:] + [''],
                             width=350)
    subtract_select.on_change('value', widget_callback)

    # dropdown menu for selecting titration sample to plot in current view
    global sample_select
    sample_select = Select(title='Y Axis Sample',
                           value=list(experiment_df)[-1],
                           options=list(experiment_df)[1:],
                           width=350)
    sample_select.on_change('value', sample_callback)

    # text input box for transforming slopes to rates
    global transform_input
    transform_input = TextInput(value='',
                                title="Enter Transform Equation",
                                width=350)
    transform_input.on_change('value', widget_callback)

    # text input box for setting delay time in logarithmic progress curve fitting
    global offset_input
    offset_input = TextInput(value='',
                             title="Enter Time Between Mixing and First Read",
                             width=350)
    offset_input.on_change('value', widget_callback)

    # text input boxes for fixing EC/IC50 parameters
    global bottom_fix
    bottom_fix = TextInput(value='', title="Fix pIC50/pEC50 Bottom")
    bottom_fix.on_change('value', widget_callback)

    global top_fix
    top_fix = TextInput(value='', title="Fix pIC50/pEC50 Top")
    top_fix.on_change('value', widget_callback)

    global slope_fix
    slope_fix = TextInput(value='', title="Fix pIC50/pEC50 Hill Slope")
    slope_fix.on_change('value', widget_callback)

    # text input boxes for progress curve xrange selection
    global start_time
    start_time = TextInput(value=str(
        experiment_df[list(experiment_df)[0]].values[0]),
                           title="Enter Start Time")
    global end_time
    end_time = TextInput(value=str(
        experiment_df[list(experiment_df)[0]].values[-1]),
                         title='Enter End Time')
    start_time.on_change('value', xbox_callback)
    end_time.on_change('value', xbox_callback)

    # range slider to select threshold for hit detection in HTS mode
    global threshold_slider
    threshold_slider = Slider(start=0,
                              end=5,
                              value=2,
                              step=0.1,
                              title='HTS Hit Threshold (Standard Deviation)',
                              width=350)
    threshold_slider.on_change('value', threshold_callback)

    # range slider to update plots according to progress cuve xrange selection
    xmin = experiment_df[experiment_df.columns[0]].values[0]
    xmax = experiment_df[experiment_df.columns[0]].values[-1]
    global range_slider
    range_slider = RangeSlider(
        start=xmin,
        end=xmax,
        value=(xmin, xmax),
        step=experiment_df[experiment_df.columns[0]].values[1] - xmin,
        title='Fine Tune X-Axis Range',
        width=650)
    range_slider.on_change('value', slider_callback)

    # button to upload local data file
    global file_source
    file_source = ColumnDataSource(data=dict(file_contents=[], file_name=[]))
    file_source.on_change('data', file_callback)
    try:
        output_filename = file_source.data['file_name'] + '-out.csv'
    except:
        output_filename = 'output.csv'
    global upload_button
    upload_button = Button(label="Upload Local File",
                           button_type="success",
                           width=350)
    upload_button.callback = CustomJS(args=dict(file_source=file_source),
                                      code=open(
                                          join(dirname(__file__),
                                               "upload.js")).read())

    # table containing rate fits and errors
    template = """
    <div style="background:<%=ct%>"; color="white";>
    <%= value %></div>
    """
    formatter = HTMLTemplateFormatter(template=template)
    columns = [
        TableColumn(field='n', title='Sample'),
        TableColumn(field='yt',
                    title='Slope (Initial Rate)',
                    formatter=formatter),
        TableColumn(field='et', title='Std. Error')
    ]
    global rate_table
    rate_table = DataTable(source=model_data_source,
                           columns=columns,
                           width=350,
                           height=250,
                           selectable=True,
                           editable=True)

    # tables containing model fits and errors
    global mm_source
    mm_source = ColumnDataSource(dict(label=[], Km=[], Vmax=[]))
    columns = [
        TableColumn(field='label', title=''),
        TableColumn(field='Vmax', title='Vmax'),
        TableColumn(field='Km', title='Km')
    ]
    global mm_table
    mm_table = DataTable(source=mm_source,
                         columns=columns,
                         width=350,
                         height=75,
                         selectable=True,
                         editable=True)
    global ic_source
    ic_source = ColumnDataSource(
        dict(label=[], Bottom=[], Top=[], Slope=[], p50=[]))
    columns = [
        TableColumn(field='label', title=''),
        TableColumn(field='Bottom', title='Bottom'),
        TableColumn(field='Top', title='Top'),
        TableColumn(field='Slope', title='Slope'),
        TableColumn(field='p50', title='pEC/IC50')
    ]
    global ic_table
    ic_table = DataTable(source=ic_source,
                         columns=columns,
                         width=350,
                         height=75,
                         selectable=True,
                         editable=True)

    # button for copying rate data table to clipboard
    global copy_button
    copy_button = Button(label="Copy Table to Clipboard",
                         button_type="primary",
                         width=350)
    copy_button.callback = CustomJS(args=dict(source=model_data_source),
                                    code=open(
                                        join(dirname(__file__),
                                             "copy.js")).read())

    # button for downloading rate data table to local csv file
    global download_button
    download_button = Button(label="Download Table to CSV",
                             button_type="primary",
                             width=350)
    download_button.callback = CustomJS(args=dict(source=model_data_source,
                                                  file_name=output_filename),
                                        code=open(
                                            join(dirname(__file__),
                                                 "download.js")).read())

    ########## document formatting #########

    desc = Div(text=open(join(dirname(__file__), "description.html")).read(),
               width=1400)

    advanced = Div(
        text="""<strong>Advanced Settings for \npEC/IC50 Analysis</strong>""")

    widgets = widgetbox(model_select, sample_select, subtract_select,
                        transform_input, offset_input, advanced, scalex_box,
                        bottom_fix, top_fix, slope_fix)
    table = widgetbox(rate_table)
    main_row = row(
        column(upload_button, widgets),
        column(fit_button, row(raw, model), resi, row(start_time, end_time),
               range_slider),
        column(download_button, copy_button, table, mm_table, ic_table,
               threshold_slider))

    sizing_mode = 'scale_width'
    l = layout([[desc], [main_row]], sizing_mode=sizing_mode)

    update()
    curdoc().clear()
    curdoc().add_root(l)
    curdoc().title = "ICEKAT"
Exemple #35
0
def make_tab():
    # Slider to select width of bin
    pastdays_select = RangeSlider(start=0,
                                  end=999,
                                  value=(0, 999),
                                  step=1,
                                  title='Past Days',
                                  sizing_mode="stretch_both")
    # Slider to select buffer size
    bufferdays_select = Slider(start=.01,
                               end=9,
                               value=0.01,
                               step=.1,
                               title='Buffer Size (days)',
                               sizing_mode="stretch_both")
    # Re-read
    refresh_button = Button(label="Time window and buffer are up to date",
                            button_type="success",
                            sizing_mode="stretch_both")
    refresh_button.disabled = True

    # read data
    flights, available_carriers = read(pastdays_select, bufferdays_select)

    # CheckboxGroup to select carrier to display
    locationcodes = np.unique(
        ['.'.join(seedid.split('.')[:3]) for seedid in available_carriers])
    selections = []
    for locationcode in locationcodes[:maxnstation]:
        matching = [s for s in available_carriers if locationcode in s]
        active = [i for i, m in enumerate(matching)]  # if "Z" == m[-1]]
        selections += [
            CheckboxButtonGroup(labels=matching,
                                active=active,
                                sizing_mode="stretch_both")
        ]
        #selections += [MultiSelect(#title="Option:",
        #                           value=matching,
        #                           active=active)

    # Find the initially selected carrieres
    initial_carriers = [s.labels[i] for s in selections for i in s.active]

    # Slider to select width of bin
    binwidth_select = Slider(start=16,
                             end=160,
                             step=16,
                             value=80,
                             title='Bin number',
                             sizing_mode="stretch_both")

    # RangeSlider control to select start and end of plotted delays
    range_select = RangeSlider(start=-1,
                               end=999,
                               value=(-.2, 99),
                               step=.1,
                               title='Range (sec)',
                               sizing_mode="stretch_both")

    # Switch from lines to hists
    type_switch = RadioButtonGroup(labels=["Histogram", "Cumulated dist."],
                                   active=0,
                                   sizing_mode="stretch_both")

    # Find the initially selected carrieres
    plottype = type_switch.labels[type_switch.active]

    src = {}
    for output in ['Latencies', 'Delays', 'PSD']:
        src[output] = make_dataset(flights,
                                   initial_carriers,
                                   range_start=range_select.value[0],
                                   range_end=range_select.value[1],
                                   bin_width=binwidth_select.value,
                                   output=output,
                                   plottype=plottype)

    callback = partial(update,
                       output='Delays',
                       type_switch=type_switch,
                       flights=flights,
                       src=src,
                       selections=selections,
                       range_select=range_select,
                       binwidth_select=binwidth_select)

    callbacklat = partial(update,
                          output='Latencies',
                          type_switch=type_switch,
                          flights=flights,
                          src=src,
                          range_select=range_select,
                          selections=selections,
                          binwidth_select=binwidth_select)

    callbackpsd = partial(update,
                          output='PSD',
                          type_switch=type_switch,
                          flights=flights,
                          src=src,
                          range_select=range_select,
                          selections=selections,
                          binwidth_select=binwidth_select)

    callbackneedsread = partial(needsreadupdate, refresh_button=refresh_button)

    callbackread = partial(readupdate,
                           src=src,
                           selections=selections,
                           range_select=range_select,
                           type_switch=type_switch,
                           binwidth_select=binwidth_select,
                           pastdays_select=pastdays_select,
                           bufferdays_select=bufferdays_select,
                           refresh_button=refresh_button)

    [
        s.on_change('active', callback, callbacklat, callbackpsd)
        for s in selections
    ]
    type_switch.on_change('active', callback, callbacklat, callbackpsd)
    binwidth_select.on_change('value', callback, callbacklat, callbackpsd)
    range_select.on_change('value', callback, callbacklat, callbackpsd)
    pastdays_select.on_change('value', callbackneedsread)
    bufferdays_select.on_change('value', callbackneedsread)
    refresh_button.on_click(callbackread)

    p = {}
    for output in ['PSD', 'Latencies', 'Delays']:
        p[output] = make_plot(src[output], output=output)

    # Create a row layout
    graphs = [p[k] for k in p]
    controls = [
        type_switch, binwidth_select, range_select, refresh_button,
        pastdays_select, bufferdays_select, *selections[:maxnstation]
    ]
    graphslayout = column(children=graphs, sizing_mode="stretch_both")
    controlslayout = column(
        children=controls,
        sizing_mode='fixed',  #stretch_width',
        width=400,
    )
    layout = row(children=[graphslayout, controlslayout],
                 sizing_mode='stretch_both')

    # Make a tab with the layout
    return Panel(child=layout, title='Channels')
                        state,
                    ] * tmp_df.shape[0])
        sources_year_vs_usd[state].data = data


def filter_categories(indexes):
    if len(indexes):
        selected_categories = [categories[ind] for ind in indexes]
    else:
        selected_categories = categories
    update_source(selected_categories)


update_source(categories)

select = CheckboxButtonGroup(labels=categories)
select.on_click(filter_categories)

hover_year_with_usd = HoverTool(tooltips=[
    ("name", "@name"),
])

p_year_with_usd = figure(plot_height=200,
                         tools=[hover_year_with_usd, "box_select", "reset"])

for state, color in zip(states, colors):
    p_year_with_usd.circle(x='x',
                           y='y',
                           line_color='white',
                           fill_color=color,
                           alpha=0.7,
                           fill_alpha=.3,
                           line_alpha=0,
                           hover_alpha=1,
                           hover_color="yellow",
                           legend="Drunk")

dot_tooltips = [("Date", "@MONTH/@DAY/@YEAR"), ("Fatalities", "@FATALS"),
                ("Drunk", "@DRUNK_DR"), ("Speeding", "@SP"),
                ("Weather", "@WEATHER")]

fig.add_tools(
    HoverTool(renderers=[other_circles, speed_circles, drunk_circles],
              tooltips=dot_tooltips))

button_group = CheckboxButtonGroup(labels=["Other", "Speeding", "Drunk"],
                                   active=[0, 1, 2],
                                   width=200)

toggle = Toggle(label="Sort by Hour", button_type="default")

slider = Slider(title="Hour (Military Time)", start=0, end=23, value=0, step=1)

empty_dict = dict(x=np.array([]),
                  y=np.array([]),
                  r=np.array([]),
                  MONTH=np.array([]),
                  DAY=np.array([]),
                  YEAR=np.array([]),
                  FATALS=np.array([]),
                  DRUNK_DR=np.array([]),
                  SP=np.array([]),
Exemple #38
0
            'size': df_slice['plot_size'],
            'text': df_slice['comment_text'].str[0:75] + '...',
            'flags': df_slice['all_flags'],
            'single_flag': df_slice['single_flag'],
            'sim_age': df_slice['sim_age']
        }).data


slider = RangeSlider(start=0,
                     end=30,
                     value=(0, 30),
                     step=1,
                     title='Simulated Age')
slider.on_change('value', callback)

buttons = CheckboxButtonGroup(labels=buttonlabels,
                              active=[0, 1, 2, 3, 4, 5, 6])
buttons.on_change('active', callback)

select = Select(title='Vectorization',
                value='Bag of Words',
                options=['Bag of Words', 'Doc2Vec'])
select.on_change('value', callback)

tooltips = [('Comment', '@text'), ('Flags', '@flags'), ('Age (d)', '@sim_age')]

n_obs = df.shape[0]
manif = 't-SNE'
title = '{} visualization of {} observations'.format(manif, n_obs)

p = figure(plot_width=figsize[0],
           plot_height=figsize[1],
Exemple #39
0
# select_linac[1].on_change('value', plot.update_source)
# select_linac[2].on_change('value', plot.update_source)

avg_len_input = TextInput(title='Avg. Len:', value='10', width=100)
avg_len_input.on_change('value', plot.update_source)

percentile_input = TextInput(title='Percentile:', value='90', width=100)
percentile_input.on_change('value', plot.update_source)

start_date_picker = DatePicker(title='Start Date:', value=plot.x[0])
end_date_picker = DatePicker(title='End Date:', value=plot.x[-1])
start_date_picker.on_change('value', plot.update_source)
end_date_picker.on_change('value', plot.update_source)

gamma_options = ['5.0%/3.0mm', '3.0%/3.0mm', '3.0%/2.0mm', 'Any']
checkbox_button_group = CheckboxButtonGroup(labels=gamma_options, active=[3])
checkbox_button_group.on_change('active', plot.update_source)

text = {key: Div() for key in [1, 2]}

plot.update_source(None, None, None)

layout = column(row(select_y, avg_len_input, percentile_input),
                row(start_date_picker, end_date_picker),
                row(Div(text='Gamma Criteria: '), checkbox_button_group),
                text[1], text[2], row(Spacer(width=10), plot.fig),
                Spacer(height=50), row(Spacer(width=10), plot.histogram),
                Spacer(height=50), row(Spacer(width=10), ichart.figure),
                row(ichart.div_center_line, ichart.div_ucl, ichart.div_lcl))

curdoc().add_root(layout)