Exemple #1
0
    def init_controls(self):
        """

        :return:
        """
        t0 = time()
        if self.verbose: print("Initializing Controls")


        # Initialize Controls
        self.color_selection = Select(title="Color By", options=self.data_dict.keys(), value=self.data_dict.keys()[0])
        self.selection_label = TextInput(value="MyGroup#1", title="Selection Label:")

        self.add_selection_label = Button(label="Add Selection Label")
        self.write_mod_file = Button(label="Download", button_type="primary")
        self.write_mod_file.callback = CustomJS(args=dict(source=self.source),
                                                code=open(os.path.join(os.path.dirname(__file__),
                                                                       "download.js")).read())

        self.tooltip_select = MultiSelect(title='Tooltip',value = [self.data_dict.keys()[0]],
                                          options=[(key,key.upper()) for key in self.data_dict.keys()])

        # Declare Tooltip Contents
        self.tooltip_list = [(col, "@" + col) for col in self.tooltip_select.value]

        self.init_control_time = time() - t0
        return self.init_control_time
Exemple #2
0
    def _get_series_multiselect(self):

        list_slct = self.cols_pos + self.cols_neg
        slct = MultiSelect(size=len(list_slct),
                           value=list_slct, options=list_slct)

        self.callback.args['slct_dataseries'] = slct
        slct.js_on_change('value', self.callback)

        return slct
Exemple #3
0
    def __init__(self, dataset=STATES):

        self.dataset = dataset

        self.state_selection = MultiSelect(
            title="States:",
            options=self.dataset,
            value=["New York", "Texas"],
            sizing_mode="stretch_both",
        )
        self.per_capita = RadioGroup(
            labels=["Total", "Per Capita"],
            active=0,
            sizing_mode="stretch_width",
        )
        self.data_getter = RadioGroup(
            labels=[
                "Cases",
                "Deaths",
                "Positivity",
                "Testing",
                "Constant Positivity",
                "Constant Testing",
            ],
            active=0,
            sizing_mode="stretch_width",
        )
        self.plot_type = RadioGroup(
            labels=["Linear", "Logarithmic"],
            active=0,
            sizing_mode="stretch_width",
        )

        self.constant_date = DatePicker(
            title="Constant Date",
            value=(datetime.today() - timedelta(days=1)).date(),
            sizing_mode="stretch_width",
        )

        self.show_total = CheckboxGroup(
            labels=["Show total"],
            sizing_mode="stretch_width",
        )

        self.total_only = CheckboxGroup(
            labels=["Total only"],
            sizing_mode="stretch_width",
        )

        self.src = None
        self.p = None
        self.logp = None

        self.tooltips = [("State", "@state")]
Exemple #4
0
    def _get_multiselects(self):

        selects = []
        for nind, ind in enumerate(self.ind_slct):
            list_slct = list(map(str, self.slct_list_dict[ind]))
            value = [list_slct[self._initial_selection_index[nind]]]
            slct = MultiSelect(size=1, value=value,
                               options=list_slct, title=ind)
            self.callback.args['slct_%s'%ind] = slct
            slct.js_on_change('value', self.callback)
            selects.append(slct)

        return selects
    def __init__(self, original):
        """Initialize scatter plot object.

        Keyword arguments:
        original -- the data processor object containing data and list of categorical indices
        """

        # Read in data table, tell Bokeh it's the data we're using
        self.original = original.df
        self.source = ColumnDataSource(original.df)

        # Take in the column names and the indices of those names that are categorical
        self.columnNames = list(self.original.columns.values)
        self.valueOptions = list(self.original.columns.values)

        self.colIndices = original.cat_indices

        # Checkboxes for categorical variables
        self.checkPanel = CheckboxGroup(labels=self.columnNames, active=self.colIndices)

        # Remove categoricals from value box on start
        self.updateValueOptions()

        # Create input tools that live on left side of pivot table
        self.valuesSelect = MultiSelect(title="Values:", options=self.valueOptions)
        self.indexSelect = MultiSelect(title="Indices:", options=self.columnNames)
        self.columnsSelect = MultiSelect(title="Columns:", options=self.columnNames)

        # Bokeh currently does not have label attribute for checkbox panels
        self.catLabel = Div(text="<label>Categorical Variables:</label>")

        # Allow user to select aggregate function (currently sum or average)
        self.aggSelect = Select(title="Aggregate Function:", value="Sum", options=["Sum", "Average"])

        # Set up update button to make changes take effect
        self.updateButton = Button(label="Update", button_type="success")

        # Placeholder for where error messages show up
        self.errorDiv = Div(text="", width=200, height=100)

        # Generate table to show user the actual data set before any pivot table stuff happens
        self.table = Div(text=self.toBootstrapTable(self.original.to_html()), width=900, height=400)

        # Bind all of input tools to one widgetbox
        self.inputs = widgetbox(self.valuesSelect, self.indexSelect, self.columnsSelect, self.aggSelect, self.catLabel,
                                self.checkPanel, self.updateButton, self.errorDiv)

        # Tell Bokeh to put input tools on left and table on right
        self.toReturn = row(self.inputs, self.table, width=800)
Exemple #6
0
def confirm_new_annotation(btn, app):
    global saved_annotations

    annotations = app.objects['annotations']
    annotation_txt = app.objects['annotation_txt'].value

    dlg = app.objects['new_annotation_dlg']
    dlg.visible = False

    new_annotations = MultiSelect.create(options=[x for x in annotations.options], name='annotations')
    rec = {'name': annotation_txt, 'value': annotation_txt}
    if annotation_txt and not rec in new_annotations.options:
        new_annotations.options.append(rec)

    saved_annotations[annotation_txt] = {
        "txt": annotation_txt,
        "charts_selection": current_selection,
    }
    #
    # for p in app.objects['charts_box'].children:
    #     import pdb; pdb.set_trace()
    #     p.text(
    #
    #         df['ind'][current_selection['1d']['indices'][0]], 0, annotation_txt,
    #         text_font_size="8pt", text_align="center", text_baseline="middle"
    #     )
    # import pdb; pdb.set_trace()
    # print "SAVED!!", saved_annotations

    return {'annotations': new_annotations}
def line_config(app, df):
    options = CheckboxGroup(
        labels=['Show peaks', 'Show Std. Dev.', 'Bolinger Bands'],
        name='new_chart_options')

    title = TextInput(title="Chart Title",
                      name='new_chart_title',
                      value="Line")

    new_chart_index = Select.create(options=['---'] + list(df.columns),
                                    name='"new_chart_index"',
                                    title="Chart index")
    chart_values_select = MultiSelect.create(options=df.columns,
                                             name="chart_values",
                                             title="Values")

    chart_data = AppHBox(
        app=app, children=[new_chart_index, chart_values_select, options])
    main_tab = AppVBox(app=app, children=[title, chart_data, 'select_palette'])
    confirm_chart_button = Button(label="Confirm",
                                  type="success",
                                  name='confirm_add_chart')

    return {
        'dlg':
        Dialog(buttons=[confirm_chart_button], content=main_tab, visible=True),
        "new_chart_index":
        new_chart_index,
        'new_chart_title':
        title,
        'chart_values':
        chart_values_select,
        'new_chart_options':
        options
    }
Exemple #8
0
def multi_select_example():
    output_file('multi_select.html')

    multi_select = MultiSelect(title='Option:',
                               value=['foo', 'quux'],
                               options=[('foo', 'Foo'), ('bar', 'BAR'),
                                        ('baz', 'bAz'), ('quux', 'quux')])

    show(widgetbox(multi_select))
Exemple #9
0
    def __init__(self):
        # extend __init__ super class
        IPlugin.__init__(self)

        # instantiate main components
        self.tx = TxData()
        self.prod_master = ProductMaster()
        self.cust_master = CustomerMaster()
        self.quote = Quote()
        self.price_model = PriceModel()

        # cds_plot lives here rather than quote because they draw on several main components
        self.cds_plot = ColumnDataSource(data=dict(x=[0], y=[0], attr_label=[''], attr_name=['']))

        # plot_filters lives here because it's drawing from several main components
        self.plot_filters = [MultiSelect(title='Product_filter', value=[''], options=[''])]
        self.plot_filters[0].on_change('value', self.update_plot)

        # configuration backup settings
        self.backup_loc = TextInput(value=getcwd())
        self.backup_config_button = Button(label='Output config', button_type='success')
        self.backup_config_button.on_click(self.output_config)

        self.config_data_input = FileInput(accept=".json")
        self.config_data_input.on_change('value', self.load_config)

        self.datafile_selector = RadioButtonGroup(labels=['Tx data', 'Product master', 'Customer master'], active=0)
        self.datafile_selector.on_change('active', self.refresh_view)

        # define and initialize views (and their layout attributes)
        self.view_quote = QuoteView(self)
        self.view_price_mgt = PriceMgtView(self)
        self.view_price_model_config = PriceModelConfigView(self)
        self.view_attr_settings = AttrSettingsView(self)
        self.view_settings = SettingsView(self)

        self.tabs = Tabs(
            tabs=[Panel(child=self.view_quote.layout, title='Quote'),
                  Panel(child=self.view_price_mgt.layout, title='Price Management'),
                  Panel(child=self.view_price_model_config.layout, title='Price adjustments'),
                  Panel(child=self.view_attr_settings.layout, title='Attribute Settings'),
                  Panel(child=self.view_settings.layout, title='Settings')])

        # define some on_change events

        self.price_model.price_group_selector.on_change('active', self.refresh_view)
        self.price_model.num_prod_groups.on_change('value', self.refresh_view, self.update_on_change)
        self.price_model.num_customer_groups.on_change('value', self.refresh_view)
        self.tx.num_columns.on_change('value', self.refresh_view)
        self.prod_master.num_columns.on_change('value', self.refresh_view)
        self.cust_master.num_columns.on_change('value', self.refresh_view)
        for pg in self.price_model.price_groups:
            pg.num_attributes.on_change('value', self.refresh_view, self.update_on_change)
            for attr in pg.attributes:
                attr.sourcefile.on_change('value', partial(attr.update_sourcecolumns_options, cpq=self))
                attr.num_configs.on_change('value', self.refresh_view, self.update_on_change, self.update_quote_filters)
Exemple #10
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 #11
0
def dash_remove_field(rbutton, app):
    """
    Event handler for click on "remove field" button
    """
    ms = app.objects['ms']
    to_remove = ms.value
    options = [x for x in ms.options if x['value'] not in to_remove]
    new_ms = MultiSelect.create(options=options, name='ms')

    # TODO: Do we really need to recreate the entire DataTable object?
    ndt = DataTable(source=source, columns=[], editable=True, width=500)
    for new_value in options:
        ndt.columns.append(
            TableColumn(
                field=new_value['value'], title=new_value['value'],editor=StringEditor()
            )
        )

    main_content = MultiSelect.create(options=['AW', 'BS', 'C'], name='pppp')
    main_tab = AppHBox(app=app, children=[main_content], width=300)

    return {'ms': new_ms, 'dt': ndt}
Exemple #12
0
    def set_plot_filters(self):
        # TODO: Select active price group based on selected item in quote table

        selected_pg_num = 0  # self.price_model.price_group_selector.active
        selected_pg = self.price_model.price_groups[selected_pg_num]

        self.plot_filters = []
        for attr in selected_pg.attributes:
            title = attr.name.value
            values = [config.name.value for config in attr.configurations]
            self.plot_filters.append(MultiSelect(title=title, value=values, options=values))

        self.view_quote.refresh(cpq=self)
Exemple #13
0
    def setup_filter_widgets(self, obj, attrname, old, new):
        # print ("setup_filter_widgets")
        """Creates new filter widget each time a new column is added to filters.

        Args:
          obj (Widget): the object that has an attribute change
          attrname (str): name of the attribute
          old (type): the previous value of unknown type
          new (type): the new value of unknown type

        """
        self.clear_selections(obj, attrname, old, new)

        # add new widget as required for each column set to filter on
        column_descriptor_dict = self.column_descriptor_dict()
        for col in self.filtering_columns:

            metadata = column_descriptor_dict[col]
            if not col in self.filter_widgets:

                # discrete
                if metadata['type'] == 'DiscreteColumn':
                    description = self.query('/bench/v1/desc/single/{0}'.format(col))
                    options = description['options']
                    select = MultiSelect.create(
                        name=col,
                        options=options)
                    self.filter_widgets[col] = select

                # continuous
                else:
                    col_query = self.query('/bench/v1/col/single/{0}'.format(col))
                    histogram = col_query['values']
                    source = make_histogram_source(histogram)
                    self.filter_sources[col] = source
                    hist_plot = make_histogram(self.filter_sources[col],
                                               plot_width=200, plot_height=100,
                                               title_text_font_size='8pt',
                                               tools='box_select'
                    )
                    hist_plot.title = col
                    self.filter_widgets[col] = hist_plot

        curdoc()._add_all()
Exemple #14
0
    def setup_filter_widgets(self, obj, attrname, old, new):
        # print ("setup_filter_widgets")
        """Creates new filter widget each time a new column is added to filters.

        Args:
          obj (Widget): the object that has an attribute change
          attrname (str): name of the attribute
          old (type): the previous value of unknown type
          new (type): the new value of unknown type

        """
        self.clear_selections(obj, attrname, old, new)

        # add new widget as required for each column set to filter on
        column_descriptor_dict = self.column_descriptor_dict()
        for col in self.filtering_columns:

            metadata = column_descriptor_dict[col]
            if not col in self.filter_widgets:

                # discrete
                if metadata['type'] == 'DiscreteColumn':
                    description = self.query(
                        '/bench/v1/desc/single/{0}'.format(col))
                    options = description['options']
                    select = MultiSelect.create(name=col, options=options)
                    self.filter_widgets[col] = select

                # continuous
                else:
                    col_query = self.query(
                        '/bench/v1/col/single/{0}'.format(col))
                    histogram = col_query['values']
                    source = make_histogram_source(histogram)
                    self.filter_sources[col] = source
                    hist_plot = make_histogram(self.filter_sources[col],
                                               plot_width=200,
                                               plot_height=100,
                                               title_text_font_size='8pt',
                                               tools='box_select')
                    hist_plot.title = col
                    self.filter_widgets[col] = hist_plot

        curdoc()._add_all()
Exemple #15
0
def dash_update_input(abutton, app):
    """
    Event handler for click on "add field" button
    """
    ms = app.objects['ms']
    dt = app.objects['dt']

    columns = [x for x in dt.columns]
    ndt = DataTable(source=source, columns=columns, editable=True, width = 500)
    new_ms = MultiSelect.create(options=[x for x in ms.options], name='ms')
    new_value = app.objects['field_to_add'].value or app.objects['field_to_add'].options[0]['value']
    rec = {'name': new_value, 'value': new_value}
    if new_value and not rec in new_ms.options:
        new_ms.options.append(rec)
        ndt.columns.append(
            TableColumn(field=new_value, title=new_value, editor=StringEditor())
        )

    return {'ms': new_ms, 'dt': ndt}
Exemple #16
0
def update_select(select_sec, app):
    # TODO: Definitely needs a better design to avoid using globals...
    global source
    global csource
    global df
    global index

    ss = app.objects['select_sec'].value
    df = load_symbol(ss)

    index = df.pop('dt')

    df = df[num_columns]
    df['ind'] = list(range(len(index)))

    for name in num_columns:
        stdv = df[name].std()
        values = [stdv for x in df.index]
        df['%s_std_dv' % name] = values

    source = ColumnDataSource(df)
    source.tags = ['main_source']

    ndt = DataTable(source=source, columns=[], editable=True, width=500)
    charts_box = AppVBox(app=app, children=[], name='charts_box')

    templ = """FOUND %s CRASHES FOR SYMBOL %s"""
    crashes_info = check_for_crash(ss)

    crashes_source = ColumnDataSource(crashes_info)
    ccolumns = [TableColumn(field=x, title=x, editor=NumberEditor()) for x in crashes_info.columns]
    txt = PreText(text=templ % (len(crashes_info), ss), width=500, height=100)
    crashes_dt = DataTable(source=crashes_source, columns=ccolumns, editable=True, width=500)

    crashes_box = AppVBox(app=app, children=[txt, crashes_dt], name='crash_stats')

    new_ms = MultiSelect.create(options=[], name='ms')
    return {
        'charts_box': charts_box,
        'dt': ndt,
        'crash_stats': crashes_box,
        'ms': new_ms,
    }
Exemple #17
0
def line_config(app, df):
    options = CheckboxGroup(
        labels=['Show peaks', 'Show Std. Dev.', 'Bolinger Bands'],
        name='new_chart_options'
    )

    title = TextInput(title="Chart Title", name='new_chart_title', value="Line")
    new_chart_index = Select.create(options=['---']+list(df.columns), name='"new_chart_index"', title="Chart index")
    chart_values_select = MultiSelect.create(options=df.columns, name="chart_values", title="Values")
    chart_data = AppHBox(app=app, children=[new_chart_index, chart_values_select, options])
    main_tab = AppVBox(app=app, children=[title, chart_data, 'select_palette'])
    confirm_chart_button = Button(label="Confirm", type="success", name='confirm_add_chart')

    return {
        'dlg': Dialog(buttons=[confirm_chart_button], content=main_tab, visible=True),
        "new_chart_index": new_chart_index,
        'new_chart_title': title,
        'chart_values': chart_values_select,
        'new_chart_options': options
    }
Exemple #18
0
    def __init__(self, original):
        """Initialize regression object.

        Keyword arguments:
        original -- the data processor object containing data and list of categorical indices
        """

        self.original = original.df

        # Sets up widgets to take user input
        self.y_select = Select(title="Value to Predict:",
                               options=list(self.original.columns.values))
        self.x_select = MultiSelect(title="Values used to Predict:",
                                    options=list(self.original.columns.values))
        self.updateButton = Button(label="Calculate Regression",
                                   button_type="success")
        self.inputs = widgetbox(self.y_select, self.x_select,
                                self.updateButton)

        # Defines an object variable that is later used to display regression info
        self.p = Div(text=" ")

        # Defines an object variable that holds the entire layout for this tab
        self.toReturn = row(self.inputs, self.p)
Exemple #19
0
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)

range_slider = RangeSlider()

#date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)))

date_picker = DatePicker()

paragraph = Paragraph(text="some text")

div = Div(text="some <b>text</b>")

pre_text = PreText(text="some text")
Exemple #20
0
# create widgets
slider_time_unit = "hour"
time_slider = create_slider(slider_time_unit)
slider_active_toggle = Toggle(label="slider not active",
                              active=False,
                              button_type="default",
                              width=150)
pattern_select = _create_radio_button_group(["Daily", "Weekly", "Yearly"])
aggregate_select = _create_radio_button_group(["Hour", "Day", "Week", "Month"])
groupby_select = _create_radio_button_group(
    ["None", "Type", "Day of Week", "Year"])
incident_types = dfincident["dim_incident_incident_type"].astype(str).unique()
#type_filter = _create_type_filter(incident_types)
type_filter = MultiSelect(title="Incident Types:",
                          value=list(incident_types),
                          options=[(t, t) for t in incident_types],
                          size=10)
select_all_types_button = Button(label="Select all",
                                 button_type="primary",
                                 width=150)


## add callbacks
def update_time_series(filter_, attr, old, new):
    """ Updates the time series plot when filters have changed.

    params
    ------
    filter_: identifier for the filter that has been changed.
             One of {'agg', 'pattern', 'group', 'types'}.
    attr: the attribute that changed.
Exemple #21
0
                           title="Start Date:",
                           max_date=df['Time'].iloc[-1].date(),
                           min_date=df['Time'][0].date(),
                           value=df['Time'][0].date(),
                           width=140)

datePickEnd = DatePicker(name="EndD",
                         title="End Date:",
                         max_date=df['Time'].iloc[-1].date(),
                         min_date=df['Time'][0].date(),
                         value=df['Time'].iloc[-1].date(),
                         width=140)
areaList = []
for n in an['Name']:
    areaList.append((n, n))
area_select = MultiSelect(title="Select area:", options=areaList)
channel_select = MultiSelect(title="Select channel:", options=[])
plotDates = Button(label="Plot between start and end dates",
                   button_type="warning")
selectAll = Button(label="Select all lights", button_type="success")

# initialise start and end values for dates
dateVal_start = df['Time'][0].date()
dateVal_end = df['Time'].iloc[-1].date()


def setTitle():
    p1.title.text = "Assembly Rooms Lighting Use: " + dateVal_start.strftime(format = '%d/%m/%y') + \
        " - " + dateVal_end.strftime(format = '%d/%m/%y')

wheel_zoom_tool = WheelZoomTool()
file_select_dropdown = Dropdown(label="Data file",
                                button_type="warning",
                                height_policy='min',
                                menu=[('refresh list', 'refresh_list'), None])
update_file_list()
color_class_select = Select(title="Colored by:",
                            value=features_list[0],
                            options=features_list[:],
                            sizing_mode="stretch_width")
toggle_class_select = Select(title="Selected by:",
                             value=features_list[0],
                             options=features_list[:],
                             sizing_mode="stretch_width")
class_toggle_multi_select = MultiSelect(
    title='toggle classes:'
)  # , options=list(data_df[features_list[0]].unique()))


# Define widgets callbacks
def update_color_class(attr, old, new):
    print(f"{attr} changed from {old} to {new}")
    cls_color_mapper, cls_list, _ = get_color_mapper(new)
    if type(cls_color_mapper['transform']) is LinearColorMapper:
        color_bar.color_mapper.palette = cls_color_mapper['transform'].palette
        color_bar.color_mapper = cls_color_mapper['transform']
        color_bar.visible = True
    else:
        color_bar.visible = False
    print(f"cm field: {cls_color_mapper['field']}")
    cr.nonselection_glyph.fill_color = cls_color_mapper
    player_names['bref_id'], player_names['bref_name'],
    player_names['mlb_team'], player_names['mlb_team_long'],
    player_names['mlb_pos']
],
                         axis=1)

player_names = player_names[player_names['bref_id'].isin(players_df.index)]

team_codes = player_names['mlb_team_long']
team_codes = team_codes.drop_duplicates()
team_codes = team_codes.sort_values().tolist()
team_codes = [i for i in team_codes if i != "Anaheim Angels"]

# Initialize team to Rangers
team_select = MultiSelect(title="MLB Team:",
                          value=["Texas Rangers"],
                          options=team_codes)
team_selected_players = player_names.loc[player_names['mlb_team_long'] ==
                                         "Texas Rangers"]

# Draw field plot
field = figure(tools=[], width=650, height=650, toolbar_location="above")
field.set(x_range=Range1d(-3, 3), y_range=Range1d(-1, 5))
field.axis.visible = False
field.grid.grid_line_alpha = 0.0

field.wedge(
    x=0,
    y=0,
    radius=3.5,
    start_angle=45 - 1.4995,
    'y': y,
    'label': label
})  #create a dataframe for future use

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

plot_figure = figure(title='Multi-Select',
                     plot_height=450,
                     plot_width=600,
                     tools="save,reset",
                     toolbar_location="below")

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

multi_select = MultiSelect(title="Filter Plot by color:",
                           value=["Red", "Orange"],
                           options=[("Red", "Red"), ("Orange", "Orange")])


def multiselect_click(attr, old, new):
    active_mselect = multi_select.value  ##Getting multi-select value

    selected_df = df[df['label'].isin(
        active_mselect)]  #filter the dataframe with value in multi-select

    source.data = dict(x=selected_df.x,
                       y=selected_df.y,
                       label=selected_df.label)


multi_select.on_change('value', multiselect_click)
                                                    predictions)
tsize = Slider(title="Test Size", start=0.05, end=0.50, value=0.2, step=0.05)
layer = Slider(title="Layer 1", start=10, end=50, value=10, step=10)
layer1 = Slider(title="Layer 2", start=10, end=50, value=10, step=10)
layer2 = Slider(title="Layer 3", start=10, end=50, value=10, step=10)
layer3 = Slider(title="Layer 4", start=10, end=50, value=10, step=10)
maxiter = Slider(title="Iterations", start=100, end=3000, value=100, step=100)
button = Button(label="Submit Parameters", button_type="success")
button2 = Button(label="Play_Maximum_Iterations", button_type="success")
multi_select = MultiSelect(title="Features to drop:",
                           value=[],
                           options=[('a', 'avg_dist'),
                                    ('b', 'avg_rating_by_driver'),
                                    ('c', 'avg_rating_of_driver'),
                                    ('d', 'avg_surge'), ('e', 'surge_pct'),
                                    ('f', 'trips_in_first_30_days'),
                                    ('g', 'luxury_car_user'),
                                    ('h', 'weekday_pct'),
                                    ('i', 'city_Astapor'),
                                    ('k', 'city_Winterfell'),
                                    ('l', 'phone_Android'),
                                    ('m', 'phone_iPhone'),
                                    ('n', 'phone_no_phone')])
p.add_tools(HoverTool(tooltips=[
    ("Count", "@counts"),
]))


def update_points():
    # E = ent.value
    l1 = int(layer.value)
    l2 = int(layer1.value)
Exemple #26
0
from bokeh.io import output_file, show
from bokeh.models.widgets import MultiSelect

output_file("multi_select.html")

multi_select = MultiSelect(title="Option:",
                           value=["foo", "quux"],
                           options=[("foo", "Foo"), ("bar", "BAR"),
                                    ("baz", "bAz"), ("quux", "quux")])

show(multi_select)
from bokeh.plotting import figure

x=[3,4,6,12,10,1]
y=[7,1,3,4,1,6]
label=['Red', 'Orange', 'Red', 'Orange','Red', 'Orange']

df=pd.DataFrame({'x':x,'y':y,'label':label}) #create a dataframe for future use

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

plot_figure = figure(title='Multi-Select',plot_height=450, plot_width=600,
              tools="save,reset", toolbar_location="below")

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

multi_select = MultiSelect(title="Filter Plot by color:", value=["Red", "Orange"],
                           options=[("Red", "Red"), ("Orange", "Orange")])

def multiselect_click(attr,old,new):
    active_mselect=multi_select.value ##Getting multi-select value

    selected_df=df[df['label'].isin(active_mselect)] #filter the dataframe with value in multi-select

    source.data=dict(x=selected_df.x, y=selected_df.y,label=selected_df.label)


multi_select.on_change('value',multiselect_click)

layout=row(multi_select, plot_figure)

curdoc().add_root(layout)
curdoc().title = "Multi-Select Bokeh Server"
Exemple #28
0
from help_text import text_dict

header_text = Div(text="""<pre>          <font size="6"><a href="http://192.168.86.29:5006/plojo">Plojo</a> Help Document</font><pre>""",width=400)

topic_list = [
chr(9608)*2+' Top Row Buttons ','+---- Upload/Browse/Fitting Button','+---- Information Box','+---- Edit Button','+---- Plot Button','+---- Load/Save Button',
chr(9608)*2+' Upload Layout ', '+---- Upload Data Options',
chr(9608)*2+' Browse Layout ','+---- Project/Experiment... Tabs','+---- plojo Keyword Search','+---- Edit/Save Experiment Information',
chr(9608)*2+' Fitting Layout ','+---- Curve Fitting with plojo',
chr(9608)*2+' Simuojo ', '+---- How to use simuojo?',
chr(9608)*2+' Fitting Methods ','+---- How does fitting work?','+---- Supported Fitting Models','+---- Confidence Intervals'
]

topic_key = ['toprow','ubfbutton','infobox','editbutton','plotbutton','loadsavebutton',
'uploadlayout','uploadoptions','browselayout','tabs','search','editinfo','fittinglayout','curvefit',
'simuojo','howtosimuojo','fitmethod','howfit','supportedfitmodel','confidence']

topic_menu = [i for i in zip(topic_key,topic_list)]

topic_select = MultiSelect(title='Topic',value=['none'],options=topic_menu,size=30)
text_show=Div(text='Select a topic to view.',width=800,height=800)

def topic_select_cb(attr,old,new):
    new=new[0]
    text_show.text = text_dict[new]

topic_select.on_change('value',topic_select_cb)
div_1 = Div(text='',width=50)
display_layout = layout([header_text],[div_1,topic_select,text_show])
curdoc().add_root(display_layout)
Exemple #29
0
update_files_button = Button(label="Update Files", button_type="default", width=50)
update_files_button.on_click(reload_all_files)

auto_update_toggle_button = Toggle(label="Auto Update", button_type="default", width=50, active=True)
auto_update_toggle_button.on_click(toggle_auto_update)

unload_file_button = Button(label="Unload", button_type="danger", width=50)
unload_file_button.on_click(unload_file)

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

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

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

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

# averaging slider
# This data source is just used to communicate / trigger the real callback
averaging_slider_dummy_source = ColumnDataSource(data=dict(value=[]))
averaging_slider_dummy_source.on_change('data', update_averaging)
Exemple #30
0
def multi_select_municipio(indices_df, width=300):
    select = MultiSelect(title="Município(s):",
                         value=[],
                         options=list(indices_df.index),
                         width=width)
    return select
Exemple #31
0
networks = data.SocialNetwork.unique().tolist()
editorials = get_multselect_options('Editoria')
categories = get_multselect_options('Categoria')
products = get_multselect_options('Produto')

month_select = DateRangeSlider(start=date(2019, 1, 1),
                               end=date(2019, 9, 1),
                               value=(date(2019, 1, 1), date(2019, 9, 1)),
                               step=1,
                               format="%b %Y")

metric_select = Select(title="Métrica:",
                       value="velocity",
                       options=[("velocity", "Parâmetro de Crise"),
                                ("positivity", "Grau de Positividade"),
                                ("gradiente", "Grau de Negatividade"),
                                ("brand_health", "Saúde da Maca"),
                                ("post_health", "Saúde do Post")])

product_select = MultiSelect(value=['Todos'], options=products)
category_select = MultiSelect(value=['Todos'], options=categories)
editorial_select = MultiSelect(value=['Todos'], options=editorials)
social_network_select = CheckboxGroup(labels=networks,
                                      active=list(range(len(networks))))

metric_title = create_div_title('MÉTRICA')
network_title = create_div_title('REDE SOCIAL')
category_title = create_div_title('CATEGORIA')
editorial_title = create_div_title('EDITORIA')
product_title = create_div_title('PRODUTO')
Exemple #32
0
                       step=1,
                       title='Nights')
NIGHTS_SLIDER.on_change(c.VALUE, update_data)

# Range Slider Widget
PRICE = FILTER_PROPERTIES[c.PRICE]
PRICE_SLIDER = RangeSlider(start=PRICE[0],
                           end=PRICE[1],
                           value=(PRICE[0], PRICE[1]),
                           step=50,
                           title='Nightly Price')
PRICE_SLIDER.on_change(c.VALUE, update_data)

# Multi Select Widgets
AMENITIES_SELECT = MultiSelect(title='Amenities:',
                               value=[],
                               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]
Exemple #33
0
print("Dataset name is " + datasetname)
desc = Div(text="""
<h2 style="font-family="Arial">
Select the features to be included in the Random Forest Model
</h2>

<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier" target="_blank">Click here </a>for more information on the parameters </p>
""",
           width=1100)

df = pd.read_csv(os.path.join('..', 'data', datasetname))

y = df[df.columns[:1]].values.ravel()
df1 = df.drop(df.columns[:1], axis=1)

features = MultiSelect(title="Features", options=df.columns[1:].tolist())
criterion = Select(title="Criterion:",
                   value="gini",
                   options=["gini", "entropy"])
max_depth = Slider(start=0, end=50, value=10, step=1, title="Max_Depth")
n_estimators = Slider(start=0,
                      end=30,
                      value=10,
                      step=1,
                      title="No of estimators:")
bootstrap = Select(title="Bootstrap:", value="True", options=["True", "False"])
oob_score = Select(title="oob_score:",
                   value="False",
                   options=["True", "False"])
warm_start = Select(title="Warm_start:",
                    value="False",
Exemple #34
0
def dashboard():
    """
    Creates the main app objects
    """
    # TODO: Should find a better design and remove those global objs...
    global source
    global csource

    source = ColumnDataSource(df)
    source.tags = ['main_source']

    csource = ColumnDataSource(cdf)
    csource.tags = ['crash_source']

    select_sec = Select.create(options=SECURITIES, name='select_sec', title="")

    asel = Select.create(options=df.columns, name='field_to_add', title="")
    chart_sel = Select.create(options=chart_types, name='chart_to_add', title="")

    msel = MultiSelect.create(options=[], name='ms')
    abutton = Button(label="add", type="success", name='add_button')
    rbutton = Button(label="remove", type="danger", name='remove_button')
    add_chart_button = Button(label="add chart", type="success", name='add_chart')


    data_table = DataTable(source=source, editable=True, width=500, height=400)
    ccolumns = [TableColumn(field=x, title=x, editor=NumberEditor()) for x in cdf.columns]
    crashes_table = DataTable(source=csource, editable=True, width=1200, height=400, columns=ccolumns)

    charts_box = AppVBox(children=[], name='charts_box')

    counts = cdf['crashes']
    crashes_hist = charts.Histogram({'crash_counts': counts}, bins=20, height=300, title="# Crashes per Symbol")
    crashes_scatter = create_crashes_scatter()

    main_tab = VBox(children=[], name='d_box')
    dlg = Dialog(buttons=[], content=main_tab , visible=False)

    options = CheckboxGroup(
        labels=['Show peaks', 'Show Std. Dev.', 'Bolinger Bands'],
        name='new_chart_options'
    )

    select_palette = Select.create(options=brewer.keys(), name='select_palette', title="Palette")
    return {
        # security tab
        'select_sec': select_sec,
        'field_to_add': asel,
        'chart_to_add': chart_sel,
        'ms': msel,
        'dt': data_table,
        'add_button': abutton,
        'remove_button': rbutton,
        'add_chart': add_chart_button,
        'charts_box': charts_box,
        'dlg': dlg,

        # Crashes tab objs
        'crashes_hist': crashes_hist,
        'crashes_scatter': crashes_scatter,
        'crashes_table': crashes_table,
        'crash_stats': PreText(text="NO CRASHES FOR SYMBOL %s" % SYMBOL, width=300),

        #
        'chart_values': MultiSelect.create(options=df.columns, name="chart_values", title="Values"),
        'new_chart_index': Select.create(options=['---']+list(df.columns), title="Chart index", name="new_chart_index"),
        'new_chart_title': TextInput(title="Chart Title", name='new_chart_title', value=''),
        'new_chart_options': options,
        'select_palette': select_palette,

        # ANNOTATIONS
        "annotations": MultiSelect.create(options=[], name="annotations", title="Annotations"),
        "add_annotation": Button(label="add", type="success", name='add_annotation'),
        "delete_annotation": Button(label="remove", type="danger", name='delete_annotation'),
        "show_annotation": Button(label="Show", type="link", name='show_annotation'),
        'new_annotation_dlg': Dialog(buttons=[], content=main_tab , visible=False),
        'annotation_txt': TextInput(title="New Annotation", name='annotation_txt', value=''),
        'new_annotation_options': CheckboxGroup(labels=[], name='new_annotation_options'),
    }
Exemple #35
0
    print("Updated label: " + new)
subject_id = TextInput(title="Subject ID:", value="ref number")
#subject_id.on_change("value", subject_id_handler)

# age at onset
def age_onset_handler(attr, old, new):
    print("Previous label: " + type(old))
    print("Updated label: " + new)
age_onset = TextInput(title="Age at ALS Onset (years)", value="")
#age_onset.on_change("value", age_onset_handler)

# onset location
def onset_loc_detail_handler(attr, old, new):
    print ('Radio button option ' + str(new) + ' selected.')
onset_loc_detail = MultiSelect(title="Location Detail (can pick multiple)", value=["unk"],
                           options=[("unk", "unknown"),("hands", "Hands"), 
                                    ("arms", "Arms"), ("feet", "Feet"), ("legs", "Legs")])
#onset_loc_detail.on_change("value", onset_loc_detail_handler)

# symptom selection
def symptom_handler(new):
    print ('Symptom selection ' + str(new) + ' selected.')
symptom = Select(title="Symptom Type:", value="Unknown", 
                 options=["Unknown", "Sensory changes", "Speech", 
                          "Stiffness", "Swallowing",
                         'Weakness', 'Atrophy', 'Cramps',
                         'Fasciculations', "Gait changes"])

# onset radio button
def onset_loc_handler(new):
    print ('Radio button option' + str(new) + ' selected.')
def tab_testing():
    data_list = glob.glob('./np/Regression/*.npy')
    data_list = sorted(data_list)
    select_data = Select(title="Data:", value="", options=data_list)

    model_list = os.listdir('./model/Regression/')
    model_list = sorted(model_list)
    select_model = Select(title="Trained Model:", value="", options=model_list)

    notifier = Paragraph(text=""" Notification """, width=200, height=100)

    def refresh_handler():
        data_list_new = glob.glob('./np/Regression/*.npy')
        data_list_new = sorted(data_list_new)
        select_data.options = data_list_new

        model_list_new = os.listdir('./model/Regression/')
        model_list_new = sorted(model_list_new)
        select_model.options = model_list_new

    button_refresh = Button(label="Refresh list")
    button_refresh.on_click(refresh_handler)

    button_test = Button(label="Test model")

    select_result = MultiSelect(title="Key(result):")

    src = ColumnDataSource()
    df = pd.DataFrame(columns=['key', 'y', 'y_hat'])

    table_src = ColumnDataSource(pd.DataFrame(columns=['Key', 'MSE', 'R^2']))
    table_columns = [
        TableColumn(field=col, title=col) for col in ['Key', 'MSE', 'R^2']
    ]
    table_acc = DataTable(source=table_src,
                          columns=table_columns,
                          width=350,
                          height=400,
                          fit_columns=True,
                          name="Accuracy per Key")

    def test_handler():
        df.drop(df.index, inplace=True)
        print("Start test")
        tf.reset_default_graph()
        K.clear_session()

        notifier.text = """ Start testing """

        if (select_data.value == ""):
            data = np.load(select_data.options[0])
        else:
            data = np.load(select_data.value)
        data = data.item()
        notifier.text = """ Import data """

        data_x = data.get('x')
        if (data_x.shape[-1] == 1 and not 'cnn' in select_model.value):
            data_x = np.squeeze(data_x, -1)
        data_y = data.get('y')
        data_key = data.get('key1')

        print(data_x.shape)
        print(data_y.shape)

        df['key'] = data_key
        df['y'] = data_y[:, 0]

        op_list = []
        for i in df['key'].unique():
            op_list.append(str(i))
        select_result.options = op_list

        print(data_x.shape)
        print(data_y.shape)
        print(data.get('key1'))

        if (select_model.value == ""):
            model_name = select_model.options[0]
        else:
            model_name = select_model.value
        model_save_dir = './model/Regression/' + model_name + '/'

        model_dl = glob.glob(model_save_dir + '*.h5')
        model_ml = glob.glob(model_save_dir + '*.sav')

        print(model_save_dir + '*.h5')
        print(model_dl)
        print(model_ml)

        if (len(model_dl) > len(model_ml)):
            model = keras.models.load_model(model_save_dir + model_name +
                                            '.h5')
            target_hat = model.predict(data_x)
            DL = True

        elif (len(model_dl) < len(model_ml)):
            model = pickle.load(
                open(model_save_dir + model_name + '.sav', 'rb'))
            data_x = data_x.reshape([data_x.shape[0], -1])
            target_hat = model.predict(data_x)
            target_hat = np.expand_dims(target_hat, -1)
            DL = False

        notifier.text = """ Model restored """
        print("Model restored.")

        xs = []
        ys = []
        keys = []
        color = ['blue', 'red']

        xs.append([i for i in range(data_y.shape[0])])
        xs.append([i for i in range(data_y.shape[0])])
        ys.append(data_y)
        keys.append(data_key)

        print(target_hat.shape)
        K.clear_session()

        ys.append(target_hat)
        keys.append(data_key)

        print(target_hat[:, 0])
        df['y_hat'] = target_hat[:, 0]

        src.data = ColumnDataSource(
            data=dict(xs=xs, ys=ys, color=color, keys=keys)).data

        figure_trend.multi_line('xs', 'ys', source=src, color='color')

        line_mse = []
        line_r_2 = []
        for unit in df['key'].unique():
            target = df[df['key'] == unit]

            y = target['y'].values
            y_hat = target['y_hat'].values

            unit_mse = np.sum((y - y_hat)**2) / target.shape[0]
            unit_r_2 = np.max([r2_score(y, y_hat), 0])

            line_mse.append(unit_mse)
            line_r_2.append(unit_r_2)

        acc = pd.DataFrame(columns=['Key', 'MSE', 'R^2'])
        acc['Key'] = df['key'].unique()

        mse_mean = np.mean(line_mse)
        r_2_mean = np.mean(line_r_2)

        line_mse = list(map(lambda x: format(x, '.2f'), line_mse))
        acc['MSE'] = line_mse
        line_r_2 = list(map(lambda x: format(x, '.2f'), line_r_2))
        acc['R^2'] = line_r_2

        acc_append = pd.DataFrame(columns=acc.columns)
        acc_append['Key'] = ['MSE average', 'R^2 average']
        acc_append['MSE'] = [mse_mean, r_2_mean]

        acc = pd.concat([acc, acc_append])

        table_src.data = ColumnDataSource(acc).data

        notifier.text = """ Drawing complete """
        history.text = history.text + "\n\t" + model_name + "'s R^2 score: " + format(
            np.mean(r_2_mean), '.2f')

    def update(attr, old, new):

        key_to_plot = select_result.value

        xs = []
        ys = []
        keys = []

        y = []
        y_hat = []
        key = []

        key_type = type(df['key'].values[0])
        for k in key_to_plot:

            y += list(df[df['key'] == key_type(k)]['y'].values)
            y_hat += list(df[df['key'] == key_type(k)]['y_hat'].values)
            key += [k for _ in range(df[df['key'] == key_type(k)].shape[0])]

        ys.append(y)
        ys.append(y_hat)

        xs.append([i for i in range(len(y))])
        xs.append([i for i in range(len(y))])

        keys.append(key)
        keys.append(key)

        color = ['blue', 'red']

        src.data = ColumnDataSource(
            data=dict(xs=xs, ys=ys, color=color, keys=keys)).data

    select_result.on_change("value", update)

    button_test.on_click(test_handler)

    button_export = Button(label="Export result")

    def handler_export():
        df.to_csv('./Export/result.csv', index=False)

    button_export.on_click(handler_export)

    figure_trend = figure(title="Prediction result", width=800, height=460)
    history = PreText(text="", width=300, height=460)

    layout = Column(
        Row(button_refresh),
        Row(select_data, select_model, button_test, select_result, notifier),
        Row(table_acc, figure_trend, history, button_export))

    tab = Panel(child=layout, title='Regression Test')

    return tab
Exemple #37
0
    def modify_doc(doc):

        # The callback for update
        def update_plots(new):

            print("Starting update")

            nonlocal Estimators

            if not isinstance(Estimators, (type(np.array), list)):
                Estimators = np.array(Estimators)

            estimator_names = np.array(list(estimator_select.value))
            ix = np.isin(Estimator_Names, estimator_names)
            estimator_indices = [int(i) for i in np.where(ix)[0].flatten()]

            estimators = np.array(Estimators)[estimator_indices]

            variable1 = drop1.value
            variable2 = drop2.value
            y = drop3.value

            #Things to update:
            # image background i.e. image source √
            # observation source √
            #Color mapper values√
            #hover tool values √
            #Figure ranges √
            #Model score text things √

            #Lets calculate all the image and observation data first

            plots = [None for i in range(len(estimators))]
            image_sources = [None for i in range(len(estimators))]
            observation_sources = [None for i in range(len(estimators))]
            hover_tools = [None for i in range(len(estimators))]
            model_score_sources = [None for i in range(len(estimators))]
            glyphs0 = [None for i in range(len(estimators))]
            color_bars = [None for i in range(len(estimators))]
            p_circles = [None for i in range(len(estimators))]
            p_images = [None for i in range(len(estimators))]

            #Iterate over the estimators
            for idx, estimator in enumerate(estimators):
                #Find the title for each plot
                estimator_name = str(estimator()).split('(')[0]

                #Extract the needed data
                full_mat = X[[variable1, variable2, y]].dropna(how="any",
                                                               axis=0)

                #Define a class bijection for class colour mapping
                unique_classes, y_bijection = np.unique(full_mat[y],
                                                        return_inverse=True)
                full_mat['y_bijection'] = y_bijection

                #Rescale the X Data so that the data fits nicely on the axis/predictions are reliable
                full_mat[variable1 + "_s"] = StandardScaler().fit_transform(
                    full_mat[variable1].values.reshape((-1, 1)))
                full_mat[variable2 + "_s"] = StandardScaler().fit_transform(
                    full_mat[variable2].values.reshape((-1, 1)))

                #Define the Step size in the mesh
                delta = Delta

                #Separate the data into arrays so it is easy to work with
                X1 = full_mat[variable1 + "_s"].values
                X2 = full_mat[variable2 + "_s"].values
                Y = full_mat["y_bijection"].values

                #Define the mesh-grid co-ordiantes over which to colour in
                x1_min, x1_max = X1.min() - 0.5, X1.max() + 0.5
                x2_min, x2_max = X2.min() - 0.5, X2.max() + 0.5

                #Create the meshgrid itself
                x1, x2 = np.arange(x1_min, x1_max,
                                   delta), np.arange(x2_min, x2_max, delta)
                x1x1, x2x2 = np.meshgrid(x1, x2)

                #Create the train test split
                X_train, X_test, y_train, y_test = train_test_split(
                    full_mat[[variable1 + "_s", variable2 + "_s"]],
                    Y,
                    test_size=Test_Size,
                    random_state=Random_State)
                #Fit and predict/score the model
                model = estimator().fit(X=X_train, y=y_train)
                # train_preds = model.predict(X_train)
                # test_preds = model.predict(X_test)
                model_score = model.score(X_test, y_test)
                model_score_text = "Model score: %.2f" % model_score

                if hasattr(model, "decision_function"):
                    Z = model.decision_function(np.c_[x1x1.ravel(),
                                                      x2x2.ravel()])

                elif hasattr(model, "predict_proba"):
                    Z = model.predict_proba(np.c_[x1x1.ravel(), x2x2.ravel()])

                else:
                    print(
                        "This Estimator doesn't have a decision_function attribute and can't predict probabilities"
                    )

                Z = np.argmax(Z, axis=1)
                Z_uniques = np.unique(Z)

                unique_predictions = unique_classes[Z_uniques]

                Z = Z.reshape(x1x1.shape)

                #Add in the probabilities and predicitions for the tooltips
                full_mat["probability"] = np.amax(model.predict_proba(
                    full_mat[[variable1 + "_s", variable2 + "_s"]]),
                                                  axis=1)

                bijected_predictions = model.predict(
                    full_mat[[variable1 + "_s", variable2 + "_s"]])
                full_mat["prediction"] = unique_classes[bijected_predictions]

                #Add an associated color to the predictions
                number_of_colors = len(np.unique(y_bijection))

                #Create the hover tool to be updated
                hover = HoverTool(tooltips=[(
                    variable1, "@" +
                    variable1), (variable2, "@" +
                                 variable2), ("Probability", "@probability"),
                                            ("Prediction",
                                             "@prediction"), ("Actual",
                                                              "@" + y)])

                #Create the axes for all the plots
                plots[idx] = figure(x_axis_label=variable1,
                                    y_axis_label=variable2,
                                    title=estimator_name,
                                    x_range=(x1x1.min(), x1x1.max()),
                                    y_range=(x2x2.min(), x2x2.max()),
                                    plot_height=600,
                                    plot_width=600)

                #Create all the image sources
                image_data = dict()
                image_data['x'] = np.array([x1x1.min()])
                image_data["y"] = np.array([x2x2.min()])
                image_data['dw'] = np.array([x1x1.max() - x1x1.min()])
                image_data['dh'] = np.array([x2x2.max() - x2x2.min()])
                image_data['boundaries'] = [Z]

                image_sources[idx] = ColumnDataSource(image_data)

                #Create all the updatable images (boundaries)
                p_images[idx] = plots[idx].image(image='boundaries',
                                                 x='x',
                                                 y='y',
                                                 dw='dw',
                                                 dh='dh',
                                                 palette="RdBu11",
                                                 source=image_sources[idx])

                #Create the sources to update the observation points
                observation_sources[idx] = ColumnDataSource(data=full_mat)

                #Create all the updatable points
                low = full_mat["y_bijection"].min()
                high = full_mat["y_bijection"].max()
                cbar_mapper = LinearColorMapper(palette=RdBu[number_of_colors],
                                                high=high,
                                                low=low)

                p_circles[idx] = plots[idx].circle(
                    x=variable1 + "_s",
                    y=variable2 + "_s",
                    color=dict(field='y_bijection', transform=cbar_mapper),
                    source=observation_sources[idx],
                    line_color="black")

                #Create the hovertool for each plot
                hover_tools[idx] = hover

                #Add the hover tools to each plot
                plots[idx].add_tools(hover_tools[idx])

                #Create all the text sources (model scores) for the plots
                model_score_sources[idx] = ColumnDataSource(
                    data=dict(x=[x1x1.min() + 0.3],
                              y=[x2x2.min() + 0.3],
                              text=[model_score_text]))

                #Add the model scores to all the plots
                score_as_text = Text(x="x", y="y", text="text")
                glyphs0[idx] = plots[idx].add_glyph(model_score_sources[idx],
                                                    score_as_text)

                #Add a colorbar
                color_bars[idx] = ColorBar(
                    color_mapper=cbar_mapper,
                    ticker=BasicTicker(desired_num_ticks=number_of_colors),
                    label_standoff=12,
                    location=(0, 0),
                    bar_line_color="black")

                plots[idx].add_layout(color_bars[idx], "right")
                plots[idx].add_tools(LassoSelectTool(), WheelZoomTool())

                # configure so that no drag tools are active
                plots[idx].toolbar.tools = plots[idx].toolbar.tools[1:]
                plots[idx].toolbar.tools[0], plots[idx].toolbar.tools[
                    -2] = plots[idx].toolbar.tools[-2], plots[
                        idx].toolbar.tools[0]

            layout = gridplot([
                widgetbox(drop1, drop2, drop3, estimator_select, update_drop)
            ], [row(plot) for plot in plots])
            return layout

            #Finished the callback
            print("Ending Update")
            push_notebook(handle=handle0)

        #lowecase innerscope variables
        variable1, variable2 = Variable1, Variable2

        #Make the 'Estimators' iterable
        nonlocal Estimators

        if not isinstance(Estimators, (type(np.array), list)):
            Estimators = np.array([Estimators])

        estimators = Estimators

        #Create the widgets
        drop1 = Select(title="Variable 1",
                       options=list(X.columns.values),
                       value=variable1)

        drop2 = Select(title="Variable 2",
                       options=list(X.columns.values),
                       value=variable2)

        drop3 = Select(title="variable 3",
                       options=list(X.columns.values),
                       value=y)

        estimator_names = [
            str(estimator()).split("(")[0] for estimator in Estimators
        ]
        estimator_indices = [
            str(idx) for idx, name in enumerate(estimator_names)
        ]
        estimator_select = MultiSelect(title="Estimators",
                                       options=estimator_indices,
                                       value=estimator_names)

        update_drop = Dropdown(label="Update",
                               default_value="-",
                               menu=[("Update", "Update")],
                               value="-")
        update_drop.on_click(update_plots)

        plots = [None for i in range(len(estimators))]
        image_sources = [None for i in range(len(estimators))]
        observation_sources = [None for i in range(len(estimators))]
        hover_tools = [None for i in range(len(estimators))]
        model_score_sources = [None for i in range(len(estimators))]
        glyphs0 = [None for i in range(len(estimators))]
        color_bars = [None for i in range(len(estimators))]
        p_circles = [None for i in range(len(estimators))]
        p_images = [None for i in range(len(estimators))]

        #Iterate over the estimators
        for idx, estimator in enumerate(estimators):
            #Find the title for each plot
            estimator_name = str(estimator()).split('(')[0]

            #Extract the needed data
            full_mat = X[[variable1, variable2, y]].dropna(how="any", axis=0)

            #Define a class bijection for class colour mapping
            unique_classes, y_bijection = np.unique(full_mat[y],
                                                    return_inverse=True)
            full_mat['y_bijection'] = y_bijection

            #Rescale the X Data so that the data fits nicely on the axis/predictions are reliable
            full_mat[variable1 + "_s"] = StandardScaler().fit_transform(
                full_mat[variable1].values.reshape((-1, 1)))
            full_mat[variable2 + "_s"] = StandardScaler().fit_transform(
                full_mat[variable2].values.reshape((-1, 1)))

            #Define the Step size in the mesh
            delta = Delta

            #Separate the data into arrays so it is easy to work with
            X1 = full_mat[variable1 + "_s"].values
            X2 = full_mat[variable2 + "_s"].values
            Y = full_mat["y_bijection"].values

            #Define the mesh-grid co-ordiantes over which to colour in
            x1_min, x1_max = X1.min() - 0.5, X1.max() + 0.5
            x2_min, x2_max = X2.min() - 0.5, X2.max() + 0.5

            #Create the meshgrid itself
            x1, x2 = np.arange(x1_min, x1_max,
                               delta), np.arange(x2_min, x2_max, delta)
            x1x1, x2x2 = np.meshgrid(x1, x2)

            #Create the train test split
            X_train, X_test, y_train, y_test = train_test_split(
                full_mat[[variable1 + "_s", variable2 + "_s"]],
                Y,
                test_size=Test_Size,
                random_state=Random_State)

            #Fit and predict/score the model
            model = estimator().fit(X=X_train, y=y_train)
            # train_preds = model.predict(X_train)
            # test_preds = model.predict(X_test)
            model_score = model.score(X_test, y_test)
            model_score_text = "Model score: %.2f" % model_score

            if hasattr(model, "decision_function"):
                Z = model.decision_function(np.c_[x1x1.ravel(), x2x2.ravel()])

            elif hasattr(model, "predict_proba"):
                Z = model.predict_proba(np.c_[x1x1.ravel(), x2x2.ravel()])

            else:
                print(
                    "This Estimator doesn't have a decision_function attribute and can't predict probabilities"
                )

            Z = np.argmax(Z, axis=1)
            Z_uniques = np.unique(Z)

            unique_predictions = unique_classes[Z_uniques]

            Z = Z.reshape(x1x1.shape)

            #Add in the probabilities and predicitions for the tooltips
            full_mat["probability"] = np.amax(model.predict_proba(
                full_mat[[variable1 + "_s", variable2 + "_s"]]),
                                              axis=1)

            bijected_predictions = model.predict(
                full_mat[[variable1 + "_s", variable2 + "_s"]])
            full_mat["prediction"] = unique_classes[bijected_predictions]

            #Add an associated color to the predictions
            number_of_colors = len(np.unique(y_bijection))

            #Create the hover tool to be updated
            hover = HoverTool(
                tooltips=[(variable1,
                           "@" + variable1), (variable2, "@" + variable2),
                          ("Probability",
                           "@probability"), ("Prediction",
                                             "@prediction"), ("Actual",
                                                              "@" + y)])

            #Create the axes for all the plots
            plots[idx] = figure(x_axis_label=variable1,
                                y_axis_label=variable2,
                                title=estimator_name,
                                x_range=(x1x1.min(), x1x1.max()),
                                y_range=(x2x2.min(), x2x2.max()),
                                plot_height=600,
                                plot_width=600)

            #Create all the image sources
            image_data = dict()
            image_data['x'] = np.array([x1x1.min()])
            image_data["y"] = np.array([x2x2.min()])
            image_data['dw'] = np.array([x1x1.max() - x1x1.min()])
            image_data['dh'] = np.array([x2x2.max() - x2x2.min()])
            image_data['boundaries'] = [Z]

            image_sources[idx] = ColumnDataSource(image_data)

            #Create all the updatable images (boundaries)
            p_images[idx] = plots[idx].image(image='boundaries',
                                             x='x',
                                             y='y',
                                             dw='dw',
                                             dh='dh',
                                             palette="RdBu11",
                                             source=image_sources[idx])

            #Create the sources to update the observation points
            observation_sources[idx] = ColumnDataSource(data=full_mat)

            #Create all the updatable points
            low = full_mat["y_bijection"].min()
            high = full_mat["y_bijection"].max()
            cbar_mapper = LinearColorMapper(palette=RdBu[number_of_colors],
                                            high=high,
                                            low=low)

            p_circles[idx] = plots[idx].circle(x=variable1 + "_s",
                                               y=variable2 + "_s",
                                               color=dict(
                                                   field='y_bijection',
                                                   transform=cbar_mapper),
                                               source=observation_sources[idx],
                                               line_color="black")

            #Create the hovertool for each plot
            hover_tools[idx] = hover

            #Add the hover tools to each plot
            plots[idx].add_tools(hover_tools[idx])

            #Create all the text sources (model scores) for the plots
            model_score_sources[idx] = ColumnDataSource(
                data=dict(x=[x1x1.min() + 0.3],
                          y=[x2x2.min() + 0.3],
                          text=[model_score_text]))

            #Add the model scores to all the plots
            score_as_text = Text(x="x", y="y", text="text")
            glyphs0[idx] = plots[idx].add_glyph(model_score_sources[idx],
                                                score_as_text)

            #Add a colorbar
            color_bars[idx] = ColorBar(
                color_mapper=cbar_mapper,
                ticker=BasicTicker(desired_num_ticks=number_of_colors),
                label_standoff=12,
                location=(0, 0),
                bar_line_color="black")

            plots[idx].add_layout(color_bars[idx], "right")
            plots[idx].add_tools(LassoSelectTool(), WheelZoomTool())

            # configure so that no drag tools are active
            plots[idx].toolbar.tools = plots[idx].toolbar.tools[1:]
            plots[idx].toolbar.tools[0], plots[idx].toolbar.tools[-2] = plots[
                idx].toolbar.tools[-2], plots[idx].toolbar.tools[0]

        layout = gridplot(
            [widgetbox(drop1, drop2, drop3, estimator_select, update_drop)],
            [row(plot) for plot in plots])
        doc.add_root(layout)
Exemple #38
0
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)

icon = Icon(icon_name="check")

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

autocomplete_input = AutocompleteInput()

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

multi_select = MultiSelect(options=["Option 1", "Option 2", "Option 3"])

slider = Slider(value=10, start=0, end=100)

range_slider = RangeSlider()

#date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)))

date_picker = DatePicker()

paragraph = Paragraph(text="some text")

div = Div(text="some <b>text</b>")

pre_text = PreText(text="some text")