Exemplo n.º 1
0
    def test_callback_property_executes(self, single_plot_page):
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
        plot.add_glyph(source, Circle(x='x', y='y', size=20))
        text_input = TextInput(css_classes=['foo'])
        text_input.callback = CustomJS(code=RECORD("value", "cb_obj.value"))

        page = single_plot_page(column(text_input, plot))

        el = page.driver.find_element_by_class_name('foo')

        enter_text_in_element(page.driver, el, "val1")

        results = page.results
        assert results['value'] == 'val1'

        # double click to highlight and overwrite old text
        enter_text_in_element(page.driver, el, "val2", click=2)

        results = page.results
        assert results['value'] == 'val2'

        # Check clicking outside input also triggers
        enter_text_in_element(page.driver, el, "val3", click=2, enter=False)
        page.click_canvas_at_position(10, 10)
        results = page.results

        assert results['value'] == 'val3'

        assert page.has_no_console_errors()
Exemplo n.º 2
0
def modify_doc(doc):
    source = ColumnDataSource(data=get_data(200))

    p = figure(toolbar_location=None)
    r = p.circle(x='x',
                 y='y',
                 radius='r',
                 source=source,
                 color="navy",
                 alpha=0.6,
                 line_color="white")

    select = Select(title="Color", value="navy", options=COLORS)
    input = TextInput(title="Number of points", value="200")

    def update_color(attrname, old, new):
        r.glyph.fill_color = select.value

    select.on_change('value', update_color)

    def update_points(attrname, old, new):
        N = int(input.value)
        source.data = get_data(N)

    input.on_change('value', update_points)

    layout = column(row(select, input, width=400), row(p))

    doc.add_root(layout)
Exemplo n.º 3
0
 def ajoute_input_num(self,
                      title: str = None,
                      groupby: str = None,
                      max_width=80) -> None:
     """Sélection du tronçon par une colonne de la table."""
     if groupby is None:
         groupby = self.tron_idx_name
     if title is None:
         title = self.tron_idx_name
     index_par_tron = DataFrame(self.tron).groupby(groupby).apply(
         lambda s: list(s.index)).to_dict()
     self.input_num = TextInput(value="", title=title, max_width=max_width)
     callback_text = CustomJS(
         args=dict(
             text=self.input_num,
             src_lines=self.source_lines,
             index_par_tron=index_par_tron,
         ),
         code="""if (text.value in index_par_tron) {
             src_lines.selected.indices = index_par_tron[text.value]
             src_lines.change.emit();
             }
             """,
     )
     self.input_num.js_on_change("value", callback_text)
Exemplo n.º 4
0
    def test_multi_row_copy(self, bokeh_model_page) -> None:
        data = {'x': [1,2,3,4], 'y': [0,1,2,3], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field="d", title="d"),
        ], source=source)

        text_input = TextInput(css_classes=["foo"])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(column(table, text_input))

        row = get_table_row(page.driver, 1)
        row.click()

        row = get_table_row(page.driver, 3)
        shift_click(page.driver, row)

        enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False)

        input_el = page.driver.find_element_by_css_selector('.foo')
        enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False)
        enter_text_in_element(page.driver, input_el, "")

        results = page.results

        # XXX (bev) these should be newlines with a TextAreaInput but TextAreaInput
        # is not working in tests for some reason presently
        assert results['value'] == '0\t1\t0\tfoo 1\t2\t1\tbar 2\t3\t2\tbaz'

        assert page.has_no_console_errors()
Exemplo n.º 5
0
def main(options, args):

    #logger = log.get_logger("ginga", options=options)
    logger = log.get_logger("ginga", level=20, log_file="/tmp/ginga.log")

    #TOOLS = "pan,wheel_zoom,box_select,tap"
    TOOLS = "box_select"

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0, 600],
                 y_range=[0, 600],
                 plot_width=600,
                 plot_height=600,
                 tools=TOOLS)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    bd = viewer.get_bindings()
    bd.enable_all(True)

    ## box_select_tool = fig.select(dict(type=BoxSelectTool))
    ## box_select_tool.select_every_mousemove = True
    #tap_tool = fig.select_one(TapTool).renderers = [cr]

    # open a session to keep our local document in sync with server
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 50)

    def load_file(path):
        image = load_data(path, logger=logger)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    def zoom_ctl_cb(attr_name, old_val, new_val):
        if new_val >= 0:
            new_val += 2
        viewer.zoom_to(int(new_val))
        scale = viewer.get_scale()
        logger.info("%f" % scale)
        viewer.onscreen_message("%f" % (scale), delay=0.3)

    # add a entry widget and configure with the call back
    #dstdir = options.indir
    dstdir = ""
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    slide = Slider(start=-20, end=20, step=1, value=1)
    slide.on_change('value', zoom_ctl_cb)

    layout = column(fig, path_w, slide)
    curdoc().add_root(layout)

    if len(args) > 0:
        load_file(args[0])
Exemplo n.º 6
0
def createFixedInputs_andBP():
    modelList = ["randomForest", "ols", "ridge", "elastic"]
    modelSelector = Select(title="Model",
                           options=modelList,
                           value='randomForest')
    ageSlider = Slider(title="Age",
                       value=inputDict['Age'],
                       start=0,
                       end=100,
                       step=1)
    sexSelector = Select(title="Sex",
                         options=['M', 'F'],
                         value=inputDict['Sex'])
    heightSlider = Slider(title="Height (inches)",
                          value=inputDict['Height'] / 2.54,
                          start=0,
                          end=90,
                          step=1)
    locationSelector = Select(title="Location",
                              options=['urban', 'rural'],
                              value='urban')

    medicalConditionList = [
        'noReport', 'ENT', 'OBGYN', 'Old_age_midLife_syndrome',
        'alcohol_poisoning', 'dermatological', 'digestive', 'endocrine',
        'heart', 'hematological', 'infectious_parasitic', 'injury',
        'muscular_rheumatological', 'neurological', 'noDiagnosis', 'other',
        'pyschiatric', 'respiratory', 'sexualDysfunction', 'tumor', 'unknown',
        'urinary'
    ]
    medicalConditionSelector = Select(title="Medical Condition",
                                      options=medicalConditionList,
                                      value='noReport')

    pregnantCheckbox = CheckboxGroup(labels=["Pregnant"], active=[])
    diabetesCheckbox = CheckboxGroup(labels=["Diabetes"], active=[])
    highBPCheckbox = CheckboxGroup(labels=["High blood pressure"], active=[])
    heart_attackCheckbox = CheckboxGroup(labels=["History of Heart attack"],
                                         active=[])
    internal_bleedingCheckbox = CheckboxGroup(
        labels=["History of internal bleeding"], active=[])

    systolText = TextInput(title="Systolic_BP(mmHg)                ",
                           value=str(130))
    diastolText = TextInput(title="Diastolic_BP(mmHg)               ",
                            value=str(80))

    fixedInputs_andBP_layout = column(modelSelector,
                                      Div(text='Background:',
                                          width=300,
                                          style={
                                              'font-size': '200%',
                                              'font-weight': 'bold',
                                              'color': 'black'
                                          }), ageSlider, sexSelector,
                                      heightSlider, locationSelector,
                                      medicalConditionSelector)  #,
    # pregnantCheckbox, diabetesCheckbox, highBPCheckbox, heart_attackCheckbox, internal_bleedingCheckbox, systolText, diastolText)

    return fixedInputs_andBP_layout, modelSelector, ageSlider, sexSelector, heightSlider, locationSelector, medicalConditionSelector, pregnantCheckbox, diabetesCheckbox, highBPCheckbox, heart_attackCheckbox, internal_bleedingCheckbox, systolText, diastolText
Exemplo n.º 7
0
    def run(self):

        self.widget_text_experiment_id = TextInput(value='170')
        self.widget_text_experiment_id.on_change('value', lambda a, o, n: self.update_experiment())
        self.widget_button_last_run = Button(label="Last run")
        self.widget_button_last_run.on_click(self.on_last_run)
        self.widget_text_experiment_id.on_change('value', lambda a, o, n: self.update_experiment())
        self.widget_epoch_select = Select(title='epoch', options=[])
        self.widget_button = Button(label="Read experiment")
        self.widget_button.on_click(self.update_experiment)
        self.widget_epoch_select.on_change('value', self.update_epoch)
        self.widget_pane = column()
        self.widget_loss_pane = column()
        self.widget_config_div = Div(text="")
        curdoc().add_root(
            column(
                row(
                    column(
                        row(Div(text="Experiment ID:"), self.widget_text_experiment_id, self.widget_button,
                            self.widget_button_last_run),
                        self.widget_loss_pane
                    ),
                    self.widget_config_div
                ),
                self.widget_epoch_select, self.widget_pane))
Exemplo n.º 8
0
    def test_single_row_copy_with_zero(self, bokeh_model_page) -> None:
        data = {'x': [1,2,3,4], 'y': [0,0,0,0], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field="d", title="d"),
        ], source=source)

        text_input = TextInput(css_classes=["foo"])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(column(table, text_input))

        row = get_table_row(page.driver, 2)
        row.click()

        enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False)

        input_el = page.driver.find_element_by_css_selector('.foo')
        enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False)
        enter_text_in_element(page.driver, input_el, "")

        sleep(0.5)
        results = page.results

        assert results['value'] == '1\t2\t0\tbar'

        assert page.has_no_console_errors()
Exemplo n.º 9
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            extractor=Select(
                title="Extractor:",
                value="",
                width=5,
                options=BokehFileViewer.extractor_product.values,
            ),
            extractor_window_start=TextInput(title="Window Start:", value=""),
            extractor_window_width=TextInput(title="Window Width:", value=""),
            extractor_window_shift=TextInput(title="Window Shift:", value=""),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=""),
        )

        for val in self.w_dl1_dict.values():
            val.on_change("value", self.on_dl1_widget_change)

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict["extractor"],
            self.w_dl1_dict["extractor_window_start"],
            self.w_dl1_dict["extractor_window_width"],
            self.w_dl1_dict["extractor_window_shift"],
            self.w_dl1_dict["extractor_lwt"],
        )
Exemplo n.º 10
0
    def test_js_on_change_executes(self, single_plot_page):
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
        plot.add_glyph(source, Circle(x='x', y='y', size=20))
        text_input = TextInput(css_classes=['foo'])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = single_plot_page(column(text_input, plot))

        el = page.driver.find_element_by_css_selector('.foo input')
        enter_text_in_element(page.driver, el, "val1")

        results = page.results
        assert results['value'] == 'val1'

        # double click to highlight and overwrite old text
        enter_text_in_element(page.driver, el, "val2", click=2)

        results = page.results
        assert results['value'] == 'val2'

        # Check clicking outside input also triggers
        enter_text_in_element(page.driver, el, "val3", click=2, enter=False)
        page.click_canvas_at_position(10, 10)
        results = page.results

        assert results['value'] == 'val3'

        assert page.has_no_console_errors()
Exemplo n.º 11
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            cleaner=Select(title="Cleaner:",
                           value='',
                           width=5,
                           options=BokehFileViewer.cleaner_product.values),
            extractor=Select(title="Extractor:",
                             value='',
                             width=5,
                             options=BokehFileViewer.extractor_product.values),
            extractor_t0=TextInput(title="T0:", value=''),
            extractor_window_width=TextInput(title="Window Width:", value=''),
            extractor_window_shift=TextInput(title="Window Shift:", value=''),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=''))

        for val in self.w_dl1_dict.values():
            val.on_change('value', self.on_dl1_widget_change)

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict['cleaner'], self.w_dl1_dict['extractor'],
            self.w_dl1_dict['extractor_t0'],
            self.w_dl1_dict['extractor_window_width'],
            self.w_dl1_dict['extractor_window_shift'],
            self.w_dl1_dict['extractor_lwt'])
Exemplo n.º 12
0
    def addtodoc(self, mainview, ctrl, *_):
        "sets-up the gui"
        self._widget = TextInput(placeholder=self._theme.placeholder,
                                 width=self._theme.width,
                                 height=self._theme.height,
                                 **self.__data())

        def _on_cb(attr, old, new):
            if not mainview.isactive():
                return

            try:
                val = float(new) if new.strip() else None
            except ValueError:
                self._widget.update(**self.__data())
                return

            instr = self._mdl.instrument
            cpy = self._config[instr]
            if cpy.precision == val:
                return

            cpy = copy(cpy)
            cpy.precision = val
            with ctrl.action:
                self._ctrl.theme.update(self._config, **{instr: cpy})

        self._widget.on_change("value", _on_cb)
        return [self._widget]
Exemplo n.º 13
0
    def test_js_on_change_executes(self,
                                   single_plot_page: SinglePlotPage) -> None:
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        plot = Plot(height=400,
                    width=400,
                    x_range=Range1d(0, 1),
                    y_range=Range1d(0, 1),
                    min_border=0)
        plot.add_glyph(source, Circle(x='x', y='y', size=20))
        text_input = TextInput()
        text_input.js_on_change('value',
                                CustomJS(code=RECORD("value", "cb_obj.value")))

        page = single_plot_page(column(text_input, plot))

        el = find_element_for(page.driver, text_input, "input")
        enter_text_in_element(page.driver, el, "val1")

        results = page.results
        assert results['value'] == 'val1'

        # double click to highlight and overwrite old text
        enter_text_in_element(page.driver, el, "val2", click=2)

        results = page.results
        assert results['value'] == 'val2'

        # Check clicking outside input also triggers
        enter_text_in_element(page.driver, el, "val3", click=2, enter=False)
        page.click_canvas_at_position(plot, 10, 10)
        results = page.results

        assert results['value'] == 'val3'

        assert page.has_no_console_errors()
Exemplo n.º 14
0
def main(options, args):

    #logger = log.get_logger("ginga", options=options)
    logger = log.get_logger("ginga", level=20, log_file="/tmp/ginga.log")

    #TOOLS = "pan,wheel_zoom,box_select,tap"
    TOOLS = "box_select"

    # create a new plot with default tools, using figure
    fig = figure(x_range=[0, 600], y_range=[0, 600],
                 plot_width=600, plot_height=600, tools=TOOLS)

    viewer = ib.CanvasView(logger)
    viewer.set_figure(fig)

    bd = viewer.get_bindings()
    bd.enable_all(True)

    ## box_select_tool = fig.select(dict(type=BoxSelectTool))
    ## box_select_tool.select_every_mousemove = True
    #tap_tool = fig.select_one(TapTool).renderers = [cr]

    # open a session to keep our local document in sync with server
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 50)

    def load_file(path):
        image = load_data(path, logger=logger)
        viewer.set_image(image)

    def load_file_cb(attr_name, old_val, new_val):
        #print(attr_name, old_val, new_val)
        load_file(new_val)

    def zoom_ctl_cb(attr_name, old_val, new_val):
        if new_val >= 0:
            new_val += 2
        viewer.zoom_to(int(new_val))
        scale = viewer.get_scale()
        logger.info("%f" % scale)
        viewer.onscreen_message("%f" % (scale), delay=0.3)

    # add a entry widget and configure with the call back
    #dstdir = options.indir
    dstdir = ""
    path_w = TextInput(value=dstdir, title="File:")
    path_w.on_change('value', load_file_cb)

    slide = Slider(start=-20, end=20, step=1, value=1)
    slide.on_change('value', zoom_ctl_cb)

    layout = column(fig, path_w, slide)
    curdoc().add_root(layout)

    if len(args) > 0:
        load_file(args[0])
Exemplo n.º 15
0
    def __init__(self, pvname, pvdef):

        self.pvname = pvname
        title = (pvname).split(':')[-1].replace('_',' ')+' ('+pvdef['unit']+')'
        value = str(pvdef['value'])
        self.unit = pvdef['unit']

        self.text_input = TextInput(value=value, title=title)
        self.text_input.on_change("value", self.set_pv)
Exemplo n.º 16
0
    def get_table_module(self):
        # https://stackoverflow.com/questions/54426404/bokeh-datatable-return-row-and-column-on-selection-callback
        self.record_cols = [
            *list(self.df.columns), 'exp', 'delete', 'his_pred',
            self.y_pred_name, 'index'
        ]
        self.record_table = pd.DataFrame(columns=self.record_cols)
        self.record_table_source = ColumnDataSource(
            self.record_table[['exp', 'delete']].to_dict(orient='list'))
        cols = [
            TableColumn(field="exp", title="Exp."),
            TableColumn(field="delete", title="Delete")
        ]
        data_table = DataTable(source=self.record_table_source,
                               columns=cols,
                               width=200,
                               height=800,
                               editable=True,
                               reorderable=False)
        test_cell = TextInput(value='kkk', title="Cell Contents:", width=200)
        test_count = TextInput(value='0', title="Cell Contents:", width=200)
        source_code = """
        var grid = document.getElementsByClassName('grid-canvas')[0].children;
        var row, column = '';

        for (var i = 0,max = grid.length; i < max; i++){
            if (grid[i].outerHTML.includes('active')){
                row = i;
                for (var j = 0, jmax = grid[i].children.length; j < jmax; j++)
                    if(grid[i].children[j].outerHTML.includes('active')) 
                        { column = j }
            }
        }
        test_cell.value = column == 1 ? String(source.data['exp'][row]) : String(source.data['delete'][row]);
        """
        callback = CustomJS(args=dict(source=self.record_table_source,
                                      test_cell=test_cell),
                            code=source_code)
        self.record_table_source.selected.js_on_change('indices', callback)
        self.record_table_source.selected.on_change(
            'indices', self.record_table_callback(test_cell, test_count))
        title = Div(text='Record',
                    sizing_mode="stretch_width",
                    style={
                        'font-size': '150%',
                        'color': self.txt_color
                    })
        record_button = Button(label="Take a snapshot",
                               button_type="success",
                               width_policy='fit',
                               width=150)
        record_button.on_click(self.record)
        self.table_panel.append(title)
        # self.table_panel.append(test_cell)
        self.table_panel.append(record_button)
        self.table_panel.append(data_table)
Exemplo n.º 17
0
 def __init__(self, doc=None):
     if doc is None:
         doc = curdoc()
     self.doc = doc
     self.file_name = None
     self.doc.title = "Rippled eBPF Probes"
     self.db_file_control = TextInput(value='', title='Db file:')
     self.db_file_control.on_change(
         'value', lambda attr, old, new: self._update_db())
     self.doc.add_root(layout([self.db_file_control]))
Exemplo n.º 18
0
 def __init__(self, file_name='probes.db'):
     self.file_name = None
     curdoc().title = "Rippled eBPF Probes"
     if file_name:
         self._update_db_file(file_name)
     else:
         self.db_file_control = TextInput(value='', title='Db file:')
         self.db_file_control.on_change(
             'value', lambda attr, old, new: self._update_db())
         curdoc().add_root(layout([self.db_file_control]))
Exemplo n.º 19
0
 def _init_set_marker(self):
     self.marker_button = Button(label=u"Set", button_type="default", width=80, height=31, disabled=True)
     self.event_code_input = TextInput(value="8", title="Event code:", width=80, disabled=True)
     self.event_code_input.on_change('value', self._check_marker_value)
     self.marker_button.on_click(self._set_marker)
     return column([Spacer(width=170, height=5),
                   row([self.event_code_input,
                       column(Spacer(width=50, height=19), self.marker_button)], height=50, width=170)],
                   width=170, height=50, sizing_mode='fixed'
                   )
Exemplo n.º 20
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Circle(x='x', y='y', size=20))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    text_input = TextInput(css_classes=["foo"])
    def cb(attr, old, new):
        source.data['val'] = [old, new]
    text_input.on_change('value', cb)
    doc.add_root(column(text_input, plot))
Exemplo n.º 21
0
def modify_doc(doc):
    source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
    plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
    plot.add_glyph(source, Circle(x='x', y='y', size=20))
    plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
    text_input = TextInput(css_classes=["foo"])
    def cb(attr, old, new):
        source.data['val'] = [old, new]
    text_input.on_change('value', cb)
    doc.add_root(column(text_input, plot))
Exemplo n.º 22
0
 def milestone_tab(self):
     self.milestone_subtitle = Div(text="Milestones & Major Accomplishments", css_classes=['subt-style'])
     self.milestone_inst = Div(text="Record any major milestones or accomplishments that occur throughout a night and the exposure numbers that correspond to it. If applicable, indicate the ID of exposures to ignore in a series.", css_classes=['inst-style'],width=1000)
     self.milestone_input = TextAreaInput(placeholder="Description", rows=10, cols=3, max_length=5000)
     self.milestone_exp_start = TextInput(title ='Exposure Start', placeholder='12345', value=None)
     self.milestone_exp_end = TextInput(title='Exposure End', placeholder='12345', value=None)
     self.milestone_exp_excl = TextInput(title='Excluded Exposures', placeholder='12346', value=None)
     self.milestone_btn = Button(label='Add Milestone', css_classes=['add_button'])
     self.milestone_alert = Div(text=' ', css_classes=['alert-style'])
     self.summary = TextAreaInput(rows=6, title='End of Night Summary',max_length=5000)
     self.summary_btn = Button(label='Add Summary', css_classes=['add_button'], width=300)
Exemplo n.º 23
0
 def create_label_text_inputs(self) -> list:
     label_text_inputs = []
     for i, category in enumerate(self.categories):
         title = "Label" if i == 0 else ""
         label_text_input = TextInput(value=category,
                                      title=title,
                                      width=100)
         label_text_input.on_change(
             "value", partial(self.handle_label_text_input_change, i))
         label_text_inputs.append(label_text_input)
     return label_text_inputs
Exemplo n.º 24
0
def create_panel(title, params, size=225):
    """
    return a Panel object containing a column layout of TextInput widgets for setting parameters
    """
    wlist = [widgetbox(Div(text='<center><strong>---' + title + '---</strong></center>'), width=size)]
    for param in params.keys():
        value = str(r0[title][param])
        text = TextInput(value=value, title=param)
        text.on_change('value', update_figs)
        wlist.append(widgetbox(text, width=size))
    return column(wlist)
Exemplo n.º 25
0
 def create_layout(self):
     self.widget_min_id = TextInput(title='Min Id', value='1957')
     self.widget_min_id.on_change('value',
                                  lambda a, o, n: self.update_by_input())
     self.widget_max_id = TextInput(title='Max Id', value='1970')
     self.widget_max_id.on_change('value',
                                  lambda a, o, n: self.update_by_input())
     self.widget_config_common = Div(text='')
     self.update_by_input()
     return column(row(self.widget_min_id, self.widget_max_id),
                   self.widget_config_common)
Exemplo n.º 26
0
 def create_label_inputs(self) -> column:
     inputs = []
     for i, label_item in enumerate(self.legend.items):
         value = self.read_item_label(i)
         disabled = value.startswith("$")
         label_input = TextInput(value=value, disabled=disabled, width=210)
         label_input.on_change("value",
                               partial(self.handle_label_item_change, i))
         inputs.append(label_input)
     title = Div(text="Labels")
     return column(title, *inputs)
Exemplo n.º 27
0
def create_panel(title, params, size=40):
    """
    return a Panel object containing a column layout of TextInput widgets for setting parameters
    """
    wlist = []
    for param in params.keys():
        value = str(r0[title][param])
        text = TextInput(value=value, title=param)
        text.on_change('value', update_figs)
        wlist.append(widgetbox(text, height=size))

    return Panel(child=column(wlist), title=title)
Exemplo n.º 28
0
class SacredRunsConfigAnalyzer(BokehComponent):
    _sacred_utils: SacredUtils
    _on_run_selected: Optional[Callable[[int], None]]

    def __init__(self,
                 sacred_config: SacredConfig,
                 on_run_selected: Optional[Callable[[int], None]],
                 min_id: int = 2258,
                 max_id: int = 2325):
        self._sacred_config = sacred_config
        self._on_run_selected = on_run_selected
        self._sacred_utils = SacredUtils(self._sacred_config)
        self._min_id = min_id
        self._max_id = max_id

    def _update_by_input(self):
        try:
            min_id = int(self.widget_min_id.value)
            max_id = int(self.widget_max_id.value)
            diff_result = self._sacred_utils.config_diff(
                list(range(min_id, max_id + 1)))
            formatted_config = diff_result.common_as_text('<br/>')
            df = diff_result.diff_as_df()
            self.ds_common.data = df
            self.widget_dt_common.columns = [
                TableColumn(field=c, title=c) for c in df.columns
            ]
            self.widget_config_common.text = f'<pre>{formatted_config} <hr/></pre>'
            # self.widget_config_common.text = f'<pre>{formatted_config} <hr/>{formatted_diff}</pre>'
        except Exception as e:
            print(f'Exception: {e}')

    def _on_table_click(self, p):
        run_ids = self.ds_common.data['run_ids'][p][0]
        if self._on_run_selected is not None:
            self._on_run_selected(run_ids[0])

    def create_layout(self):
        self.ds_common = ColumnDataSource({'a': [4]})
        self.ds_common.selected.on_change(
            'indices', lambda a, o, n: self._on_table_click(n))
        self.widget_min_id = TextInput(title='Min Id', value=str(self._min_id))
        self.widget_min_id.on_change('value',
                                     lambda a, o, n: self._update_by_input())
        self.widget_max_id = TextInput(title='Max Id', value=str(self._max_id))
        self.widget_max_id.on_change('value',
                                     lambda a, o, n: self._update_by_input())
        self.widget_config_common = Div(text='')
        self.widget_dt_common = DataTable(source=self.ds_common, width=1000)
        self._update_by_input()
        return column(row(self.widget_min_id, self.widget_max_id),
                      self.widget_config_common, self.widget_dt_common)
Exemplo n.º 29
0
class TextInputComponent(ComponentMixin):
    def __init__(self, text_input_kwargs):
        super().__init__()
        self.text_input = TextInput(**text_input_kwargs)
        self.layout = self.text_input
        self.input_text_callback = None

    def set_mediator(self, mediator):
        super().set_mediator(mediator)
        event_name = 'text-change'
        text_change = self.make_attr_old_new_callback(event_name)
        self.input_text_callback = text_change
        self.text_input.on_change('value', self.input_text_callback)
Exemplo n.º 30
0
 def _make_edit_widgets(self):
     delete_button = Button(label="-",
                            button_type="warning",
                            align=("start", "end"),
                            width=50)
     delete_button.on_click(self.delete_callback)
     return {
         "input_col": TextInput(title="Column", width=150),
         "input_val": TextInput(title="Value", width=100),
         "delete_button": delete_button,
         "value_row": row(align=("start", "end")),
         "value_buttons": {},
     }
Exemplo n.º 31
0
    def __init__(self):
        pd.set_option('display.max_colwidth', -1)

        try:
            self.base_df = load_clean_df()
        except:
            fpath = BUNDLED_DATA_DIR + '/clean-light.csv'
            self.base_df = load_clean_df(fpath=fpath)
        self.base_df[SEARCH_FIELD] = self.base_df.apply(lambda row: ' '.join(str(x).lower() for x in row[SEARCH_COLS] if pd.notnull(x)), axis=1)

        # divs holding the charts
        self.sim_input_desc_div = Div(text='', width=CHARTS_WIDTH)
        self.sim_input_div = Div(text='', width=CHARTS_WIDTH)
        self.hm_divs = [Div(text='', width=DIV_WIDTH) for _ in range(2)]
        self.hist_divs = [Div(text='', width=DIV_WIDTH) for _ in range(2)]
        self.bc_divs = [Div(text='', width=DIV_WIDTH) for _ in range(2)]
        self.comp_div = Div(text='', width=CHARTS_WIDTH)

        # other divs
        self.top_div = Div(text='', width=CHARTS_WIDTH)

        # controls
        self.search_text_ctrl = TextInput(title=None, value='', width=WIDGET_BOX_WIDTH - 50)

        self.sim_ctrl = Select(title=None, options=all_sims.get_sim_names(), value=all_sims.get_sim_name(TfidfCosSim))
        self.analysed_cols_ctrl = CheckboxGroup(labels=COL_OPTIONS, active=[COL_OPTIONS.index(c) for c in ['suff_qtext', 'type']])
        self.sim_params_ctrl = CheckboxGroup(labels=list(SIM_PARAMS_CHECKOPTS), active=list(range(len(SIM_PARAMS_CHECKOPTS))))
        self.wv_dict_model_ctrl = RadioGroup(labels=[e.name for e in qsim.W2vModelName], active=0)

        self.sim_input_nres_ctrl = Slider(title="Number of results", value=10, start=1, end=100, step=1)
        self.sim_input_sample_size_ctrl = Slider(title="Sample size", value=1000, start=100, end=len(self.base_df), step=100)
        self.sim_input_text_ctrl = TextInput(title=None, value='', width=WIDGET_BOX_WIDTH - 50)

        self.hm_sample_size_ctrl = Slider(title=SAMPLE_SIZE_LABEL, value=30, start=10, end=50, step=5)

        self.hist_sample_size_ctrl = Slider(title=SAMPLE_SIZE_LABEL, value=30, start=10, end=len(self.base_df), step=10)

        self.bc_sample_size_ctrl = Slider(title=SAMPLE_SIZE_LABEL, value=30, start=10, end=len(self.base_df), step=5)
        self.bc_bars_ctrl = Slider(title="Number of bars", value=10, start=5, end=25, step=1)

        self.spectrum_start_ctrl = Slider(title="from", value=0, start=0, end=1, step=0.01)
        self.spectrum_end_ctrl = Slider(title="to", value=1, start=0, end=1, step=0.01)
        self.spectrum_buckets_ctrl = Slider(title="Number of buckets", value=5, start=1, end=20, step=1)
        self.spectrum_bucket_size_ctrl = Slider(title="Questions per bucket", value=2, start=1, end=10, step=1)
        self.spectrum_cs_only_ctrl = CheckboxGroup(labels=['Cross survey pairs only'], active=[])
        self.spectrum_spectrum_sample_size_ctrl = Slider(title=SAMPLE_SIZE_LABEL, value=30, start=30, end=len(self.base_df), step=10)

        self.submit_btn = Button(label="Update", button_type="success")
        self.submit_btn.on_click(self.update)

        self.update()
Exemplo n.º 32
0
class SacredRunsConfigAnalyzer:
    def __init__(self, mongo_observer: MongoObserver):
        self._observer = mongo_observer

    def analyze_runs(
        self, run_ids: List[int]
    ) -> Tuple[Dict[str, Any], Dict[List[Tuple[str, Any]], List[int]]]:
        runs = self._observer.runs.find({'_id': {
            '$in': run_ids
        }}, {
            '_id': 1,
            'config': 1
        })
        items = list(runs)
        common_keys = find_common_keys(items, lambda x: x['config'])
        result = group_dicts(
            items, lambda x: dict_omit_keys(x['config'],
                                            set(common_keys) | {'seed'}),
            lambda x: x['_id'])
        return common_keys, result

    def update_by_input(self):
        try:
            min_id = int(self.widget_min_id.value)
            max_id = int(self.widget_max_id.value)
            common_keys, diff = self.analyze_runs(
                list(range(min_id, max_id + 1)))

            def join_dict(delimiter: str, data: Dict):
                return delimiter.join([f'{k}: {v}' for k, v in data.items()])

            formatted_config = join_dict('<br/>', common_keys)
            formatted_diff = '<br/>'.join([
                f'{join_dict(", ", tuple_to_dict(k))}: {v}'
                for k, v in diff.items()
            ])
            self.widget_config_common.text = f'<pre>{formatted_config} <hr/>{formatted_diff}</pre>'
        except Exception as e:
            print(f'Exception: {e}')

    def create_layout(self):
        self.widget_min_id = TextInput(title='Min Id', value='1957')
        self.widget_min_id.on_change('value',
                                     lambda a, o, n: self.update_by_input())
        self.widget_max_id = TextInput(title='Max Id', value='1970')
        self.widget_max_id.on_change('value',
                                     lambda a, o, n: self.update_by_input())
        self.widget_config_common = Div(text='')
        self.update_by_input()
        return column(row(self.widget_min_id, self.widget_max_id),
                      self.widget_config_common)
Exemplo n.º 33
0
    def __init__(self, data_x, data_y, name, p):
        self.name = name
        self.figure = p
        self.data_x = np.asarray(data_x)
        self.data_y = np.asarray(data_y)
        self.mani_data_x = self.data_x
        self.mani_data_y = self.data_y
        self.cds = ColumnDataSource(
            dict(x=self.mani_data_x, y=self.mani_data_y))

        self.y_scale = TextInput(value='1', title="Y scale")
        self.x_scale = TextInput(value='1', title="X scale")
        self.y_offset = TextInput(value='0', title="Y offset")
        self.x_offset = TextInput(value='0', title="X offset")

        self.y_scale.on_change('value', self._on_change)
        self.x_scale.on_change('value', self._on_change)
        self.y_offset.on_change('value', self._on_change)
        self.x_offset.on_change('value', self._on_change)

        rolling_num = len(self.data_x) // 10
        if rolling_num == 0:
            rolling_num = 1

        self.rolling_average = Slider(start=0,
                                      end=rolling_num,
                                      value=0,
                                      title='rolling average')
        self.rolling_average.on_change('value', self._on_change)

        self.plot_line()
        self.plot_line()
Exemplo n.º 34
0
def emission_lines(fname):
    def line_update(attr, old, new):
        # TODO: make it faster by finding a method to only modify the changed object
        z_list = [(1 + float(z.value)) for z in z_in_list]
        for i in range(len(line_list)):
            for j in range(len(line_list[i])):
                # j: jth line for ith element
                line_list[i][j].visible = True if not (checkboxes[i].active
                                                       == []) else False
                line_list[i][j].location = emission_lines[i][j] * z_list[i]

    # variables
    emission_lines = np.genfromtxt(fname,
                                   skip_header=1,
                                   delimiter=',',
                                   unpack=True)
    linename_list = np.loadtxt(fname,
                               delimiter=',',
                               unpack=True,
                               max_rows=1,
                               dtype='str')
    line_list = []  # line_list[i][j] for jth line in ith element
    checkboxes = []  # checkboxes[i] for ith element
    z_in_list = []  # z_in_list[i]  for ith element
    v_in_list = []  # v_in_list[i]  for ith element

    # generate widgets
    for i in range(len(emission_lines)):
        element = linename_list[i]
        print('Setting lines for ', element, '...')
        b_tmp = CheckboxGroup(labels=[element], active=[])
        b_tmp.on_change('active', line_update)
        checkboxes.append(b_tmp)
        #z_tmp = TextInput(value='2',title=element,sizing_mode='scale_width')
        z_tmp = TextInput(value='0', sizing_mode='scale_width')
        z_tmp.on_change('value', line_update)
        z_in_list.append(z_tmp)
        lines_for_this_element = []
        for j in range(len(emission_lines[i])):
            wavelength = emission_lines[i][j]
            if not np.isnan(wavelength):
                print('\t* lambda = ', emission_lines[i][j])
                line_tmp = Span(location=wavelength,
                                dimension='height',
                                line_color='orange',
                                line_width=1)  # TODO: line color
                lines_for_this_element.append(line_tmp)
        line_list.append(lines_for_this_element)
    line_update('', '', '')
    return line_list, z_in_list, checkboxes
Exemplo n.º 35
0
    def exp_tab(self):
        self.exp_subtitle = Div(text="Nightly Progress", css_classes=['subt-style'])
        self.exp_inst = Div(text="Throughout the night record the progress, including comments on Calibrations and Exposures. All exposures are recorded in the eLog, so only enter information that can provide additional information.", width=800, css_classes=['inst-style'])
        self.hdr_type = Select(title="Observation Type", value='Observation', options=self.header_options)
        self.hdr_btn = Button(label='Select', css_classes=['add_button'])

        self.add_image = TextInput(title="Add Image", placeholder='Pictures/image.png', value=None)

        self.exp_script = TextInput(title='Script Name', placeholder='dithering.json', value=None)
        self.exp_time_end = TextInput(title='Time End', placeholder='20:07', value=None)
        self.exp_focus_trim = TextInput(title='Trim from Focus', placeholder='54', value=None)
        self.exp_tile = TextInput(title='Tile Number', placeholder='68001', value=None)
        self.exp_tile_type = Select(title="Tile Type", value=None, options=['None','QSO','LRG','ELG','BGS','MW'])
        self.exp_input_layout = layout([])
Exemplo n.º 36
0
# slider controlling spatial stepsize of the solver
h_slider = Slider(title="spatial meshwidth", name='spatial meshwidth', value=pde_settings.h_init, start=pde_settings.h_min,
                  end=pde_settings.h_max, step=pde_settings.h_step)
h_slider.on_change('value', mesh_change)
# slider controlling spatial stepsize of the solver
k_slider = Slider(title="temporal meshwidth", name='temporal meshwidth', value=pde_settings.k_init, start=pde_settings.k_min,
                  end=pde_settings.k_max, step=pde_settings.k_step)
k_slider.on_change('value', mesh_change)
# radiobuttons controlling pde type
pde_type = RadioButtonGroup(labels=['Heat', 'Wave'], active=0)
pde_type.on_change('active', pde_type_change)
# radiobuttons controlling solver type
solver_type = RadioButtonGroup(labels=['Explicit', 'Implicit'], active=0)
solver_type.on_change('active', mesh_change)
# text input for IC
initial_condition = TextInput(value=pde_settings.IC_init, title="initial condition")
initial_condition.on_change('value', initial_condition_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,wheel_zoom,box_zoom"
# Generate a figure container
plot = Figure(plot_height=400,
              plot_width=400,
              tools=toolset,
              title="Time dependent PDEs",
              x_range=[pde_settings.x_min, pde_settings.x_max],
              y_range=[-1, 1]
              )

# Plot the numerical solution at time=t by the x,u values in the source property
plot.line('x', 'u', source=plot_data_num,
Exemplo n.º 37
0
        fun_lam = lambda *x: np.ones_like(x[0]) * float(fun_sym)
    else:
        fun_lam = lambdify(args, fun_sym, modules=['numpy'])

    return fun_lam

def string_to_function_parser(fun_str, args):
    fun_sym = sympify(fun_str)
    fun_lam = sym_to_function_parser(fun_sym, args)
    return fun_lam, fun_sym

# Data
line_source = ColumnDataSource(data=dict(x=[], y=[]))

# Controls
f_input = TextInput(value="sin(x)", title="f(x):")
derivative_input = Slider(title="n", value=1.0, start=0.0, end=5.0, step=1)

def fun_change(attrname, old, new):
    f_str = f_input.value
    f_fun, f_sym = string_to_function_parser(f_str, ['x'])
    print der.value
    df_sym = diff(f_sym, 'x', int(der.value))
    df_fun = sym_to_function_parser(df_sym,['x'])
    x = np.linspace(-5, 5, 100)
    y = f_fun(x)
    dy = df_fun(x)

    line_source.data = dict(x=x, y=y, dy=dy)

def init_data():
Exemplo n.º 38
0
# initialize properties
update_is_enabled = True

# initialize controls
# dropdown menu for sample functions
function_type = Dropdown(label="choose a sample function pair or enter one below",
                         menu=convolution_settings.sample_function_names)
function_type.on_click(function_pair_input_change)

# slider controlling the evaluated x value of the convolved function
x_value_input = Slider(title="x value", name='x value', value=convolution_settings.x_value_init,
                       start=convolution_settings.x_value_min, end=convolution_settings.x_value_max,
                       step=convolution_settings.x_value_step)
x_value_input.on_change('value', input_change)
# text input for the first function to be convolved
function1_input = TextInput(value=convolution_settings.function1_input_init, title="my first function:")
function1_input.on_change('value', input_change)
# text input for the second function to be convolved
function2_input = TextInput(value=convolution_settings.function1_input_init, title="my second function:")
function2_input.on_change('value', input_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Convolution of two functions",
              x_range=[convolution_settings.x_min_view, convolution_settings.x_max_view],
              y_range=[convolution_settings.y_min_view, convolution_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_function1, line_width=3, line_alpha=0.6, color='red', legend='function 1')
Exemplo n.º 39
0
    """
    size = int(sample_size.value) / 2
    if source_url.data == {}:
        source.data = random_roc_data(auc=float(auc.value)/100.0, size=size)
    else:
        source.data = source_url.data
        for w in [threshold, text, auc, sample_size]:
            w.disabled = True
    x, y = get_collide()
    point_source.data = dict(x=[x], y=[y])
    conf_source.data = conf_matrix()


source = ColumnDataSource(data=random_roc_data(size=200))

text = TextInput(title="title", name='title', value='ROC Curve')
sample_size = Slider(title="Sample Size (splits 50/50)", value=400, start=50, end=800, step=2)
threshold = Slider(title="Threshold", value=50.0, start=0.0, end=100.0, step=0.1)
auc = Slider(title="Area Under Curve (AUC)", value=70.0, start=0.0, end=100.0, step=0.1)
dataurl = TextInput(title="Data Url", name='data', value='DEMO')

# Generate a figure container
plot = Figure(title_text_font_size="12pt",
              plot_height=400,
              plot_width=400,
              tools="crosshair,pan,reset,resize,save,wheel_zoom",
              title=text.value,
              x_range=[0, 1],
              y_range=[0, 1])

# Plot the line by the x,y values in the source property
Exemplo n.º 40
0
]
p.add_layout(legend)

def update():
    try:
        expr = sy.sympify(text.value, dict(x=xs))
    except Exception as exception:
        errbox.text = str(exception)
    else:
        errbox.text = ""
    x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)

    p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
    legend.items[0].label = value("%s" % expr)
    legend.items[1].label = value("taylor(%s)" % expr)
    source.data = dict(x=x, fy=fy, ty=ty)

slider = Slider(start=1, end=20, value=1, step=1, title="Order")
slider.on_change('value', lambda attr, old, new: update())

text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', lambda attr, old, new: update())

errbox = PreText()

update()

inputs = column(text, slider, errbox, width=400)

curdoc().add_root(column(inputs, p))
Exemplo n.º 41
0
def on_query_sample_click():
    sample_name = indir+'query_example.txt'
    polysample =    '(47.625834810279436, -122.37593650817871)' + \
                    '(47.62566126823201, -122.3206615447998)'   + \
                    '(47.59400913793055, -122.32237815856934)'  + \
                    '(47.59441431361767, -122.3488998413086)'
    networkx_osm_ops.construct_poly_query(polysample, sample_name, 
                                          min_road_type='primary')
    os.system('open ' + sample_name)

button_query_sample.on_click(on_query_sample_click)
#############

#############
# Text input
text_poly = TextInput(value=poly_string, title="Polygon Coordinates:")
def on_text_value_change_poly(obj, attr, old, new):
    global poly_string
    print "New polygon coords:", new
    poly_string = new
    
text_poly.on_change('value', on_text_value_change_poly)
#############

#############
# define input directory
# Text input
text_input = TextInput(value=indir, title="Input Directory:")
def on_text_value_change_input(obj, attr, old, new):
    global indir
    print "Input Directory:", new
Exemplo n.º 42
0
plot.grid[0].grid_line_alpha = 0.0
plot.grid[1].grid_line_alpha = 0.0

# Plot the direction field
quiver = my_bokeh_utils.Quiver(plot)
# Plot initial values
plot.scatter('x0', 'y0', source=source_initialvalue, color='black', legend='(x0,y0)')
# Plot streamline
plot.line('x', 'y', source=source_streamline, color='black', legend='streamline')
# Plot critical points and lines
plot.scatter('x', 'y', source=source_critical_pts, color='red', legend='critical pts')
plot.multi_line('x_ls', 'y_ls', source=source_critical_lines, color='red', legend='critical lines')

# initialize controls
# text input for input of the ode system [u,v] = [x',y']
u_input = TextInput(value=odesystem_settings.sample_system_functions[odesystem_settings.init_fun_key][0], title="u(x,y):")
v_input = TextInput(value=odesystem_settings.sample_system_functions[odesystem_settings.init_fun_key][1], title="v(x,y):")

# dropdown menu for selecting one of the sample functions
sample_fun_input = Dropdown(label="choose a sample function pair or enter one below",
                            menu=odesystem_settings.sample_system_names)

# Interactor for entering starting point of initial condition
interactor = my_bokeh_utils.Interactor(plot)

# initialize callback behaviour
sample_fun_input.on_click(sample_fun_change)
u_input.on_change('value', ode_change)
v_input.on_change('value', ode_change)
interactor.on_click(initial_value_change)