def createSnakeControls(self):
        #snake mode controls
        snakeModeControls = RadioButtonGroup(labels=["Square", "LED"],
                                             active=0,
                                             width=400,
                                             button_type="primary")
        # snakeModeControls.on_change("active",self.visibilityCallback)

        self.snakeSpeed = 500
        snakeSpeedSlider = Slider(title="Speed",
                                  show_value=False,
                                  value=self.snakeSpeed,
                                  start=30,
                                  end=1000,
                                  step=5)
        snakeSpeedSlider.on_change("value", self.snakeSpeedCallback)
        snakeNumberControls = RadioButtonGroup(labels=["1", "2"],
                                               active=0,
                                               width=400,
                                               button_type="primary",
                                               name="Num Snakes")
        snakeColorWindow = self.createColorOutputWindow(2)

        sendSnakeButton = Button(label="Send")
        sendSnakeButton.on_click(self.postSnake)

        return [
            snakeModeControls, snakeNumberControls, snakeSpeedSlider,
            snakeColorWindow, sendSnakeButton
        ]
Exemplo n.º 2
0
    def init(self, doc):
        # Source must only be modified through a stream
        self.source = ColumnDataSource(data=self.data)
        self.colors[0] = 'cyan'
        #self.source = ColumnDataSource(data=self.data[self.scale])

        # Enable theming
        theme = Theme(
            os.path.dirname(os.path.abspath(__file__)) + '/theme.yaml')
        doc.theme = theme
        self.doc = doc

        fig = figure(plot_width=600,
                     plot_height=400,
                     tools='xpan,xwheel_zoom, xbox_zoom, reset, save',
                     title=self.title,
                     x_axis_label=self.XAXIS,
                     y_axis_label=self.ylabel)

        # Initialize plots
        for i, key in enumerate(self.keys):
            fig.line(source=self.source,
                     x=self.x,
                     y=key,
                     color=self.colors[i],
                     line_width=LINE_WIDTH,
                     legend_label=key)

            band = Band(source=self.source,
                        base=self.x,
                        lower=key + 'lower',
                        upper=key + 'upper',
                        level='underlay',
                        line_color=self.colors[i],
                        line_width=1,
                        line_alpha=0.2,
                        fill_color=self.colors[i],
                        fill_alpha=0.2)
            fig.add_layout(band)

        def switch_scale(attr, old, new):
            """Callback for RadioButtonGroup to switch tick scale
            and refresh document
            Args:
                attr: variable to be changed, in this case 'active'
                old: old index of active button
                new: new index of active button
            """
            self.scale = self.scales[new]
            self.source.data = self.data[self.scale]

        self.timescales = RadioButtonGroup(
            labels=[str(scale) for scale in self.scales],
            active=self.scales.index(self.scale))
        self.timescales.on_change('active', switch_scale)

        self.structure = layout([[self.timescales], [fig]])
        self.doc.add_root(self.structure)

        self.fig = fig
Exemplo n.º 3
0
    def __init__(self):
        self.WIDTH_MATRIX = 1
        self.HEIGHT_MATRIX = 1
        self.tabs = RadioButtonGroup(labels=['Page1', 'Page2'], active=0)
        self.tabs.on_change('active',
                            lambda attr, old, new: self.change_page())

        self.data_directory = 'data'
        self.data_files = os.listdir(self.data_directory)

        self.select_data_files1 = Select(title="Data files 1:",
                                         value="df1",
                                         options=["df1"] + self.data_files)
        self.select_data_files2 = Select(title="Data files 2:",
                                         value="df2",
                                         options=["df2"] + self.data_files)

        self.select_data_files1.on_change(
            'value', lambda attr, old, new: self.init_dataframes())
        self.select_data_files2.on_change(
            'value', lambda attr, old, new: self.init_dataframes())
        self.refresh_button = Button(label="Refresh",
                                     button_type="success",
                                     width=100)
        self.refresh_button.on_click(self.update_directory)

        self.layout = column(
            self.tabs, row(self.select_data_files1, self.select_data_files2),
            self.refresh_button)
        curdoc().add_root(self.layout)
Exemplo n.º 4
0
    def createControls(self):
        delta_pres = (self.max_pres - self.min_pres) / (self.plot_scale - 1)
        delta_sat = 1.0 / (self.plot_scale - 1)

        self.slidePres = Slider(start=self.min_pres,
                                end=self.max_pres,
                                value=self.min_pres +
                                (self.max_pres - self.min_pres),
                                step=delta_pres,
                                title='Constant Pressure',
                                callback_policy='mouseup')
        self.slideSat = Slider(start=0,
                               end=1,
                               value=0.5,
                               step=delta_sat,
                               title='Constant Saturation',
                               callback_policy='mouseup')
        self.radioAbsRel = RadioButtonGroup(labels=['Absolute', 'Relative'],
                                            active=1)
        self.buttonReset = Button(label='Reset Initial Conditions')

        self.slidePres.on_change('value', self.updateCPres)
        self.slideSat.on_change('value', self.updateCSat)
        self.radioAbsRel.on_change('active', self.toggleAbsRel)
        self.buttonReset.on_click(self.clickReset)
Exemplo n.º 5
0
class SimulOptimWidget:
    def __init__(self, target, simul_df, possible_targets, var_influyentes,
                 periodo, ranges, periodo_custom_start, periodo_custom_end):
        self.simulate_wb = DynamicSimulWidget(
            target=target,
            df=simul_df,
            periodo=periodo,
            periodo_custom_start=periodo_custom_start,
            periodo_custom_end=periodo_custom_end)
        # self.optimize_wb = DynamicOptimWidget(target=target, possible_targets=possible_targets, var_influyentes=var_influyentes, ranges=ranges)
        self.optimize_wb = create_optim_div(target=target,
                                            possible_targets=possible_targets,
                                            var_influyentes=var_influyentes,
                                            ranges=ranges)
        self.wb = widgetbox([self.simulate_wb.wb],
                            sizing_mode='stretch_width',
                            max_width=690)
        self.rb = RadioButtonGroup(labels=['Simular', 'Optimizar'],
                                   height=35,
                                   active=0,
                                   min_width=690,
                                   max_width=690)
        self.rb.on_click(self.select_simul_optim)

    def select_simul_optim(self, new):
        if new == 0:
            self.wb.children = [self.simulate_wb.wb]
        else:
            self.wb.children = [self.optimize_wb]
Exemplo n.º 6
0
 def add_coaddcam(self, plots):
     #-----
     #- Highlight individual-arm or camera-coadded spectra
     coaddcam_labels = ["Camera-coadded", "Single-arm"]
     self.coaddcam_buttons = RadioButtonGroup(labels=coaddcam_labels, active=0)
     self.coaddcam_callback = CustomJS(
         args = dict(coaddcam_buttons = self.coaddcam_buttons,
                     list_lines=[plots.data_lines, plots.noise_lines,
                                 plots.zoom_data_lines, plots.zoom_noise_lines],
                     alpha_discrete = plots.alpha_discrete,
                     overlap_bands = plots.overlap_bands,
                     alpha_overlapband = plots.alpha_overlapband),
         code="""
         var n_lines = list_lines[0].length
         for (var i=0; i<n_lines; i++) {
             var new_alpha = 1
             if (coaddcam_buttons.active == 0 && i<n_lines-1) new_alpha = alpha_discrete
             if (coaddcam_buttons.active == 1 && i==n_lines-1) new_alpha = alpha_discrete
             for (var j=0; j<list_lines.length; j++) {
                 list_lines[j][i].glyph.line_alpha = new_alpha
             }
         }
         var new_alpha = 0
         if (coaddcam_buttons.active == 0) new_alpha = alpha_overlapband
         for (var j=0; j<overlap_bands.length; j++) {
                 overlap_bands[j].fill_alpha = new_alpha
         }
         """
     )
     self.coaddcam_buttons.js_on_click(self.coaddcam_callback)
Exemplo n.º 7
0
 def add_widgets(self):
     self.stream_option = RadioButtonGroup(labels=['EEG', 'ACC', 'GYR'],
                                           active=0)
     self.filter_option = RadioButtonGroup(
         labels=['Low Pass', 'High Pass', 'Band Pass'], active=0)
     self.widget_box = widgetbox(self.stream_option,
                                 self.filter_option,
                                 width=300)
Exemplo n.º 8
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)
Exemplo n.º 9
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
Exemplo n.º 10
0
def build_dashboard(path: Path, num_queries=1000):
    output_file(str(path / 'dashboard.html'))

    data = pd.read_csv(str(path / 'overall_metrics.csv'), index_col=0, dtype={
        'dataset': str,
        'click_model': str,
        'online_benchmark': np.float64,
        'offline_benchmark': np.float64,
        'online_mean@10': np.float64,
        'online_std@10': np.float64,
        'offline_mean @ 10': np.float64,
        'offline_std @ 10': np.float64
    })
    COLOR_MAPPING = dict(zip(data.dataset.unique(), Category10[9]))

    data['color'] = data.dataset.map(COLOR_MAPPING)

    data['lower_offline'] = data['offline_mean@10'] - data['offline_std@10']
    data['upper_offline'] = data['offline_mean@10'] + data['offline_std@10']

    data['lower_online'] = data['online_mean@10'] - data['online_std@10']
    data['upper_online'] = data['online_mean@10'] - data['online_std@10']

    data['y'] = data['offline_mean@10']
    data['x'] = data.index.values
    source = ColumnDataSource(data)
    view = CDSView(source=source, filters=DEFAULT_FILTERS)

    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    hover = HoverTool(tooltips=[("NDCG@10", "$y")])
    p = figure(tools=TOOLS, x_range=(0, num_queries), y_range=(0, 1))
    p.add_tools(hover)

    p.line(x='x', y='y', source=source, view=view, line_color=data.color.iloc[0], legend='GA-TDM')
    
    p.line(x='x', y='online_benchmark', source=source, view=view, line_color='red', legend='MGD-19')
    p.line(x='x', y='offline_benchmark', source=source, view=view, line_color='black', legend='MGD-19')

    # Widgets
    # Evaluation mode
    eval_mode_rb = RadioButtonGroup(labels=['Offline', 'Online'], active=0, callback=change_eval_mode(source, p, view))
    # Click model
    click_model_rb = RadioButtonGroup(labels=['Perfect', 'Navigational', 'Informational'], active=0, callback=change_cm(view))
    # Dataset
    dataset_select = Select(title="Dataset", value="HP2003", options=list(data.dataset.unique()), callback=change_ds(view))
    
    # Legend
    p.legend.location = 'top_left'

    wb = widgetbox([eval_mode_rb, click_model_rb, dataset_select])

    save(column([wb, p]))
Exemplo n.º 11
0
    def _doc_modifier(doc: Document) -> None:
        plot, source = _create_plot(stats, aspects)
        events_table = _create_events_table()
        events_type = RadioButtonGroup(labels=['All Events', 'In-Domain Events'], active=0)

        # pylint: disable=unused-argument
        def _events_handler(attr, old, new):
            _update_events(stats, aspects, events_table, source, events_type.active)

        events_type.on_change('active', _events_handler)
        source.selected.on_change('indices', _events_handler)  # pylint: disable=no-member
        doc.add_root(column(_create_header(), plot, events_type, events_table,
                            sizing_mode="scale_width"))
Exemplo n.º 12
0
def classification_tab():
    pairs = [["stackoverflow.com", "academia.stackexchange.com"],["stackoverflow.com", "softwareengineering.stackexchange.com"]]
    
    # pretrained classification models
    nbsoac = load("app/models/10k_so_ac_bayes_model.joblib")
    nbsose = load("app/models/10k_so_se_bayes_model.joblib")
    svmsoac = load("app/models/10k_so_ac_SVM_model.joblib")
    svmsose = load("app/models/10k_so_se_SVM_model.joblib")
    
    learning_type = RadioButtonGroup(labels=["Bayes", "Support Vector Machine"], active=0)
    
    site_pair = RadioButtonGroup(labels=["Stack Overflow/Academia", "Stack Overflow/Software Engineering"], active=0)
    
    tai = TextAreaInput(value="", rows=6, title="Enter a post message:")
    
    predict = Button(label="Predict", button_type="success")
    
    p = Paragraph(text="""Your Site Prediction will be displayed here""",
            width=300, height=50)
    
    def make_prediction():
        lt = learning_type.active
        sp = site_pair.active
        model = None
        if lt == 0:
            if sp == 0:
                model = nbsoac
            else:
                model = nbsose
        else:
            if sp == 0:
                model = svmsoac
            else:
                model = svmsose
        prediction = model.predict([tai.value])[0]
        p.text = "Message belongs to site: " + pairs[sp][prediction - 1]


    predict.on_click(make_prediction)

    # Put controls in a single element
    controls = WidgetBox(learning_type, site_pair, tai, predict, p)

    # Create a row layout
    layout = row(controls)

    tab = Panel(child=layout, title='Message Site Classification')
    
    return tab
Exemplo n.º 13
0
    def enable_interaction(self):
        radiokeys = list(self._scatters.keys())
        self._which_scatter = RadioButtonGroup(labels=radiokeys, active=0)
        data_sources = {
            key: scatter.data_source
            for key, scatter in self._scatters.items()
        }
        js_argdict = f"""{{
            { ','.join(f"{i}: {k}" for i, k in enumerate(radiokeys)) }
        }}"""
        self.figure.js_on_event('tap', CustomJS(
            args=dict(which_scatter=self._which_scatter, **data_sources),
            code=f"""
                var argdict = {js_argdict};
                var scatter = argdict[which_scatter.active];
                var data = {{
                    'x': scatter.data.x,
                    'y': scatter.data.y
                }};
                data['x'].push(cb_obj['x']);
                data['y'].push(cb_obj['y']);
                scatter.data = data;
                scatter.change.emit();
            """
        ))

        for source_name, data_source in data_sources.items():
            self.register_state_attribute(source_name, data_source, 'data', prefix=['inputs'])
Exemplo n.º 14
0
    def get_layout_query(self):
        heading_text="A program that displays every episode's rating for the tv_series."
        heading=Paragraph(text=heading_text,width=400)
        self.Search = Button(label="Search")
        self.btnGroupchoose = RadioButtonGroup(name='choose', labels=["By imdbID", "By Title"], active=0)
        paragraph = Paragraph(text="Search way")
        self.Parameter_input = TextInput(value="", title="ID or Title:", placeholder="ID or Title")
        self.select = Select(title="Season:", value="None", options=["None"])
        self.Status=Paragraph(text="Status:",width=200)
        self.Tvtext=Paragraph(text="Tv:",width=200)
        self.Seasontext=Paragraph(text="Season:",width=200)

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

        p = figure(x_range=x,plot_height=400,title="Season rating",
                   toolbar_location=None, tools="")

        p.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
        p.xaxis.major_label_orientation = 1

        self.Search.on_click(self.search_click)
        self.select.on_change('value',self.select_click)

        self.layout_query = layout(
            [
                [heading],
                [[widgetbox(paragraph, width=100),widgetbox(self.btnGroupchoose)],
                [widgetbox(self.Parameter_input)],
                [widgetbox(self.Search, width=100)],],
                [[self.Status,self.Tvtext,self.Seasontext],self.select],
                p
            ]
        )
Exemplo n.º 15
0
    def create(cls):
        """One-time creation of app's objects.

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

        obj.utc_button = RadioButtonGroup(labels=["local time", "UTC"],
                                          active=cs.utc_start)

        obj.source_data_range = ColumnDataSource(data=dict(x=[], y=[]))
        obj.p_manager.create(obj.source_data_range)

        obj.plot_weather = obj.p_manager.plot_weather
        obj.plot_ceil = obj.p_manager.plot_ceil
        obj.plot_data_range = obj.p_manager.plot_data_range

        obj.plot_ceil.x_range = obj.plot_weather.x_range

        obj.children.append(obj.utc_button)
        obj.children.append(obj.plot_data_range)
        obj.children.append(obj.plot_ceil)
        obj.children.append(obj.plot_weather)

        if cs.utc_start == 0:
            print 'changing to utc '
            sys.stdout.flush()
            obj.p_manager.shift_time(obj, 0)

        return obj
Exemplo n.º 16
0
    def __init__(self, options_list, risk_free_rate, iv):
        self.options = options_list
        self.r = risk_free_rate
        self.iv = iv
        self.curr_iv = iv
        self.t = datetime.today()
        self.expiry_t = self.options[0].expiration

        self.x_vector = None
        self.min_strike = None
        self.max_strike = None

        # Widgets
        self.right_radio = RadioButtonGroup(labels=["Calls", "Puts"], active=0)
        self.expiry_slider = Slider(title="Days to exp.",
                                    value=0.0,
                                    start=-5.0,
                                    end=5.0,
                                    step=1)
        self.iv_slider = Slider(title="IV",
                                value=self.curr_iv,
                                start=0.0,
                                end=1.0,
                                step=0.01)
        self.restore_iv_button = Button(label="Restore IV")
Exemplo n.º 17
0
    def make_input_widgets(self):
        """Define the widgets to select dataset, verification package,
        metrics and period
        """

        self.datasets_widget = Select(title="Dataset:",
                                      value=self.selected_dataset,
                                      options=self.datasets['datasets'])

        self.filters_widget = Select(title="Filter:",
                                     value=self.selected_filter,
                                     options=self.filters)

        self.packages_widget = Select(title="Verification package:",
                                      value=self.selected_package,
                                      options=self.packages['packages'])

        self.metrics_widget = Select(title="Metric:",
                                     value=self.selected_metric,
                                     options=self.metrics['metrics'])

        active = self.periods['periods'].index(self.selected_period)

        self.period_widget = RadioButtonGroup(labels=self.periods['periods'],
                                              active=active)
Exemplo n.º 18
0
    def __init__(self, logdata: DataFrame):
        self.line_dataset = None
        self.scatter_dataset = None
        self.logdata = logdata

        # Partition markers, filter out span data from full log
        self.span_locations = logdata[logdata.Name.isin(conf.sections)]
        self.logdata = self.logdata[~self.logdata.Name.isin(conf.sections)]

        # Convert to datetime format
        self.logdata.Timestamp = to_datetime(self.logdata.Timestamp, unit='ms')

        # Scatter data
        self.scatter_data = self.logdata

        # Multi line data prep
        self.line_data = self.logdata.groupby('Channel').aggregate({
            'Timestamp':
            list,
            'Value':
            list
        })

        self.id_list = list(self.line_data.index)
        self.id_list.sort()
        self.line_checkbox = CheckboxGroup(labels=self.id_list)
        self.line_checkbox.on_change('active', self.lineplot_handler)
        self.scatter_checkbox = CheckboxGroup(labels=self.id_list)
        self.scatter_checkbox.on_change('active', self.scatterplot_handler)

        #self.duration = self.logdata.Timestamp.max() -
        self.reaction_times = [1, 2, 3, 4, 5]
        self.extra_data_text = PreText(text='')

        try:
            self.sections = generate_sections(logdata)
            radio_labels = [
                'Section %s' % i for i in range(len(self.sections))
            ]
            radio_labels.append('All')
            self.radio_buttons = RadioButtonGroup(labels=radio_labels,
                                                  active=len(radio_labels) - 1)
            self.radio_buttons.on_change('active', self.radio_button_handler)
        except IndexError:
            print('Missing Slide values. Skipping section generation')
            self.radio_buttons = RadioButtonGroup(labels=['Fix your data'])
Exemplo n.º 19
0
def add_count_toggle(plot):
    from bokeh.layouts import widgetbox
    from bokeh.models import (CustomJS, Column, Circle, Rect, ColumnDataSource,
                              LinearColorMapper, ColorBar, Label)
    from bokeh.models.widgets import RadioButtonGroup

    args = dict(
        circle=None,
        rect=None,
    )
    for r in plot.references():
        if isinstance(r, Circle):
            args['circle'] = r
        elif isinstance(r, Rect):
            args['rect'] = r
        elif isinstance(r, LinearColorMapper):
            args['cmapper'] = r
        elif isinstance(r, ColorBar):
            args['cbar'] = r
        elif isinstance(r, ColumnDataSource):
            args['ds'] = r
        elif isinstance(r, Label):
            args['title'] = r

    callback = CustomJS(args=args,
                        code="""
       var label = cb_obj.labels[cb_obj.active];
       var selection = {Observations: 'count', Subjects: 'subjects'}[label];
       if (circle !== null) {circle.fill_color.field = selection};
       if (rect !== null && rect.fill_color) {rect.fill_color.field = selection };
       var max_val = Math.max.apply(null, ds.data[selection]);
       cmapper.high = max_val;
       cbar.ticker.ticks = [0, max_val];
       split_title = title.text.split(' ');
       split_title[2] = label.toLowerCase();
       title.text = split_title.join(' ');
       ds.trigger("change");
    """)

    plot.min_border_top = 50
    radio_button_group = RadioButtonGroup(labels=["Observations", "Subjects"],
                                          active=0)
    radio_button_group.callback = callback
    widgets = widgetbox(radio_button_group, width=300)
    return Column(widgets, plot)
Exemplo n.º 20
0
    def modify_doc(self, doc):
        # checkboxes for groups
        self.group_selection_add = CheckboxGroup(labels=self.group_ids,
                                                 active=[0, 1])
        self.group_selection_add.on_change('active', self.update_add)
        initial_groups = [i + 1 for i in self.group_selection_add.active]
        # radio button for data type
        self.type_selection_add = RadioButtonGroup(
            labels=["Prior", "After", "Diff"], active=0)
        self.type_selection_add.on_change('active', self.update_add)
        initial_type = self.type_selection_add.active
        # add control and initialize display
        controls = WidgetBox(self.group_selection_add, self.type_selection_add)
        self.sources_add = self.make_dataset_add(initial_groups, initial_type)
        # add two panels, one for adding
        p = self.make_plot(self.sources_add, True)
        layout = row(controls, p)
        tab1 = Panel(child=layout, title='Add')

        # # checkboxes for groups
        # self.possible_groups = list(combinations([1,2,3], 2))
        # labels = []
        # for pg in self.possible_groups:
        #     labels.append(self.group_ids[pg[0]] + ' vs ' + self.group_ids[pg[1]])
        # self.group_selection_comp = RadioButtonGroup(labels=labels, active=0)
        # self.group_selection_comp.on_change('active', self.update_comp)
        # initial_groups = self.possible_groups[self.group_selection_comp.active]
        # # radio button for data type
        # self.type_selection_comp = RadioButtonGroup(labels=["Prior", "After", "Diff"], active=0)
        # self.type_selection_comp.on_change('active', self.update_comp)
        # initial_type = self.type_selection_comp.active
        # # add control and initialize display
        # controls = WidgetBox(self.group_selection_comp, self.type_selection_comp)
        # self.sources_comp = {}
        # for i, g in enumerate(self.group_ids):
        #     # for initialization only
        #     self.sources_comp[g] = self.make_dataset_add([i], initial_type)
        # # add two panels, one for adding
        # p = self.make_plot(self.sources_comp, False)
        # layout = row(controls, p)
        # tab2 = Panel(child=layout, title = 'Compare')

        # Make a tab with the layouts
        tabs = Tabs(tabs=[tab1])
        doc.add_root(tabs)
Exemplo n.º 21
0
    def __init__(self, name='', pg_type='Product'):

        self.name = TextInput(value=name, width=250)
        self.pg_type = pg_type

        self.num_attributes = Spinner(title="Number of attributes", low=1, high=100, step=1, value=1, width=150)
        self.num_attributes.on_change('value', self.update_attributes, self.update_attribute_selector)

        self.attributes = [Attribute()]
        self.attribute_selector = RadioButtonGroup(labels=['Attribute #1'], active=0)
Exemplo n.º 22
0
    def use_server_with_radio_buttons(self):
        # crate columndatasource
        source = ColumnDataSource(
            dict(average_grades=["B+", "A", "D-"],
                 exam_grades=["A+", "C", "D"],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        # create the figure
        f = figure(x_range=[
            "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A",
            "A+"
        ],
                   y_range=[
                       "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+",
                       "A-", "A", "A+"
                   ])

        # add labels for glyphs
        labels = LabelSet(x="average_grades",
                          y="exam_grades",
                          text="student_names",
                          x_offset=5,
                          y_offset=5,
                          source=source)
        f.add_layout(labels)

        # create glyphs
        f.circle(x="average_grades", y="exam_grades", source=source, size=8)

        # create function
        def update_labels(attr, old, new):
            labels.text = options[radio_button_group.active]

        # create select widget
        options = ["average_grades", "exam_grades", "student_names"]
        radio_button_group = RadioButtonGroup(labels=options)
        radio_button_group.on_change("active", update_labels)

        # create layout and add to curdoc
        lay_out = layout([[radio_button_group]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Exemplo n.º 23
0
 def add_vi_quality(self, viewer_cds, widgets):
     #- Main VI quality widget
     self.vi_quality_input = RadioButtonGroup(labels=self.vi_quality_labels)
     vi_quality_code = self.js_files["CSVtoArray.js"] + self.js_files["save_vi.js"]
     vi_quality_code += """
         if ( vi_quality_input.active >= 0 ) {
             cds_metadata.data['VI_quality_flag'][ifiberslider.value] = vi_quality_labels[vi_quality_input.active]
         } else {
             cds_metadata.data['VI_quality_flag'][ifiberslider.value] = "-1"
         }
         autosave_vi_localStorage(output_file_fields, cds_metadata.data, title)
         cds_metadata.change.emit()
     """
     self.vi_quality_callback = CustomJS(
         args = dict(cds_metadata = viewer_cds.cds_metadata,
                     vi_quality_input = self.vi_quality_input,
                     vi_quality_labels = self.vi_quality_labels,
                     ifiberslider = widgets.ifiberslider,
                     title=self.title, output_file_fields = self.output_file_fields),
         code=vi_quality_code )
     self.vi_quality_input.js_on_click(self.vi_quality_callback)
Exemplo n.º 24
0
def source_filters(sources):
    def _handle_state_filter():
        for fullname in sources['dataframes']:
            df = sources['dataframes'][fullname]
            df = df[(df.index >= _state['date_range'][0]) & (df.index <= _state['date_range'][1])]
            units = UNIT_CONVERSION_MAP[_state['units']]
            df = df * UNIT_CONVERSION[units]
            sources['sources'][fullname].data = ColumnDataSource(df).data

        for callback in ELEMENT_CALLBACKS:
            callback(sources=sources, **_state)

    def _date_slider_handler(attr, old, new):
        start_time, end_time = new
        start_date = dt.datetime.fromtimestamp(start_time / 1000)
        end_date = dt.datetime.fromtimestamp(end_time / 1000)
        _state['date_range'] = (start_date, end_date)
        _handle_state_filter()

    start_date = dt.datetime(year=2018, month=12, day=1)
    end_date = dt.datetime(year=2018, month=12, day=1)
    date_slider = DateRangeSlider(start=_state['date_range'][0], end=_state['date_range'][1], value=_state['date_range'], step=1, title="Date Range", height=100)
    date_slider.on_change('value', _date_slider_handler)

    def _radio_button_group_handler(attr, old, new):
        _state['units'] = int(new)
        _handle_state_filter()

    radio_button_group = RadioButtonGroup(labels=UNIT_CONVERSION_MAP, active=0, width=700, height=100)

    radio_button_group.on_change('active', _radio_button_group_handler)

    div_button_group_selection = Div(text=f'<img src="/visualization/static/images/{UNIT_CONVERSION_MAP[_state["units"]]}.svg" height="100px"/>', height=100)

    def _update_div_button_group(**kwargs):
        units = UNIT_CONVERSION_MAP[kwargs['units']]
        div_button_group_selection.text = f'<img src="/visualization/static/images/{units}.svg" height="100px"/>'
    ELEMENT_CALLBACKS.append(_update_div_button_group)

    return [date_slider, radio_button_group, div_button_group_selection]
Exemplo n.º 25
0
    def __init__(self):

        self.WIDTH_MATRIX = WIDTH_MATRIX
        self.HEIGHT_MATRIX = HEIGHT_MATRIX
        self.DATA_DIRIRECTORY = DATA_DIR
        self.plots_rock = column()
        self.source_correlation_plot = None
        self.select_plots = []

        self.view_model = views.ViewModel.ViewModel()

        self.data_files = os.listdir(self.DATA_DIRIRECTORY)
        self.my_data_frames = models.MyDataFrames.MyDataFrames()
        self.Y_COL = self.my_data_frames.get_name_dept()
        self.tabs = RadioButtonGroup(labels=['Page1', 'Page2'], active=0)
        self.tabs.on_change('active',
                            lambda attr, old, new: self.change_page())

        self.select_data_files1 = Select(title="Data files 1:",
                                         value="df1",
                                         options=["df1"] + (self.data_files))
        self.select_data_files2 = Select(title="Data files 2:",
                                         value="df2",
                                         options=["df2"] + (self.data_files))

        self.select_data_files1.on_change(
            'value', lambda attr, old, new: self.change_dataframes())
        self.select_data_files2.on_change(
            'value', lambda attr, old, new: self.change_dataframes())
        self.refresh_button = Button(label="Refresh",
                                     button_type="success",
                                     width=100)
        self.refresh_button.on_click(self.update_directory)

        self.plot_matrix = views.PlotMatrix.PlotMatrix()
        self.layout = column(
            self.tabs, row(self.select_data_files1, self.select_data_files2),
            self.refresh_button)
        curdoc().add_root(self.layout)
Exemplo n.º 26
0
    def show_analysis() -> None:
        global stats, aspects, plot, source, tabs
        plot, source = _create_plot()
        events_table = _create_events_table()

        # pylint: disable=unused-argument
        def _events_handler(attr, old, new):
            _update_events(events_table, events_type.active)

        # Toggle display of in-domain / All aspect mentions
        events_type = RadioButtonGroup(labels=["All Events", "In-Domain Events"], active=0)

        analysis_layout = layout([[plot], [events_table]])

        # events_type display toggle disabled
        # analysis_layout = layout([[plot],[events_type],[events_table]])

        analysis_tab = Panel(child=analysis_layout, title="Analysis")
        tabs.tabs.insert(2, analysis_tab)
        tabs.active = 2
        events_type.on_change("active", _events_handler)
        source.selected.on_change("indices", _events_handler)  # pylint: disable=no-member
Exemplo n.º 27
0
def bkapp(doc):
    def update_plot(attrname, old_value, new_value):
        disease = disease_selector.value
        smooth = int(smooth_selector.value)
        src = models.get_disease_totals_by_name(disease, smooth)
        source.data.update(src.data)
        chart.title.text = disease
        disease_selector.label = disease
        smooth_selector.label = str(smooth)
        doc.title = "Epidemic - {}".format(disease)

    # request
    args = doc.session_context.request.arguments
    get_param = lambda param, default: args.get(
        param, [bytes(str(default), encoding='utf')])[0].decode('utf-8')
    disease = get_param('disease', DEFAULT_DISEASE)
    smooth = get_param('smooth', 2)
    ## Components

    # Widgets
    disease_selector = Dropdown(label=disease,
                                value=disease,
                                menu=list(zip(DISEASES, DISEASES)))
    smooth_selector = Dropdown(label=smooth,
                               value=smooth,
                               menu=[(str(i), str(i)) for i in range(1, 9)])
    picker = RadioButtonGroup(labels=['Total Cases', 'Cases by Region'],
                              width=300)

    # Sources

    source = ColumnDataSource(
    )  # models.get_disease_data_by_name(disease,smooth)
    # Events
    disease_selector.on_change('value', update_plot)
    smooth_selector.on_change('value', update_plot)

    # Figures
    chart = make_plot(source, disease)
    ranger = make_range_tool(chart)
    chart_range = make_range_plot(source, ranger)

    #
    controls = column(widgetbox(disease_selector, smooth_selector, picker),
                      height=280)
    charts_col = column(chart, chart_range, width=1024)

    doc.add_root(row(charts_col, controls))
    doc.title = "Epidemic - {}".format(disease)
    update_plot(None, None, None)
Exemplo n.º 28
0
    def _init_controls(self):
        """Initialize all controls in the dashboard"""
        # EEG/ECG Radio button
        self.mode_control = RadioButtonGroup(labels=MODE_LIST, active=0)
        self.mode_control.on_click(self._change_mode)

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

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

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

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

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

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

        # Add widgets to the doc
        m_widgetbox = widgetbox([self.mode_control, self.y_scale, self.t_range, self.heart_rate,
                                 self.battery, self.temperature, self.light, self.firmware], width=220)
        return m_widgetbox
    def setupControls(self):
        boardModeButtons = RadioButtonGroup(labels=self.boardModes,
                                            active=0,
                                            width=400,
                                            button_type="primary")
        boardModeButtons.on_change("active", self.boardModeCallback)

        self.brightnessSlider = Slider(title="Brightness",
                                       show_value=False,
                                       height=self.figureSize,
                                       value=.5,
                                       start=0,
                                       end=1,
                                       step=.1,
                                       orientation="vertical")
        self.brightnessSlider.on_change("value", self.brightnessCallback)

        #create an empty row to store the active controls in
        activeControlsBox = column(name="activeControls")

        #setup the image handler controls to control the board
        cIS.iconFileSource.on_change('data', self.iconFileCallback)

        self.controls = column(boardModeButtons, activeControlsBox)
Exemplo n.º 30
0
    def view_setup(self):

        self.text5 = Div(text="Ticker downloader:", width=150)

        self.tickerdownloader = TextInput(value='', width=80)
        self.tickerdownloadbutton = Button(label='Press to download',
                                           button_type='default',
                                           disabled=False,
                                           width=50)
        self.tickerdownloadbutton.on_click(self.tickerdownloadbutton_handler)

        self.exchangebutton = RadioButtonGroup(labels=["NYSE", "NASDAQ"],
                                               active=0,
                                               width=140)
        self.exchangebutton.on_change("active", self.exchange)

        self.widgets = column(
            column(self.text5, self.tickerdownloader,
                   self.tickerdownloadbutton, self.exchangebutton))
        main_row = row(self.widgets)
        layout = column(main_row)

        curdoc().add_root(layout)
        curdoc().title = "Stocks"
Exemplo n.º 31
0
        update_plot(f, N, t_start, t_end)


# initialize data source
source_fourier = ColumnDataSource(data=dict(t=[], x_fourier=[]))
source_orig = ColumnDataSource(data=dict(t=[], x_orig=[]))
source_interval_patch = ColumnDataSource(data=dict(x_patch=[], y_patch=[]))
source_interval_bound = ColumnDataSource(data=dict(x_min=[], x_max=[], y_minmax=[]))
source_coeff = ColumnDataSource(data=dict(a=[], b=[]))
source_f = ColumnDataSource(data=dict(f=[None]))
source_periodicity = ColumnDataSource(data=dict(t_start=[None], t_end=[None]))
source_view = ColumnDataSource(data=dict(x_start=[None], x_end=[None], y_start=[None], y_end=[None]))

# initialize controls
# buttons for choosing a sample function
sample_function_type = RadioButtonGroup(labels=fs.function_names, active=fs.function_init)

# here one can choose arbitrary input function
default_function_input = TextInput(value=fs.function_input_init)
default_function_period_start = TextInput(title='period start', value=fs.timeinterval_start_init)
default_function_period_end = TextInput(title='period end', value=fs.timeinterval_end_init)

# slider controlling degree of the fourier series
degree = Slider(title="degree", name='degree', value=fs.degree_init, start=fs.degree_min,
                end=fs.degree_max, step=fs.degree_step)

# initialize callback behaviour
degree.on_change('value', degree_change)
default_function_input.on_change('value',
                                 type_input_change)  # todo write default functions for any callback, like above
default_function_period_start.on_change('value', type_input_change)
Exemplo n.º 32
0
p2 = figure(width = 600, height = 400, title = 'Area difference of Nearest Neighbors',
			x_axis_label = 'Formation time, s')

p2.segment('x', 'sdplus', 'x', 'sdminus', source = s2, line_width = 2)
p2.circle('x', 'y', color = 'color', source = s2, size = 12, alpha = 0.65)

p3 = figure(width = 600, height = 400, title = 'Plot of Area vs. Area',
			x_axis_label = 'Area (um^2)',
			y_axis_label = 'Area (um^2)')
p3.segment('x', 'ysdplus', 'x', 'ysdminus', source = s3, line_width = 2)
p3.segment('xsdplus', 'y', 'xsdminus', 'y', source = s3, line_width = 2)
p3.circle('x', 'y', color = 'color', source = s3, size = 12, alpha = 0.65)

# Set up widgets
kneighb = Slider(title = 'Number of nearest neighbors to average', value = 1, start = 1, end = (k - 1), step = 1)
radio_button_group1 = RadioButtonGroup(labels=["NN Distance", "NN Index"], active = 0)
radio_button_group2 = RadioButtonGroup(labels=["Average", "NN Difference", "NN Difference Index"], active=0)
menu = [('Area', 'Area'), ('Coherency', 'Coherency'), ('Orientaiton', 'Orientation')]
dropdown = Dropdown(label = 'Lower Right Parameter', menu = menu, value = 'Area')
menu2 = [('Area', 'Area'), ('Coherency', 'Coherency'), ('Orientaiton', 'Orientation'), ('Distance', 'Distance')]
x3drop = Dropdown(label = 'Lower Left X-axis', menu = menu2, value = 'Area')
y3drop = Dropdown(label = 'Lower Left Y-axis', menu = menu2, value = 'Area')

pTXT = Paragraph(text = """Welcome to the interactive Nearest Neighbor data explorer. The first toggle controls
 the top right plot, selecting average NN distance in microns, or NN Index (normalized by the number of domains).
 The next menus control the lower two plots: select which parameter to be plotted with the dropdown menus, and
 use the toggle to pick average value, average NN difference, or NN difference index. Green points are constant
 flow series, Pink are constant volume series. Error bars are 1/4 standard deviation.""")

w = widgetbox(pTXT, radio_button_group1, dropdown, x3drop, y3drop, radio_button_group2)
Exemplo n.º 33
0
widgets.append(x_field)
y_field = Select(
    title = 'Y-Axis Value',
    options=sorted([
        (key, val) for (key, val) in cols.items()
    ], key = lambda x:x[1]),
    value = 'best_mt_score'
)
widgets.append(y_field)
hide_null = Toggle(
    active=True,
    label="Hide 0 results with null X or Y axis values"
)
widgets.append(hide_null)

presets = RadioButtonGroup(
    labels=["MT vs WT Epitope Affinity", "Tumor Clonality and Expression"], active=0)

def available(x):
    for entry in entries:
        if x in entry and entry[x] is not None:
            return True
    return False

if not available('corresponding_wt_score') or not available('best_mt_score'):
    presets.labels.remove('MT vs WT Epitope Affinity')
if not available('tumor_dna_vaf') or not available('tumor_rna_vaf'):
    presets.labels.remove('Tumor Clonality and Expression')
widgets.append(presets)

#Set up the data dictionary (a transposed version of entries)
data_dict = {
Exemplo n.º 34
0
dropdown_disabled = Dropdown(label="Dropdown button (disabled)", button_type="warning", disabled=True, menu=menu)
dropdown_disabled.js_on_click(CustomJS(code="console.log('dropdown_disabled: ' + this.value, this.toString())"))

#dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="default")
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

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

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

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

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

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

doc = Document()
doc.add_root(widget_box)

if __name__ == "__main__":
    doc.validate()
Exemplo n.º 35
0
#dropdown_split.on_click(lambda value: print('dropdown_split: %s' % value))
#dropdown_split.js_on_click(CustomJS(code="console.log('dropdown_split: ' + this.value, this.toString())"))

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

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

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

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

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

document = curdoc()
document.add_root(widgetBox)

if __name__ == "__main__":
Exemplo n.º 36
0
X = np.copy(X_init)
hist, edges = np.histogram(X, density=True, bins=50)

p1 = figure(x_range=[-10, 10], y_range=[-0.7, 0.7])
p1.add_tools(ResizeTool())
r1 = p1.line(x, y, color="navy")
h1 = p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#036564", line_color="#033649", alpha=0.5)

p2 = figure()
p2.add_tools(ResizeTool())
h2 = p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
           fill_color="#036564", line_color="#033649", alpha=0.5)

slider = Slider(start=1, end=10, value=1, step=.1, title="Speed")
button_group = RadioButtonGroup(labels=["Play", "Pause"], active=1)
button = Button(label="Reset", button_type="warning")
it = PreText(text="Iteration 1")
wb = widgetbox(slider, button_group, button, it)


session = push_session(curdoc())

def redraw():
    hist, edges = np.histogram(X, density=True, bins=50)
    h1.data_source.data["top"] = hist
    h1.data_source.data["left"] = edges[:-1]
    h1.data_source.data["right"] = edges[1:]

    hist, edges = np.histogram(math.sqrt(step)*X, density=True, bins=50)
    h2.data_source.data["top"] = hist
from bokeh.plotting import figure

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

df=pd.DataFrame({'x':x,'y':y,'label':label})

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

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

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

radio_button_group = RadioButtonGroup(labels=["Red", "Orange"])

def radiogroup_click(attr,old,new):
    active_radio=radio_button_group.active ##Getting radio button value

    # filter the dataframe with value in radio-button
    if active_radio==0:
        selected_df = df[df['label'] == 'Red']
    elif active_radio==1:
        selected_df = df[df['label'] == "Orange"]

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


radio_button_group.on_change('active',radiogroup_click)
Exemplo n.º 38
0
dropdown = Dropdown(label="Dropdown button", type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

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

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

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

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

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

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

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

if __name__ == "__main__":
    link = session.object_link(document.context)
    print("Please visit %s to see the plots" % link)
    view(link)
    print("\npress ctrl-C to exit")
    session.poll_document(document)
p_title.grid.grid_line_color = None
p_title.outline_line_color = None
p_title.axis.visible = None

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


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

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

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

cluster_commonality = Div(
Exemplo n.º 40
0
''' ran change from original '''
def open_local_file(attr,old,new):
    labels.text = ["chosen file is : " + tkFileDialog.askopenfilename()]
    print labels.text

def open_local_file_long(attr,old,new):
    import wx
    import os

    app = wx.PySimpleApp()
    wildcard = "Python source (*.py)|*.py|" \
               "Compiled Python (*.pyc)|*.pyc|" \
               "All files (*.*)|*.*"
    dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN)
    if dialog.ShowModal() == wx.ID_OK:
        print dialog.GetPath()

    dialog.Destroy()


#create select widget
options=["average_grades","exam_grades","student_names"]
radio_button_group=RadioButtonGroup(labels=options)
# radio_button_group.on_change("active",update_labels)
radio_button_group.on_change("active",open_local_file)

#create layout and add to curdoc
lay_out=layout([[radio_button_group]])
curdoc().add_root(f)
curdoc().add_root(lay_out)
Exemplo n.º 41
0
snr_plot.yaxis.axis_label='F_p/F_s (x10^9)' 
snr_plot.xaxis.axis_label='Wavelength [micron]' 

snr_plot.line('lam','cratio',source=planet,line_width=2.0, color="green", alpha=0.7)
snr_plot.circle('lam', 'spec', source=planet, fill_color='red', line_color='black', size=8) 
snr_plot.segment('lam', 'downerr', 'lam', 'uperr', source=planet, line_width=1, line_color='grey', line_alpha=0.5) 

def change_filename(attrname, old, new): 
   format_button_group.active = None 


instruction0 = Div(text="""Choose a file rootname here 
                           (no special characters):""", width=300, height=15)
text_input = TextInput(value="filename", title=" ", width=100)
instruction1 = Div(text="""Then choose a format here:""", width=300, height=15)
format_button_group = RadioButtonGroup(labels=["txt", "fits"])
instruction2 = Div(text="""Your file will be linked here:""", width=300, height=15)
link_box  = Div(text=""" """, width=300, height=15)


def i_clicked_a_button(new): 
    filename=text_input.value + {0:'.txt', 1:'.fits'}[format_button_group.active]
    print "Your format is   ", format_button_group.active, {0:'txt', 1:'fits'}[format_button_group.active] 
    print "Your filename is: ", filename 
    fileformat={0:'txt', 1:'fits'}[format_button_group.active]
    link_box.text = """Working""" 
 
    t = Table(planet.data)
    t = t['lam', 'spec','cratio','uperr','downerr'] 

    if (format_button_group.active == 1): t.write(filename, overwrite=True)