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])
Beispiel #2
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))
 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
Beispiel #4
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
Beispiel #5
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
Beispiel #6
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
Beispiel #7
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)
Beispiel #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
Beispiel #9
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)
Beispiel #10
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")
Beispiel #11
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)
Beispiel #12
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:',
Beispiel #13
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=
Beispiel #14
0
# %% PREPARING PANELS AND TABS ================================================
# =============================================================================

# Seetting one Panel with a single Figure in each Tab
tab1 = Panel(child=figures_dict['f1'][0], title='Intensity vs. Mass')
tab2 = Panel(child=figures_dict['f2'][0], title='Retention Time vs. Mass')
tab3 = Panel(child=figures_dict['f3'][0], title='Intensity vs. Retention Time')

# %% INITIATING BOKEH WIDGETS =================================================
# =============================================================================

# Getting list of unique Nodes
nodes = list(df['Node'].unique())

# Creating Check Box Button Group Widget for Nodes
node_cbbg = CheckboxButtonGroup(labels=nodes,
                                active=[nodes.index(i) for i in nodes])

# Creating Toggle Button Widget for show/hide unclustered PrSMs
unclustered_toggle = Toggle(label='Hide unclustered')

# Creating Spinner Widget for the DBSCAN eps hyperparameter
ε_spinner = Spinner(title='ε',
                    width=100,
                    value=p['ε'],
                    low=0.0005,
                    high=0.0050,
                    step=0.0001)

# Creating Spinner Widget for the DBSCAN min_samples hyperparameter
n_spinner = Spinner(title='n_min',
                    width=100,
Beispiel #15
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")
Beispiel #16
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)
Beispiel #17
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"],
Beispiel #18
0
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
Beispiel #19
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
Beispiel #20
0
    def do_layout(self):
        """
        generates the overall layout by creating all the widgets, buttons etc and arranges
        them in rows and columns
        :return: None
        """
        self.source = self.generate_source()
        tab_plot = self.generate_plot(self.source)
        multi_select = MultiSelect(title="Option (Multiselect Ctrl+Click):",
                                   value=self.active_country_list,
                                   options=countries,
                                   height=500)
        multi_select.on_change('value', self.update_data)
        tab_plot.on_change('active', self.update_tab)
        radio_button_group_per_capita = RadioButtonGroup(
            labels=["Total Cases", "Cases per Million"],
            active=0 if not self.active_per_capita else 1)
        radio_button_group_per_capita.on_click(self.update_capita)
        radio_button_group_scale = RadioButtonGroup(
            labels=[Scale.log.name.title(),
                    Scale.linear.name.title()],
            active=self.active_y_axis_type.value)
        radio_button_group_scale.on_click(self.update_scale_button)
        radio_button_group_df = RadioButtonGroup(labels=[
            Prefix.confirmed.name.title(),
            Prefix.deaths.name.title(),
            Prefix.recovered.name.title(),
        ],
                                                 active=int(
                                                     self.active_case_type))
        radio_button_group_df.on_click(self.update_data_frame)
        refresh_button = Button(label="Refresh Data",
                                button_type="default",
                                width=150)
        refresh_button.on_click(load_data_frames)
        export_button = Button(label="Export Url",
                               button_type="default",
                               width=150)
        export_button.on_click(self.export_url)
        slider = Slider(start=1,
                        end=30,
                        value=self.active_window_size,
                        step=1,
                        title="Window Size for rolling average")
        slider.on_change('value', self.update_window_size)
        radio_button_average = RadioButtonGroup(
            labels=[Average.mean.name.title(),
                    Average.median.name.title()],
            active=self.active_average)
        radio_button_average.on_click(self.update_average_button)
        plot_variables = [
            self.active_plot_raw, self.active_plot_average,
            self.active_plot_trend
        ]
        plots_button_group = CheckboxButtonGroup(
            labels=["Raw", "Averaged", "Trend"],
            active=[i for i, x in enumerate(plot_variables) if x])
        plots_button_group.on_click(self.update_shown_plots)

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

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

        curdoc().add_root(self.layout)
        curdoc().title = "Bokeh Covid-19 Dashboard"
Beispiel #21
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

'''
Beispiel #22
0
p.triangle('x',
           'y',
           source=chap_1930_geosource,
           color="orange",
           size=4,
           legend="1930s Chaparral")

# p.circle('x','y', source = shrub_1990_geosource,
# color = 'black', size=4,legend="1990s shrubland")

p.square('x',
         'y',
         source=landfire_geosource,
         color='brown',
         size=4,
         legend="2010s Chaparral")

p.multi_line('xs', 'ys', source=ca_geosource, color="black")

# Add the CheckBox group
Check_Box = CheckboxButtonGroup(labels=checkbox_labels, active=[])
Check_Box.on_click(checkbox_handler)

# Position the color bars
p.add_layout(alt_color_bar, 'right')
p.add_layout(dMAT_color_bar, 'right')

layout = column(Check_Box, p)
curdoc().add_root(layout)
Beispiel #23
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)
Beispiel #24
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')
Beispiel #25
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"
                           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([]),
                        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,
Beispiel #28
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)
Beispiel #29
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],
Beispiel #30
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...'