Example #1
0
def create_panel(dynamic, static, title, size=60):
    """
    return a Panel object with title
    """

    # create a column layout of widgets for setting the dynamic parameters
    dlist = []
    for d in dynamic:

        value = r0[title][d]
        slider = widgetbox(Slider(title=d, value=value, start=0, end=10 * value), width=400, height=size)
        slider.children[0].on_change('value', update_figs)

        text = widgetbox(PreText(text='range:'), width=60, height=size)
        minus = widgetbox(Button(label='-'), width=size, height=size)
        plus = widgetbox(Button(label='+'), width=size, height=size)
        minus.children[0].on_click(update_sliders)
        plus.children[0].on_click(update_sliders)

        dlist.append(column(slider, row(minus, text, plus)))
    dcol = column(dlist)

    # create a column layout of TextInput widgets for setting the static parameters
    slist = []
    for s in static:

        value = str(r0[title][s])
        text = widgetbox(TextInput(value=value, title=s), height=size)
        text.children[0].on_change('value', update_figs)

        slist.append(text)
    scol = column(slist)

    return Panel(child=row(dcol, scol), title=title)
Example #2
0
    def compose_layout(self):
        """Compose the layout ot the app, the main elements are the widgets to
        select the dataset, the metric, a div for the title, a plot and a table
        """

        # Load metrics and datasets
        self.metrics = get_metrics(default='AM1')
        self.datasets = get_datasets(default='cfht')

        # Get args from the app URL or use defaults
        args = get_url_args(doc=curdoc,
                            defaults={'metric': self.metrics['default']})

        self.selected_dataset = args['ci_dataset']

        self.selected_metric = args['metric']

        # get specifications for the selected metric
        self.specs = get_specs(self.selected_metric)

        self.selected_window = args['window']

        # dataset select widget
        dataset_select = Select(title="Data Set:",
                                value=self.selected_dataset,
                                options=self.datasets['datasets'], width=100)

        dataset_select.on_change("value", self.on_dataset_change)

        # thresholds are used to make plot annotations
        self.configure_thresholds()

        # metric select widget
        metric_select = Select(title="Metric:", value=self.selected_metric,
                               options=self.metrics['metrics'], width=100)

        metric_select.on_change("value", self.on_metric_change)

        self.data = \
            get_meas_by_dataset_and_metric(self.selected_dataset,
                                           self.selected_metric,
                                           self.selected_window)

        self.update_data_source()
        self.make_plot()
        self.make_table()

        if len(self.data['values']) < 1:
            self.loading.text = "No data to display"
        else:
            self.loading.text = ""

        self.layout = column(row(widgetbox(metric_select, width=150),
                                 widgetbox(dataset_select, width=150)),
                             widgetbox(self.title, width=1000),
                             self.plot,
                             widgetbox(self.table_title, width=1000),
                             self.table)
Example #3
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)
Example #4
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            cleaner=Select(title="Cleaner:", value='', width=5,
                           options=WaveformCleanerFactory.subclass_names),
            extractor=Select(title="Extractor:", value='', width=5,
                             options=ChargeExtractorFactory.subclass_names),
            extractor_t0=TextInput(title="T0:", value=''),
            extractor_window_width=TextInput(title="Window Width:", value=''),
            extractor_window_shift=TextInput(title="Window Shift:", value=''),
            extractor_sig_amp_cut_HG=TextInput(title="Significant Amplitude "
                                                     "Cut (HG):", value=''),
            extractor_sig_amp_cut_LG=TextInput(title="Significant Amplitude "
                                                     "Cut (LG):", 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_sig_amp_cut_HG'],
            self.w_dl1_dict['extractor_sig_amp_cut_LG'],
            self.w_dl1_dict['extractor_lwt'])
Example #5
0
    def interactive_figure(self):
        """Add interactivity, ie. the option to show/hide lines to the figure."""

        lines = self.plot_figure()  # Generates a list of lines
        labels = [line for line in lines.keys()]  # Prepare a list of labels for the tickboxes
        lineNames = ['l'+str(x) for x in range(len(lines))]  # Prepare a list of names for the lines
        lines = {k: v for k, v in zip(lineNames, lines.values())}  # Create a dictionary {name: line}
        activeL = list(range(len(lines)))  # List of all line index to mark them as active in CheckboxGroup

        JScode = [self._visible_line_JS(k) for k in lines]  # Generate JavaScript for each line
        JScode = '\n'.join(JScode)  # From a list to a single string

        with open(osjoin(getcwd(), 'mLearning', 'JScodeAllLines.js'), 'r') as fileJS:
            buttonJS = fileJS.read()  # Read JavaScript code from a file to toggle the visibility of all lines
        # with open(osjoin(getcwd(), 'mLearning', 'JScode.js'), 'w+') as codeFile:
        #     codeFile.write(JScode)  # Write whole CustomJS to a file for debugging purposes

        callback = CustomJS(code=JScode, args={})  # Args will be added once checkbox and button are added to lines
        checkbox = CheckboxGroup(labels=labels,
                                 active=activeL,  # Labels to be ticked from the beginning
                                 callback=callback,
                                 name='checkbox')  # JavaScript var name

        buttonCallback = CustomJS(code=buttonJS, args={})  # Same as for callback
        button = Button(label="Select/Unselect All",  # Button HTML text
                        button_type="default",
                        callback=buttonCallback,
                        name='button')  # JavaScript var name

        lines['checkbox'], lines['button'] = checkbox, button  # Adding widget to lines
        callback.args, buttonCallback.args = lines, lines  # And then lines to callback
        layout = row(self.fig, widgetbox(children=[button, checkbox], width=200))  # One row, two columns

        logging.debug('Interaction implemented')
        return layout
Example #6
0
def general_plot(request):
    # List of tools to enable
    tools = "pan,reset,save,wheel_zoom,box_zoom"

    title = 'Generic Plotting'
    x = [10, 20, 30, 40, 50]
    y = [100, 200, 300, 400, 500]
    source = ColumnDataSource(data=dict(
        x=[1, 2, 3, 4, 5],
        y=[10, 20, 30, 40, 50],
        desc=['A', 'B', 'C', 'D', 'E']
    ))

    hover = HoverTool(tooltips=[
        ("index", "$index"),
        ("(x,y)", "($x,$y)"),
        ("desc", "@desc"),
    ])

    title = title

    jscode = """
        console.log("In callable");
        var data = source.data;
        x = data['x'];
        console.log(x)
        y = data['y'] * 0;
        source.change.emit();
        """

    jscode2 = """
        var urlstring = "http://127.0.0.1:8000/IWI/player/graphanalytics/?investment_id=zinc,year=1990"
        var data = zincData
        window.location = urlstring; 
    """

    callback = CustomJS(args=dict(source=source), code=jscode)
    callback2 = CustomJS(args=dict(source=source), code=jscode2)

    # Creating some of the wid  gets
    select_xaxis = Select(title="X-Axis:", value="foo", options=["foo", "bar", "baz", "quux"])
    select_yaxis = Select(title="Y-Axis:", value="foo", options=["foo", "bar", "baz", "quux"])
    button_plot = Button(label="Plot", callback=callback2)
    # button_plot.on_click(CustomJS(args=dict(source=source), code=jscode))

    widgets = widgetbox(select_xaxis, select_yaxis, button_plot, width=300)

    x_axis_label = select_xaxis.value
    y_axis_label = select_yaxis.value
    plot = figure(x_axis_label=x_axis_label, y_axis_label=y_axis_label, title=title, plot_width=400, plot_height=400,
                  tools=tools)
    plot.line('x', 'y', line_width=2, source=source, legend='Test')
    plot.add_tools(hover)

    graph_layout = layout([[plot], [widgets]])

    script, div = components(graph_layout)
    variables = {'script': script, 'div': div}

    return render(request=request, template_name='general_plot.html', context=variables)
Example #7
0
    def __init__(self, target):
        self.target = target[::-1]
        self.source1 = ColumnDataSource(data=dict(image=[self.target]))
        self.alpha = Slider(title="alpha", value=30,
                            start=10, end=50, step=1)
        self.sigma = Slider(title="sigma", value=3,
                            start=1, end=20, step=1)

        self.fig1 = self.define_figure('image')
        self.regist_image(self.fig1,self.source1)

        blurred = ndi.gaussian_filter(self.target, sigma=self.sigma.value)
        self.source2 = ColumnDataSource(data=dict(image=[blurred]))
        self.fig2 = self.define_figure('blurred')
        self.regist_image(self.fig2,self.source2)


        filtered = ndi.gaussian_filter(blurred, sigma=1)
        sharped = blurred+self.alpha.value*(blurred-filtered)
        sharped = sharped.astype(np.uint8)
        self.source3 = ColumnDataSource(data=dict(image=[sharped]))
        self.fig3 = self.define_figure('sharped')
        self.regist_image(self.fig3,self.source3)

        widget_list = [self.alpha, self.sigma]
        for widget in widget_list:
            widget.on_change('value', self.update_data)
        inputs = widgetbox(*[widget_list])
        self.plot = row(inputs, gridplot(
            [[self.fig1, self.fig2, self.fig3]]), width=600)
 def __init__(self, xs, ys):
     self.xs=xs
     self.ys=ys
     self.source = ColumnDataSource(data=dict(xs=xs, ys=ys))
     self.fig = figure(title='sin function',
                       x_range=[min(xs), max(ys)],
                       y_range=[min(ys), max(ys)])
     self.fig.line('xs', 'ys', source=self.source)
     self.text = TextInput(title='Title',
                           value='sin function')
     self.offset = Slider(title="offset", value=0.0,
                          start=-5.0, end=5.0, step=0.1)
     self.amplitude = Slider(title="amplitude", value=1.0,
                             start=-5.0, end=5.0, step=0.1)
     self.phase = Slider(title="phase", value=0.0,
                         start=0.0, end=2*np.pi, step=0.1)
     self.freq = Slider(title="frequency", value=1.0,
                        start=0.1, end=5.1, step=0.1)
     
     widget_list = [self.text, self.offset,
                    self.amplitude, self.phase, self.freq]
     for widget in widget_list:
         if widget!=self.text:
             widget.on_change('value', self.update_data)
         else:
             widget.on_change('value', self.update_title)
     inputs=widgetbox(*[widget_list])
     self.plot=row(inputs,self.fig,width=800)
Example #9
0
    def __init__(self):
        N = 11
        self.N = N
        xs = np.linspace(-np.pi, np.pi, N)
        ys = xs
        Xs, Ys = np.meshgrid(xs, ys)
        self.Xs, self.Ys = Xs.flatten(), Ys.flatten()
        a, b = 1, 0
        c, d = 0, 1
        mat = matrix(a, b, c, d)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])

        TOOLS = "pan,save,reset"
        self.dic_xs = {"Xs{}".format(step): self.Xs[N*step:N*(step+1)]
                       for step in range(N)}
        self.dic_ys = {"Ys{}".format(step): self.Ys[N*step:N*(step+1)]
                       for step in range(N)}
        dic_trasn_xs = {"transXs{}".format(
            step): transXs[N*step:N*(step+1)] for step in range(N)}
        dic_trans_ys = {"transYs{}".format(
            step): transYs[N*step:N*(step+1)] for step in range(N)}
        data = {**self.dic_xs, **self.dic_ys, **dic_trasn_xs, **dic_trans_ys}
        colors = Category20[11]
        self.source = ColumnDataSource(data=data)
        self.fig = figure(tools=TOOLS, title="target",
                          x_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1),
                          y_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1))
        for s in range(N):
            eval("""self.fig.scatter('Xs{0}', 'Ys{0}', 
                                     source=self.source, 
                                     color=colors[{0}])""".format(s))

        self.transfig = figure(tools=TOOLS, title="transformed",
                               x_range=self.fig.x_range,
                               y_range=self.fig.y_range)
        for s in range(N):
            eval("""self.transfig.scatter('transXs{0}', 'transYs{0}', 
                                          source=self.source, 
                                          color=colors[{0}])""".format(s))

        self.a_slider = Slider(title="a", value=a,
                               start=-10, end=10, step=0.1)
        self.b_slider = Slider(title="b", value=b,
                               start=-10, end=10, step=0.1)
        self.c_slider = Slider(title="c", value=c,
                               start=-10, end=10, step=0.1)
        self.d_slider = Slider(title="d", value=d,
                               start=-10, end=10, step=0.1)

        for widget in [self.a_slider, self.b_slider,
                       self.c_slider, self.d_slider]:
            widget.on_change('value', self.update_data)
        box = widgetbox([self.a_slider, self.b_slider,
                         self.c_slider, self.d_slider])
        self.plot = column(gridplot([[self.a_slider, self.b_slider],
                                     [self.c_slider, self.d_slider]]),
                           gridplot([[self.fig, self.transfig]]))
Example #10
0
def button_print_page():
    """Button to print currently displayed webpage to paper or pdf.

    Notes
    -----
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Print this page", button_type="success")
    button.callback = CustomJS(code="""print()""")
    return widgetbox(button)
    def main(self):
        controls = [self.game_thresh, self.select_team]
        for control in controls:
            control.on_change('value', lambda attr, old, new: self.update())

        sizing_mode = 'fixed'  # 'scale_width' also looks nice with this example
        inputs = widgetbox(*controls, sizing_mode=sizing_mode)
        l1 = layout([[self.sample_text],[inputs],[self.p2]], sizing_mode=sizing_mode)
        self.update()  # initial load of the data
        return l1
Example #12
0
    def __init__(self, worker, **kwargs):
        with log_errors():
            self.worker = worker

            names = ['nbytes', 'duration', 'bandwidth', 'count', 'type',
                     'inout-color', 'type-color', 'key', 'key-color', 'start',
                     'stop']
            quantities = ['nbytes', 'duration', 'bandwidth', 'count',
                          'start', 'stop']
            colors = ['inout-color', 'type-color', 'key-color']

            # self.source = ColumnDataSource({name: [] for name in names})
            self.source = ColumnDataSource({
                'nbytes': [1, 2],
                'duration': [0.01, 0.02],
                'bandwidth': [0.01, 0.02],
                'count': [1, 2],
                'type': ['int', 'str'],
                'inout-color': ['blue', 'red'],
                'type-color': ['blue', 'red'],
                'key': ['add', 'inc'],
                'start': [1, 2],
                'stop': [1, 2]
                })

            self.x = Select(title='X-Axis', value='nbytes', options=quantities)
            self.x.on_change('value', self.update_figure)

            self.y = Select(title='Y-Axis', value='bandwidth', options=quantities)
            self.y.on_change('value', self.update_figure)

            self.size = Select(title='Size', value='None',
                               options=['None'] + quantities)
            self.size.on_change('value', self.update_figure)

            self.color = Select(title='Color', value='inout-color',
                                options=['black'] + colors)
            self.color.on_change('value', self.update_figure)

            if 'sizing_mode' in kwargs:
                kw = {'sizing_mode': kwargs['sizing_mode']}
            else:
                kw = {}

            self.control = widgetbox([self.x, self.y, self.size, self.color],
                                     width=200, **kw)

            self.last_outgoing = 0
            self.last_incoming = 0
            self.kwargs = kwargs

            self.layout = row(self.control, self.create_figure(**self.kwargs),
                              **kw)

            self.root = self.layout
Example #13
0
def data_retrieval():


    conn = lite.connect('/Users/shanekenny/PycharmProjects/WiFinder/app/website/WiFinderDBv02.db')
    with conn:
        datetime = "2015-11-12"
        df = pd.read_sql_query("SELECT W.Log_Count, W.Time, W.Hour, W.Datetime, R.RoomID, R.Capacity, C.ClassID, C.Module, C.Reg_Students, O.Occupancy, O.OccID FROM WIFI_LOGS W JOIN CLASS C ON W.ClassID = C.ClassID JOIN ROOM R ON C.Room = R.RoomID JOIN OCCUPANCY O ON C.ClassID = O.ClassID WHERE R.RoomID = 'B002' AND W.Datetime =\'{}\' GROUP BY W.LogID;".format(datetime), conn)
        # p = figure(width=800, height=250, x_axis_type="datetime")
        # p.line = Line(df, title="WIfi Logs", ylabel='Count', xlabel='Time',index='W.Datetime', legend=True)

        df['Time'] = df['Time'].apply(pd.to_datetime)
        p = figure(width=800, height=250, x_axis_type="datetime", )
        p.extra_y_ranges = {"foo": Range1d(start=0, end=1)}

        p.line(df['Time'], df['Log_Count'],  color='red',legend='Log Count')
        p.line(df['Time'], df['Reg_Students'], color='green',legend='Registered Students')
        p.line(df['Time'], df['Capacity'], color='blue', legend='Capacity')
        p.line(df['Time'], df['Occupancy']*100, color='orange', legend='Occupancy')

        p.add_layout(LinearAxis(y_range_name="foo"), 'left')

        # picker_start = "2015-11-03"
        # picker_end = '2015-11-13'
        # slider = DatePicker(title="Date:", min_date=picker_start, max_date=picker_end, value=picker_start)
        slider = Slider(start=0, end=10, value=1, step=.1, title="Stuff")

        controls = [slider]


        sizing_mode = 'fixed'
        inputs = widgetbox(*controls, sizing_mode=sizing_mode)

        layoutss = widgetbox(slider)

        r = layout([[p, layoutss]], sizing_mode='stretch_both')


        script, div = components(r)

        return flask.render_template('explore.html', script=script,
                                     div=div,
                                     )
Example #14
0
 def init_layout(self):
     widgets = [widget for d in self.widgets.values()
                for widget in d if widget]
     wbox = widgetbox(widgets, width=self.width)
     if self.position in ['right', 'below']:
         plots = [self.plot.state, wbox]
     else:
         plots = [wbox, self.plot.state]
     layout_fn = row if self.position in ['left', 'right'] else column
     layout = layout_fn(plots, sizing_mode=self.sizing_mode)
     return layout
Example #15
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)
Example #16
0
    def __init__(self):
        xs = np.linspace(-np.pi, np.pi, 11)
        ys = xs
        Xs, Ys = np.meshgrid(xs, ys)
        self.Xs, self.Ys = Xs.flatten(), Ys.flatten()
        a, b = 1, 0
        c, d = 0, 1
        mat = matrix(a, b, c, d)
        transXs, transYs = mat @ np.array([self.Xs, self.Ys])

        TOOLS = "pan,lasso_select,save,reset"
        self.source = ColumnDataSource(data=dict(Xs=self.Xs, Ys=self.Ys,
                                                 transXs=transXs, transYs=transYs))
        self.evectors = ColumnDataSource(data=dict(ev0x=[0, 0], ev0y=[0, 1],
                                                   ev1x=[0, 1], ev1y=[0, 0],
                                                   transev0x=[0, 0], transev0y=[0, 1],
                                                   transev1x=[0, 1], transev1y=[0, 0]))

        self.fig = figure(tools=TOOLS, title="target",
                          x_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1),
                          y_range=(-np.pi*np.sqrt(2)-1, np.pi*np.sqrt(2)+1))
        self.fig.scatter('Xs', 'Ys', source=self.source)
        self.fig.line('ev0x', 'ev0y', source=self.evectors,
                      line_width=5, line_alpha=0.5, color='red')
        self.fig.line('ev1x', 'ev1y', source=self.evectors,
                      line_width=5, line_alpha=0.5, color='blue')
        self.transfig = figure(tools=TOOLS, title="transformed",
                               x_range=self.fig.x_range, y_range=self.fig.y_range)
        self.transfig.circle('transXs', 'transYs', source=self.source)
        self.transfig.line('transev0x', 'transev0y', source=self.evectors,
                           line_width=5, line_alpha=0.5, color='red')
        self.transfig.line('transev1x', 'transev1y', source=self.evectors,
                           line_width=5, line_alpha=0.5, color='blue')
        self.a_slider = Slider(title="a", value=a,
                               start=-10, end=10, step=0.1)
        self.b_slider = Slider(title="b", value=b,
                               start=-10, end=10, step=0.1)
        self.c_slider = Slider(title="c", value=c,
                               start=-10, end=10, step=0.1)
        self.d_slider = Slider(title="d", value=d,
                               start=-10, end=10, step=0.1)
        self.eigen0 = Div(text="eigen0")
        self.eigen1 = Div(text="eigen1")
        for widget in [self.a_slider, self.b_slider, self.c_slider, self.d_slider]:
            widget.on_change('value', self.update_data)
        box = widgetbox([self.a_slider, self.b_slider,
                         self.c_slider, self.d_slider])
        self.plot = column(gridplot([[self.a_slider, self.b_slider, self.eigen0],
                                     [self.c_slider, self.d_slider, self.eigen1]]),
                           gridplot([[self.fig, self.transfig]]))
Example #17
0
def button_save_table(table):
    """Button to save selected data table as csv.

    Notes
    -----
    * Does not work for column values containing tuples (like 'neighbors')
    * Currently columns being saved are hard coded in the javascript callback
    * Available styles: 'default', 'primary', 'success', 'warning', 'danger'
    """
    button = Button(label="Download selected data", button_type="success")
    button.callback = CustomJS(args=dict(source=table.source),
                               code=open(join(dirname(__file__),
                                              "js/download_data.js")).read())
    return widgetbox(button)
Example #18
0
File: plot.py Project: jni/prin
def serve(datasource):
    columns = list(datasource.keys())
    positive_vars = [k for k in columns if np.all(datasource[k] > 0)]
    x = Select(title='X-Axis', value='in_degree',
               options=columns)
    y = Select(title='Y-Axis', value='pagerank',
               options=columns)
    size = Select(title='Size', value='None',
                  options=['None'] + positive_vars)
    color = Select(title='Color', value='None',
                    options=['None'] + columns)
    controls = layouts.widgetbox([x, y, color, size], width=200)
    plot = bokeh_plot(datasource)
    document = layouts.row(controls, plot)
Example #19
0
def run(doc):

    fig = figure(title='random data', width=400, height=200, tools='pan,box_zoom,reset,save')

    source = ColumnDataSource(data={'x': [], 'y': []})
    fig.line('x', 'y', source=source)

    def click(n=100):
        source.data = {'x': range(n), 'y': random(n)}

    button = Button(label='update', button_type='success')
    button.on_click(click)

    layout = column(widgetbox(button), fig)
    doc.add_root(layout)
    click()
Example #20
0
def modify_doc(doc):
    x = np.linspace(0, 10, 1000)
    y = np.log(x) * np.sin(x)

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

    plot = figure(title="Simple plot with slider")
    plot.line('x', 'y', source=source)

    slider = Slider(start=1, end=10, value=1, step=0.1)

    def callback(attr, old, new):
        y = np.log(x) * np.sin(x*new)
        source.data = dict(x=x, y=y)
    slider.on_change('value', callback)

    doc.add_root(row(widgetbox(slider), plot))
Example #21
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'])
Example #22
0
    def __init__(self, node_id, dtype, sensor_names, dates):
        """
        :param node_id: str
        :param dtype: str
        :param sensor_names: [str]
        :param dates: str

        DataSet class. This class contains all the data for node and sensor type. node_id is the nodes unique id, dtype is the string
        data type for the node (e.g. 'Temperature', sensor names is the list of sensors with that data type, and date is the date of
        the data in YYYY-MM-DD format.
        """
        self.id = node_id
        self.dtype = dtype
        self.sensor_names = sensor_names
        self.dates = dates
        self.sources = {}
        self.used_sources = {}
        self.null_sources = {}
        self.cbg = CheckboxButtonGroup(labels=self.sensor_names, active=[i for i in range(len(self.sensor_names))])
        self.wb = widgetbox(self.cbg, width=600)
        self.plot = figure(title=self.dtype + ' data from node ' + self.id,
                           x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,save,box_select")
Example #23
0
    def main(self, org="H"):
        controls = [self.min_percentile, self.max_percentile, self.select_team, self.game_equivalent]
        for control in controls:
            control.on_change('value', lambda attr, old, new: self.update())

        sizing_mode = 'fixed'  # 'scale_width' also looks nice with this example

        inputs = widgetbox(*controls, sizing_mode=sizing_mode)
        if org== "H":
            l1 = layout([
            [inputs],
            [self.textbox],
            [self.p1, self.p2],
            ], sizing_mode=sizing_mode)

        else:
            l1 = layout([
            [inputs],
            [self.textbox],
            [self.p1], 
            [self.p2],
            ], sizing_mode=sizing_mode)
        self.update()  # initial load of the data
        return l1
Example #24
0
    def intro_tab(self):

        """Intro tab - explains the application"""

        html = ("<h1>UT330 UI</h1>"
                "<p>"
                "This UI controls a UT330 device from any operating "
                "system. It displays the temperature and humidity from "
                "pre-existing data files downloaded from a UT330 and it "
                "enables new data files to be read from a UT330 device "
                "connected to the computer. For full details of how the "
                "software works (and for licensing), read the "
                "<a href='https://github.com/MikeWoodward/UT330B'>"
                "Github page</a>."
                "</p>"
                "<p>"
                "Mike Woodward, 2017"
                "</p>")

        intro_text = Div(text=html,
                         width=self.page_width,
                         height=self.page_height)

        return Panel(child=widgetbox(intro_text), title="UT330 UI")
Example #25
0
groupby_select.on_change('active', lambda attr, old, new: update_plot())


animal_trials = ColumnDataSource()
animal_trials_plot = figure(title='number of trials', tools="", width=1000,
                             height=150)
animal_trials_plot.xaxis.axis_label = 'Session'
animal_trials_plot.yaxis.axis_label = 'Number of trials'
animal_trials_plot.line('session', 'trials', source=animal_trials)

animal_fa = ColumnDataSource()
animal_fa_plot = figure(title='False alarm rate', tools="", width=1000,
                        height=150, y_range=(0, 1))
animal_fa_plot.xaxis.axis_label = 'Session'
animal_fa_plot.yaxis.axis_label = 'FA rate'
animal_fa_plot.line('session', 'fa', source=animal_fa)


page_layout = layout(
    animal_select,
    animal_trials_plot,
    animal_fa_plot,
    [widgetbox(date_select, groupby_select), create_plot()],
)

# Run the updaters to initialize everything
animal_changed()
update_plot()

curdoc().add_root(page_layout)
Example #26
0
xmenu = []
for param in r0.keys():
    for item in r0[param]:
        xmenu.append((item, item))
    xmenu.append(None)
xdrop = Dropdown(menu=xmenu[:-1], button_type='primary')
xdrop.on_change('value', update_xdrop)

# create the Panel and Tabs objects for setting up the investment parameters
panels = []
for param in r0.keys():
    panels.append(create_panel(param, r0[param]))
tabs = Tabs(tabs=panels, width=1000)

# create the app layout
top = row(fig, widgetbox(xdrop, width=300))
layout = column(top, tabs)

# update the document and initialize the app by setting the Dropdown value
curdoc().add_root(layout)
param0 = list(r0.keys())[0]
xdrop.value = list(r0[param0].keys())[0]








                hover_line_color='red')

plot.legend.location = 'top_right'

year_slider = Slider(start=2000, end=2018, value=2000, step=1, title="Year")


def callback(attr, old, new):
    new_yr = new
    new1 = {
        'x': tr_plot[tr_plot['Year'] == new_yr].Age,
        'y': tr_plot[tr_plot['Year'] == new_yr].Transfer_fee,
        'position': tr_plot[tr_plot['Year'] == new_yr].Position,
        'league_from': tr_plot[tr_plot['Year'] == new_yr].League_from,
        'league_to': tr_plot[tr_plot['Year'] == new_yr].League_to,
        'name': tr_plot[tr_plot['Year'] == new_yr].Name,
        'team_to': tr_plot[tr_plot['Year'] == new_yr].Team_to,
        'team_from': tr_plot[tr_plot['Year'] == new_yr].Team_from,
        'transfer_fee_M': tr_plot[tr_plot['Year'] == new_yr].transfer_fee_M
    }
    source.data = new1


year_slider.on_change('value', callback)

layout = column(widgetbox(year_slider), plot)

curdoc().add_root(layout)

#output_file('Transfer.html')
show(layout)
Example #28
0
p4.circle('ra', 'pmdec', source=hy_dr2_res, color='red')

p_zvra = figure(plot_height=300, plot_width=300)
p_zvra.xaxis.axis_label = 'z'
p_zvra.yaxis.axis_label = 'vra'
p_zvra.circle('z', 'vra', source=source)
p_zvra.circle('z', 'dvra', source=hy_dr2_res, color='red')

p_zvdec = figure(plot_height=300, plot_width=300)
p_zvdec.xaxis.axis_label = 'z'
p_zvdec.yaxis.axis_label = 'vdec'
p_zvdec.circle('z', 'vdec', source=source)
p_zvdec.circle('z', 'dvdec', source=hy_dr2_res, color='red')

p_xvra = figure(plot_height=300, plot_width=300)
p_xvra.xaxis.axis_label = 'x'
p_xvra.yaxis.axis_label = 'vra'
p_xvra.circle('x', 'vra', source=source)
p_xvra.circle('x', 'dvra', source=hy_dr2_res, color='red')

p_xvdec = figure(plot_height=300, plot_width=300)
p_xvdec.xaxis.axis_label = 'x'
p_xvdec.yaxis.axis_label = 'vdec'
p_xvdec.circle('x', 'vdec', source=source)
p_xvdec.circle('x', 'dvdec', source=hy_dr2_res, color='red')

inputs = widgetbox(vx, vy, vz, sigmav, omegax, omegay, omegaz, w1, w2, w3, w4,
                   w5)
curdoc().add_root(
    row(inputs, gridplot([[p, p_pm], [p_zvra, p_zvdec], [p_xvra, p_xvdec]])))
    data = data['data']
    df = pd.DataFrame(data)
    df.columns = [
        'Ticker', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Dividend',
        'Split_Ratio', 'Adj_Open', 'Adj_High', 'Adj_Low', 'Adj_Close',
        'Adj_Volume'
    ]

    dates = pd.DataFrame(data).iloc[:, 1]
    dates = pd.to_datetime(dates)
    temp = pd.DataFrame(data, index=dates)
    temp = temp.iloc[:, [1, 5]]
    temp.columns = ['Date', 'Close']

    new_idx = pd.date_range(prev_date, curr_date, freq='D')
    temp2 = temp.reindex(new_idx)

    source.data = dict(x1=pd.to_datetime(temp['Date']), y1=temp['Close'][:])
    source2.data = dict(x2=pd.to_datetime(new_idx), y2=temp2['Close'][:])


for w in [ticker_text, date_text]:
    w.on_change('value', update_data)

temporal_button.on_change('active', update_data)

# Set up layouts and add to document
inputs = widgetbox(ticker_text, date_text, temporal_button)

curdoc().add_root(row(inputs, p, width=800))
curdoc().title = "Closing Prices"
Example #30
0
def colorbar_slider(fig):
    '''
    Adds interactive sliders and text input boxes for the colorbar.
    Returns a layout object to be put into a gridplot
    '''
    cb = get_colorbar_renderer(fig)
    data = get_image_data(fig)
    data = reject_outliers_quick(data)
    datamin = nanmin(data)
    datamax = nanmax(data)
    im = get_glyph_renderer(fig)  # Get image renderer

    from bokeh.models import CustomJS, Slider, TextInput
    from bokeh.models.widgets import Button
    from bokeh.layouts import widgetbox

    model = Slider()  # trick it into letting datamin and datamax into CustomJS
    model.tags.append(datamin)  # Hide these in here
    model.tags.append(datamax)

    callback_u = CustomJS(args=dict(cb=cb, im=im, model=model),
                          code="""
        var cm = cb.color_mapper;
        var upp = upper_slider.get('value');
        upper_input.value = upp.toString()
        lower_slider.end = upp
        cm.high = upp;
        im.glyph.color_mapper.high = upp;
        if (cm.low >= cm.high){
        cm.low = upp/1.1 // to prevent limits being the same
        im.glyph.color_mapper.low = low/1.1;
        }
        if (upp > model.tags[1]){
            upper_slider.end = upp
        }
        """)

    callback_l = CustomJS(args=dict(cb=cb, im=im, model=model),
                          code="""
        var cm = cb.color_mapper;
        var low = lower_slider.get('value');
        lower_input.value = low.toString()
        upper_slider.start = low
        cm.low = low;
        im.glyph.color_mapper.low = low;
        if (cm.high <=  cm.low){
        cm.high = low*1.1 // to prevent limits being the same
        im.glyph.color_mapper.high = low*1.1;
        }
        if (low < model.tags[0]){
            lower_slider.start = low
        }""")

    callback_ut = CustomJS(args=dict(cb=cb, im=im, model=model),
                           code="""
        var cm = cb.color_mapper;
        var upp = parseFloat(upper_input.get('value'));
        upper_slider.value = upp
        cm.high = upp;
        im.glyph.color_mapper.high = upp;
        if (cm.low >=  cm.high){
        cm.low = upp/1.1 // to prevent limits being the same
        im.glyph.color_mapper.low = upp/1.1;
        }
        if (upp > model.tags[1]){
            upper_slider.end = upp
        }
        """)

    callback_lt = CustomJS(args=dict(cb=cb, im=im, model=model),
                           code="""
        var cm = cb.color_mapper;
        var low = parseFloat(lower_input.get('value'));
        lower_slider.value = low
        cm.low = low;
        im.glyph.color_mapper.low = low;
        if (cm.high <=  cm.low){
        cm.high = low*1.1 // to prevent limits being the same
        im.glyph.color_mapper.high = low*1.1;
        }
        if (low < model.tags[0]){
            lower_slider.start = low
        }
        """)

    callback_reset_js = CustomJS(args=dict(cb=cb, im=im, model=model),
                                 code="""
        var cm = cb.color_mapper;
        var low = model.tags[0];
        var high = model.tags[1];
        low = parseFloat(low.toPrecision(3)) // 3 sig figs
        high = parseFloat(high.toPrecision(3)) // 3 sig figs
        lower_slider.value = low;
        lower_slider.set('step', (high-low)/50);
        cm.low = low;
        upper_slider.value = high;
        upper_slider.set('step', (high-low)/50);
        cm.high = high;
        im.glyph.color_mapper.low = low;
        im.glyph.color_mapper.high = high;
        lower_input.value = low.toString();
        upper_input.value = high.toString();
        lower_slider.start = low;
        lower_slider.end = high;
        upper_slider.start = low;
        upper_slider.end = high;
        model.trigger('change')
        cb_obj.trigger('change)')
    """)

    reset_button = Button(label='Reset', callback=callback_reset_js)

    def callback_reset(*args, **kwargs):
        from IPython.display import Javascript, display

        # display(callback_reset_js)
        # callback_reset_js.name = None
        # callback_reset_js.name = 'test'
        # display('Plot updated, press reset to rescale!')
        # cb.color_mapper.low = datamin
        # cb.color_mapper.high = datamax
        # im.glyph.color_mapper.low = datamin
        # im.glyph.color_mapper.high = datamax
        # lower_slider.start = datamin
        # lower_slider.end = datamax
        # lower_slider.value = datamin
        # upper_slider.start = datamin
        # upper_slider.end = datamax
        # lower_slider.value = datamax
        # lower_input.value = str(datamin)
        # upper_input.value = str(datamax)
        # update()
        # fig.text(x=0,y=0,text='Plot updated, press reset to rescale!')
        # reset_button.label='Reset: Data changed! Press me!'

    # reset_button.trigger('clicks',0,1)
    reset_button.on_click(callback_reset)

    # def callback_die(attr, old, new):
    #     from IPython.display import display
    #     display('yoooo')
    #     display(old)
    #     display(new)
    #     raise Exception()
    # exception_button = Button(label='KILL ME')
    # exception_button.on_click(callback_die)

    lower_slider = Slider(
        start=datamin,
        end=datamax,
        value=datamin,
        step=(datamax - datamin) / 50,  # smallest step is 1e-5
        title="Lower lim",
        callback=callback_l)
    lower_slider.width = 100

    upper_slider = Slider(start=datamin,
                          end=datamax,
                          value=datamax,
                          step=(datamax - datamin) / 50,
                          title="Upper lim",
                          callback=callback_u)
    upper_slider.width = 100

    lower_input = TextInput(callback=callback_lt, value=str(datamin), width=50)
    upper_input = TextInput(callback=callback_ut, value=str(datamax), width=50)

    # add all of these widgets as arguments to the callback functions
    for callback in ['l', 'u', 'lt', 'ut', 'reset_js']:
        for widget in [
                'lower_slider', 'upper_slider', 'lower_input', 'upper_input',
                'reset_button'
        ]:
            exec('callback_%s.args["%s"] = %s' % (callback, widget, widget))

    wb = widgetbox(
        [upper_slider, upper_input, lower_slider, lower_input, reset_button],
        width=100,
        sizing_mode='stretch_both')
    return wb
Example #31
0
                     value=1,
                     step=.1,
                     title="Frequency",
                     callback=callback)
callback.args["freq"] = freq_slider

phase_slider = Slider(start=0,
                      end=6.4,
                      value=0,
                      step=.1,
                      title="Phase",
                      callback=callback)
callback.args["phase"] = phase_slider

offset_slider = Slider(start=-5,
                       end=5,
                       value=0,
                       step=.1,
                       title="Offset",
                       callback=callback)
callback.args["offset"] = offset_slider

layout = row(
    plot,
    widgetbox(amp_slider, freq_slider, phase_slider, offset_slider),
)

output_file("python_callback.html", title="python_callback.py example")

show(layout)
Example #32
0
                   y_range=(0, max(f)),
                   active_drag=None,
                   plot_width=800,
                   plot_height=200)
        p.image(image=[Sxx],
                x=0,
                y=0,
                dw=max(t),
                dh=max(f),
                palette='Spectral11')

        plots.append(p)

    return column(p)


print files

data_select = Select(title='File:',
                     value=files[0],
                     options=data_list(files[0], files))
data_select.on_change('value', update_file)

p = make_total_spectrogram(files[0])

col = mic_spectrogram(files[0])

layout = column(row(widgetbox(data_select), p), col)

show(layout)
Example #33
0
File: main.py Project: desihub/qlf
    def load_qa(self):

        cam = self.selected_arm + str(self.selected_spectrograph)

        mergedqa = QLFModels().get_output(self.selected_process_id, cam)

        gen_info = mergedqa['GENERAL_INFO']
        flavor = mergedqa['FLAVOR']

        if flavor == "science":
            ra = gen_info['RA']
            dec = gen_info['DEC']

        check_ccds = mergedqa['TASKS']['CHECK_CCDs']

        xwsigma = check_ccds['METRICS']['XWSIGMA']
        xw_amp = check_ccds['METRICS']['XWSIGMA_AMP']

        xw_fib = check_ccds['METRICS']['XWSIGMA_FIB']

        nrg = check_ccds['PARAMS']['XWSIGMA_NORMAL_RANGE']
        wrg = check_ccds['PARAMS']['XWSIGMA_WARN_RANGE']
        obj_type = sort_obj(gen_info)  # [""]*500

        if mergedqa['FLAVOR'].upper() == 'SCIENCE':
            program = mergedqa['GENERAL_INFO']['PROGRAM'].upper()
            program_prefix = '_' + program
        else:
            program_prefix = ''
        xw_ref = check_ccds['PARAMS']['XWSIGMA' + program_prefix + '_REF']

        xsigma = xw_fib[0]
        wsigma = xw_fib[1]

        delta_rg = wrg[1] - wrg[0]
        hist_rg = (wrg[0] - 0.1 * delta_rg, wrg[1] + 0.1 * delta_rg)

        my_palette = get_palette("RdYlBu_r")

        xfiber = np.arange(len(xsigma))
        wfiber = np.arange(len(wsigma))
        if mergedqa['FLAVOR'].upper() != 'SCIENCE':
            ra = np.full(500, np.nan)
            dec = np.full(500, np.nan)

        source = ColumnDataSource(
            data={
                'x1': ra,
                'y1': dec,
                'xsigma': xsigma,
                'wsigma': wsigma,
                'delta_xsigma': np.array(xsigma) - xw_ref[0],
                'delta_wsigma': np.array(wsigma) - xw_ref[1],
                'xref': [xw_ref[0]] * len(xsigma),
                'wref': [xw_ref[1]] * len(xsigma),
                'xfiber': xfiber,
                'wfiber': wfiber,
                'OBJ_TYPE': obj_type,
                'left': np.arange(0, 500) - 0.4,
                'right': np.arange(0, 500) + 0.4,
                'bottom': [0] * 500
            })

        xsigma_tooltip = """
            <div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">XSigma: </span>
                    <span style="font-size: 1vw; color: #515151">@xsigma</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Reference: </span>
                    <span style="font-size: 1vw; color: #515151">@xref</span>
                </div>

                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Obj Type: </span>
                    <span style="font-size: 1vw; color: #515151;">@OBJ_TYPE</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">RA: </span>
                    <span style="font-size: 1vw; color: #515151;">@x1</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">DEC: </span>
                    <span style="font-size: 1vw; color: #515151;">@y1</span>
                </div>

                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">FIBER ID: </span>
                    <span style="font-size: 1vw; color: #515151;">@xfiber</span>
                </div>

                </div>
            """

        wsigma_tooltip = """
            <div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">WSigma: </span>
                    <span style="font-size: 1vw; color: #515151">@wsigma</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Reference: </span>
                    <span style="font-size: 1vw; color: #515151">@wref</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Obj Type: </span>
                    <span style="font-size: 1vw; color: #515151;">@OBJ_TYPE</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">RA: </span>
                    <span style="font-size: 1vw; color: #515151;">@x1</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">DEC: </span>
                    <span style="font-size: 1vw; color: #515151;">@y1</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">FIBER ID: </span>
                    <span style="font-size: 1vw; color: #515151;">@wfiber</span>
                </div>

            </div>
            """

        url = "http://legacysurvey.org/viewer?ra=@ra&dec=@dec&zoom=16&layer=decals-dr5"

        # determining the position of selected cam fibers:
        obj_type = sort_obj(gen_info)
        # ---------------------------------

        if flavor == "science":

            # axes limit
            xmin, xmax = [min(ra[:]), max(ra[:])]
            ymin, ymax = [min(dec[:]), max(dec[:])]
            xfac, yfac = [(xmax - xmin) * 0.06, (ymax - ymin) * 0.06]
            left, right = xmin - xfac, xmax + xfac
            bottom, top = ymin - yfac, ymax + yfac

            low, high = wrg
            xmapper = LinearColorMapper(palette=my_palette,
                                        low=low,
                                        high=high,
                                        nan_color="darkgrey")

            wmapper = LinearColorMapper(palette=my_palette,
                                        low=low,
                                        high=high,
                                        nan_color="darkgrey")

            # ============
            # XSIGMA WEDGE

            radius = 0.0165
            radius_hover = 0.02

            # centralize wedges in plots:
            ra_center = 0.5 * (max(ra) + min(ra))
            dec_center = 0.5 * (max(dec) + min(dec))
            xrange_wedge = Range1d(start=ra_center + .95, end=ra_center - .95)
            yrange_wedge = Range1d(start=dec_center + .82,
                                   end=dec_center - .82)

            wedge_plot_x = Plot2d(x_range=xrange_wedge,
                                  y_range=yrange_wedge,
                                  x_label="RA",
                                  y_label="DEC",
                                  tooltip=xsigma_tooltip,
                                  title="XSIGMA",
                                  width=500,
                                  height=380,
                                  yscale="auto").wedge(
                                      source,
                                      x='x1',
                                      y='y1',
                                      field='delta_xsigma',
                                      mapper=xmapper,
                                      colorbar_title='xsigma').plot

            taptool = wedge_plot_x.select(type=TapTool)
            taptool.callback = OpenURL(url=url)

            # ============
            # WSIGMA WEDGE
            wedge_plot_w = Plot2d(x_range=xrange_wedge,
                                  y_range=yrange_wedge,
                                  x_label="RA",
                                  y_label="DEC",
                                  tooltip=wsigma_tooltip,
                                  title="WSIGMA",
                                  width=500,
                                  height=380,
                                  yscale="auto").wedge(
                                      source,
                                      x='x1',
                                      y='y1',
                                      field='delta_wsigma',
                                      mapper=wmapper,
                                      colorbar_title='wsigma').plot

            taptool = wedge_plot_w.select(type=TapTool)
            taptool.callback = OpenURL(url=url)

        # ================================
        # Stat histogram

        # x_fiber_hist
        d_yplt = (max(xsigma) - min(xsigma)) * 0.1
        yrange = [0, max(xsigma) + d_yplt]

        xhist = Plot2d(
            yrange,
            x_label="Fiber number",
            y_label="X std dev (number of pixels)",
            tooltip=xsigma_tooltip,
            title="",
            width=600,
            height=300,
            yscale="auto",
            hover_mode="vline",
        ).quad(
            source,
            top='xsigma',
        )

        # w_fiber_hist
        d_yplt = (max(wsigma) - min(wsigma)) * 0.1
        yrange = [0, max(wsigma) + d_yplt]

        whist = Plot2d(
            yrange,
            x_label="Fiber number",
            y_label="W std dev (number of pixels)",
            tooltip=xsigma_tooltip,
            title="",
            width=600,
            height=300,
            yscale="auto",
            hover_mode="vline",
        ).quad(
            source,
            top='wsigma',
        )

        # ================================
        # Stat histogram

        def histpar(yscale, hist):
            if yscale == 'log':
                ylabel = "Frequency + 1"
                yrange = (1, 11**(int(np.log10(max(hist))) + 1))
                bottomval = 'bottomplusone'
                histval = 'histplusone'
            else:
                ylabel = "Frequency"
                yrange = (0.0 * max(hist), 1.1 * max(hist))
                bottomval = 'bottom'
                histval = 'hist'
            return [ylabel, yrange, bottomval, histval]

        xhistlabel = "XSIGMA"
        yscale = "auto"

        hist_tooltip_x = """
            <div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Frequency: </span>
                    <span style="font-size: 1vw; color: #515151">@hist</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">XSIGMA: </span>
                    <span style="font-size: 1vw; color: #515151;">[@left, @right]</span>
                </div>
            </div>
        """

        hist, edges = np.histogram(xsigma, 'sqrt')

        source_hist = ColumnDataSource(
            data={
                'hist': hist,
                'histplusone': hist + 1,
                'bottom': [0] * len(hist),
                'bottomplusone': [1] * len(hist),
                'left': edges[:-1],
                'right': edges[1:]
            })

        ylabel, yrange, bottomval, histval = histpar(yscale, hist)

        p_hist_x = Plot2d(
            x_label=xhistlabel,
            y_label=ylabel,
            tooltip=hist_tooltip_x,
            title="",
            width=600,
            height=300,
            yscale="auto",
            y_range=yrange,
            x_range=(hist_rg[0] + xw_ref[0], hist_rg[1] + xw_ref[0]),
            hover_mode="vline",
        ).quad(
            source_hist,
            top=histval,
            bottom=bottomval,
            line_width=0.4,
        )

        # Histogram 2
        xhistlabel = "WSIGMA"
        hist_tooltip_w = """
            <div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">Frequency: </span>
                    <span style="font-size: 1vw; color: #515151">@hist</span>
                </div>
                <div>
                    <span style="font-size: 1vw; font-weight: bold; color: #303030;">WSIGMA: </span>
                    <span style="font-size: 1vw; color: #515151;">[@left, @right]</span>
                </div>
            </div>
        """

        hist, edges = np.histogram(wsigma, 'sqrt')

        source_hist = ColumnDataSource(
            data={
                'hist': hist,
                'histplusone': hist + 1,
                'bottom': [0] * len(hist),
                'bottomplusone': [1] * len(hist),
                'left': edges[:-1],
                'right': edges[1:]
            })

        ylabel, yrange, bottomval, histval = histpar(yscale, hist)
        yrangew = yrange

        p_hist_w = Plot2d(
            x_label=xhistlabel,
            y_label=ylabel,
            tooltip=hist_tooltip_w,
            title="",
            width=600,
            height=300,
            yscale="auto",
            y_range=yrange,
            x_range=(hist_rg[0] + xw_ref[1], hist_rg[1] + xw_ref[1]),
            hover_mode="vline",
        ).quad(
            source_hist,
            top=histval,
            bottom=bottomval,
            line_width=0.8,
        )

        # --------------------------------------------------------------
        # vlines ranges:
        bname = 'XWSIGMA'

        for ialert in nrg:  # par[bname+'_NORMAL_RANGE']:
            spans = Span(location=ialert + xw_ref[0],
                         dimension='height',
                         line_color='green',
                         line_dash='dashed',
                         line_width=2)
            p_hist_x.add_layout(spans)
            my_label = Label(x=ialert + xw_ref[0],
                             y=yrange[-1] / 2.2,
                             y_units='data',
                             text='Normal',
                             text_color='green',
                             angle=np.pi / 2.)
            p_hist_x.add_layout(my_label)

        for ialert in wrg:  # par[bname+'_WARN_RANGE']:
            spans = Span(location=ialert + xw_ref[0],
                         dimension='height',
                         line_color='tomato',
                         line_dash='dotdash',
                         line_width=2)
            p_hist_x.add_layout(spans)
            my_label = Label(x=ialert + xw_ref[0],
                             y=yrange[-1] / 2.2,
                             y_units='data',
                             text='Warning',
                             text_color='tomato',
                             angle=np.pi / 2.)
            p_hist_x.add_layout(my_label)

        for ialert in nrg:  # par[bname+'_NORMAL_RANGE']:
            spans = Span(location=ialert + xw_ref[1],
                         dimension='height',
                         line_color='green',
                         line_dash='dashed',
                         line_width=2)
            p_hist_w.add_layout(spans)
            my_label = Label(x=ialert + xw_ref[1],
                             y=yrangew[-1] / 2.2,
                             y_units='data',
                             text='Normal',
                             text_color='green',
                             angle=np.pi / 2.)
            p_hist_w.add_layout(my_label)

        for ialert in wrg:  # par[bname+'_WARN_RANGE']:
            spans = Span(location=ialert + xw_ref[1],
                         dimension='height',
                         line_color='tomato',
                         line_dash='dotdash',
                         line_width=2)
            p_hist_w.add_layout(spans)
            my_label = Label(x=ialert + xw_ref[1],
                             y=yrangew[-1] / 2.2,
                             y_units='data',
                             text='Warning',
                             text_color='tomato',
                             angle=np.pi / 2.)
            p_hist_w.add_layout(my_label)

        # amp 1
        xamp = Patch().plot_amp(
            dz=xw_amp[0],
            refexp=[xw_ref[0]] * 4,
            name="XSIGMA AMP",
            description="X standard deviation (number of pixels)",
            wrg=wrg)

        xamp_status = Patch().plot_amp(
            dz=xw_amp[0],
            refexp=[xw_ref[0]] * 4,
            name="XSIGMA AMP (STATUS)",
            description="X standard deviation (number of pixels)",
            wrg=wrg,
            nrg=nrg,
            status_plot=True,
        )

        # amp 2
        wamp = Patch().plot_amp(
            dz=xw_amp[1],
            refexp=[xw_ref[1]] * 4,
            name="WSIGMA AMP",
            description="W standard deviation (number of pixels)",
            wrg=wrg)

        wamp_status = Patch().plot_amp(
            dz=xw_amp[1],
            refexp=[xw_ref[1]] * 4,
            name="WSIGMA AMP (STATUS)",
            description="W standard deviation (number of pixels)",
            wrg=wrg,
            nrg=nrg,
            status_plot=True,
        )

        # -------------------------------------------------------------------------
        info_col = Title().write_description('xwsigma')

        current_exposures = check_ccds['METRICS']['XWSIGMA']

        if flavor == 'science':
            program = gen_info['PROGRAM'].upper()
            reference_exposures = check_ccds['PARAMS']['XWSIGMA_' + program +
                                                       '_REF']
            keynames = ["XSIGMA"]
            table_x = Table().single_table(keynames, [current_exposures[0]],
                                           [reference_exposures[0]], nrg, wrg)
            keynames = ["WSIGMA"]
            table_w = Table().single_table(keynames, [current_exposures[1]],
                                           [reference_exposures[1]], nrg, wrg)

            layout = column(
                info_col,
                widgetbox(Div(), css_classes=["tableranges"]),
                widgetbox(
                    Div(text=
                        '<h2 align=center style="text-align:center;">  XSIGMA </h2>'
                        )),
                widgetbox(
                    Div(text=
                        '<h2 align=center style="text-align:center;">  WSIGMA </h2>'
                        )),
                table_x,
                table_w,
                column(wedge_plot_x, sizing_mode='scale_both'),
                column(wedge_plot_w, sizing_mode='scale_both'),
                column(xhist, sizing_mode='scale_both'),
                column(whist, sizing_mode='scale_both'),
                column(p_hist_x, sizing_mode='scale_both'),
                column(p_hist_w, sizing_mode='scale_both'),
                column(xamp, sizing_mode='scale_both'),
                column(wamp, sizing_mode='scale_both'),
                column(xamp_status, sizing_mode='scale_both'),
                column(wamp_status, sizing_mode='scale_both'),
                css_classes=["display-grid"],
                sizing_mode='scale_width')
        else:
            reference_exposures = check_ccds['PARAMS']['XWSIGMA_REF']
            keynames = ["XSIGMA"]
            table_x = Table().single_table(keynames, current_exposures,
                                           reference_exposures, nrg, wrg)
            keynames = ["WSIGMA"]
            table_w = Table().single_table(keynames, current_exposures,
                                           reference_exposures, nrg, wrg)

            layout = column(
                info_col,
                widgetbox(Div(), css_classes=["tableranges"]),
                widgetbox(
                    Div(text=
                        '<h2 align=center style="text-align:center;">  XSIGMA </h2>'
                        )),
                widgetbox(
                    Div(text=
                        '<h2 align=center style="text-align:center;">  WSIGMA </h2>'
                        )),
                table_x,
                table_w,
                column(xhist, sizing_mode='scale_both'),
                column(whist, sizing_mode='scale_both'),
                column(p_hist_x, sizing_mode='scale_both'),
                column(p_hist_w, sizing_mode='scale_both'),
                column(xamp, sizing_mode='scale_both'),
                column(wamp, sizing_mode='scale_both'),
                column(xamp_status, sizing_mode='scale_both'),
                column(wamp_status, sizing_mode='scale_both'),
                css_classes=["display-grid"],
                sizing_mode='scale_width')

        return file_html(layout, CDN, "XWSIGMA")
Example #34
0
salt_img = salt.image_rgba(image=[salt_data],
                           x=0,
                           y=0,
                           dw=side_width,
                           dh=side_height)

salt_slider = Slider(start=0,
                     end=0.5,
                     value=0.1,
                     step=0.1,
                     width=side_width - 40,
                     title='Salt and Pepper Filter - Adjust the Density')

salt_slider.on_change('value', updateSaltPepper)

salt_slide = widgetbox(children=[salt_slider], sizing_mode='scale_both')

figures.append(salt)

# =============================================================================
# Image 7 - Gaussian Smoothing Filter
# =============================================================================


def gaussian_filter(input_img, sigma):
    """ 
    Computes the gaussian filter on each color channel of the input image
    
    Input:
        orginal image
        sigma value for the gaussian filter
    upload.append(data[i].upload)
    ping.append(data[i].ping)

d = {'date': date, 'download': download, 'upload': upload, 'ping': ping}

df = pd.DataFrame(data=d)

df['download'] = pd.to_numeric(df['download'])
df['upload'] = pd.to_numeric(df['upload'])
df['ping'] = pd.to_numeric(df['ping'])

download_summary = df['download'].describe()
upload_summary = df['upload'].describe()
ping_summary = df['ping'].describe()

summary = {
    'stat': download_summary.index,
    'download': download_summary.values,
    'upload': upload_summary.values,
    'ping': ping_summary.values
}

summary_df = pd.DataFrame(summary)
summary_div = Div(text=summary_df.to_html(index=False))

output_file("results.html")
p = figure(x_axis_type='datetime', plot_width=1700)
p.line(date, download, line_width=1)
p.line(date, upload, line_width=1, line_color='red')
save(widgetbox(p, summary_div, sizing_mode='scale_both'))
Example #36
0
# Import the necessary modules
from bokeh.layouts import widgetbox, row
from bokeh.models import Slider


# Define the callback function: update_plot
def update_plot(attr, old, new):
    # Set the yr name to slider.value and new_data to source.data
    yr = slider.value
    new_data = {
        'x': data.loc[yr].fertility,
        'y': data.loc[yr].life,
        'country': data.loc[yr].Country,
        'pop': (data.loc[yr].population / 20000000) + 2,
        'region': data.loc[yr].region,
    }
    source.data = new_data


# Make a slider object: slider
slider = Slider(start=1970, end=2010, step=1, value=1970, title='Year')

# Attach the callback to the 'value' property of slider
slider.on_change('value', update_plot)

# Make a row layout of widgetbox(slider) and plot and add it to the current document
layout = row(widgetbox(slider), plot)
curdoc().add_root(layout)
Example #37
0
                  color={'field': 'state', 'transform': color_mapper},
                  alpha=0.8, line_color='#240606', line_width=1, line_alpha=0.3)
    r2 = p.multi_line('xs', 'ys', line_width='line_width', alpha='alphas',
                      color={'field': 'weight', 'transform': mapper},
                      source=edge_df)

    node_hover = HoverTool(tooltips=[('Name', '@Name'), ('State', '@state'), ('No. of Connections', '@Degree'),
                                     ('Total Frequency', '@WDegree')], renderers=[r1])
    node_hover.attachment = 'right'
    edge_hover = HoverTool(tooltips=[('Airports', '@city1'), ('', '@city2'), ('Frequency', '@weight')], renderers=[r2])
    edge_hover.line_policy = 'interp'
    edge_hover.attachment = 'left'
    p.add_tools(node_hover)
    p.add_tools(edge_hover)
    return p


def update(attr, old, new):
    layout.children[1] = create_figure()


ndf = Slider(start=0, end=10, value=0, step=.1, title="Min. Node")
ndf.on_change('value', update)

edf = Slider(start=0, end=0.6, value=0, step=.05, title="Min. Edge Frequency")
edf.on_change('value', update)

controls = widgetbox([ndf, edf], width=300)
layout = row(controls, create_figure())
curdoc().add_root(layout)
Example #38
0
def music_tab(Music):
    def make_dataset(Music):
        #con = sql.connect('/Users/aaronwestmoreland/Documents/Data.Projects/Music/Metacritic.db')

        #Music = psql.read_sql('SELECT * FROM Music;', con)

        Mus_split = Music["Day"].str.split(' ', expand=True)
        Music["Month"] = Mus_split[0]
        Music["Date"] = Mus_split[1]

        c_map = bp.magma(len(np.unique(Music["Score"])))
        c_dict = zip(np.unique(Music["Score"]), c_map)
        Col_MAP = dict(c_dict)
        Music["color"] = Music["Score"].apply(lambda x: Col_MAP[x])

        #Music["Month"]

        Music["DateTime"] = pd.to_datetime(Music["Release"],
                                           format="%b %d, %Y")

        Music['alpha'] = np.where(Music["Score"].astype(float) >= 90, 0.9,
                                  0.25)

        mu_dict = dict(
            x=Music["Release"],
            y=Music["Score"].astype(float),
            album=Music["Album"],
            release=Music["Release"],
            artist=Music["Artist"],
            alpha=Music["alpha"],
            color=Music['color'],
        )
        return ColumnDataSource(mu_dict)

    def make_plot(src):
        axis_map = {
            "Year": "DateTime",
            "MetaCritic Score": "Score",
        }

        x_axis = Select(title="X Axis",
                        options=sorted(axis_map.keys()),
                        value="Year")
        y_axis = Select(title="Y Axis",
                        options=sorted(axis_map.keys()),
                        value="MetaCritic Score")

        TOOLTIPS = [("Album", "@album"), ("Artist", "@artist"),
                    ("Score", "@y"), ("Release", "@release")]

        p = figure(plot_height=600,
                   plot_width=700,
                   title="",
                   toolbar_location="below",
                   x_axis_type="datetime")
        p.circle(x="x",
                 y="y",
                 source=src,
                 size=7,
                 color="color",
                 line_color=None,
                 fill_alpha="alpha")
        p.add_tools(
            HoverTool(show_arrow=False, line_policy='next', tooltips=TOOLTIPS))
        p.xaxis.formatter = DatetimeTickFormatter(
            hours=["%d %B %Y"],
            days=["%d %B %Y"],
            months=["%d %B %Y"],
            years=["%d %B %Y"],
        )

        p.xaxis.major_label_orientation = np.pi / 4
        return p, axis_map, y_axis, x_axis

    def select_Music():
        Month_val = Month.value
        selected = Music
        if (Month_val != "All"):
            selected = selected[selected.Month.str.contains(Month_val) == True]
        return selected

    def update():
        df = select_Music()
        x_name = axis_map[x_axis.value]
        y_name = axis_map[y_axis.value]

        p.xaxis.axis_label = x_axis.value
        p.yaxis.axis_label = y_axis.value
        p.title.text = "%d Albums selected" % len(df)
        src.data = dict(
            x=df[x_name],
            y=df[y_name].astype(float),
            album=df["Album"],
            release=df["Release"],
            artist=df["Artist"],
            alpha=df["alpha"],
            color=df["color"],
        )

    src = make_dataset(Music)
    months = list(np.unique(Music["Month"]))
    months.append("All")

    Month = Select(title="Release Month", value="All", options=months)

    p, axis_map, y_axis, x_axis = make_plot(src)

    controls = [Month]
    for control in controls:
        control.on_change('value', lambda attr, old, new: update())

    sizing_mode = 'fixed'

    inputs = widgetbox(*controls, sizing_mode=sizing_mode)
    l = layout([[inputs, p]], sizing_mode=sizing_mode)

    update()
    tab = Panel(child=l, title="Music")
    return tab
Example #39
0
def get_changed_parameters(initial_parameters, plot_width):
    """
    get a bokeh widgetbox object with a table of the changed parameters
    :param initial_parameters: ulog.initial_parameters
    """
    param_names = []
    param_values = []
    param_defaults = []
    param_mins = []
    param_maxs = []
    param_descriptions = []
    default_params = get_default_parameters()
    for param_name in sorted(initial_parameters):
        param_value = initial_parameters[param_name]

        if param_name.startswith('RC') or param_name.startswith('CAL_'):
            continue

        try:
            if param_name in default_params:
                default_param = default_params[param_name]
                if default_param['type'] == 'FLOAT':
                    is_default = abs(float(default_param['default']) - float(param_value)) < 0.00001
                    if 'decimal' in default_param:
                        param_value = round(param_value, int(default_param['decimal']))
                else:
                    is_default = int(default_param['default']) == int(param_value)
                if not is_default:
                    param_names.append(param_name)
                    param_values.append(param_value)
                    param_defaults.append(default_param['default'])
                    param_mins.append(default_param.get('min', ''))
                    param_maxs.append(default_param.get('max', ''))
                    param_descriptions.append(default_param.get('short_desc', ''))
            else:
                # not found: add it as if it were changed
                param_names.append(param_name)
                param_values.append(param_value)
                param_defaults.append('')
                param_mins.append('')
                param_maxs.append('')
                param_descriptions.append('(unknown)')
        except Exception as error:
            print(type(error), error)
    param_data = dict(
        names=param_names,
        values=param_values,
        defaults=param_defaults,
        mins=param_mins,
        maxs=param_maxs,
        descriptions=param_descriptions)
    source = ColumnDataSource(param_data)
    columns = [
        TableColumn(field="names", title="Name",
                    width=int(plot_width*0.2), sortable=False),
        TableColumn(field="values", title="Value",
                    width=int(plot_width*0.15), sortable=False),
        TableColumn(field="defaults", title="Default",
                    width=int(plot_width*0.1), sortable=False),
        TableColumn(field="mins", title="Min",
                    width=int(plot_width*0.075), sortable=False),
        TableColumn(field="maxs", title="Max",
                    width=int(plot_width*0.075), sortable=False),
        TableColumn(field="descriptions", title="Description",
                    width=int(plot_width*0.40), sortable=False),
        ]
    data_table = DataTable(source=source, columns=columns, width=plot_width,
                           height=300, sortable=False, selectable=False)
    div = Div(text="""<b>Non-default Parameters</b> (except RC and sensor calibration)""",
              width=int(plot_width/2))
    return widgetbox(div, data_table, width=plot_width)
Example #40
0
    predictions=clf.predict(x_test_original)
    print("Accuracy =", accuracy_score(y_test_original,predictions))
    y_score = clf.predict_proba(x_test_original)[:,1]
    precision, recall, _ = precision_recall_curve(y_test_original, y_score)
    p1.line(precision, recall, line_width=2,line_alpha=0.6,name ="line2")
    average_precision = average_precision_score(y_test_original, predictions)
    p1.title.text = "Average Precision Score %f" % average_precision
    #print(np.unique(predictions))
    tn, fp, fn, tp = confusion_matrix(y_test_original,predictions,labels=[0,1]).ravel()
    source.data =dict(fruits=fruits, counts=[tp, fp, tn, fn])
    p.title.text = "Model Accuracy %f" % accuracy_score(y_test_original,predictions)
    
controls = [features, fit_intercept, solver, warm_start, dual]
for control in controls:
    control.on_change('value', lambda attr, old, new: update())

sizing_mode = 'fixed'  # 'scale_width' also looks nice with this example

inputs = widgetbox(*controls, sizing_mode=sizing_mode)

l = layout([
    [desc],
    [row(target,stats)],
    [inputs,tabs]
],sizing_mode= sizing_mode)


#update()  # initial load of the data
 
curdoc().add_root(l)
curdoc().title = "Churn" 
Example #41
0
### bokeh server

# Perform necessary imports
from bokeh.io import curdoc
from bokeh.layouts import widgetbox
from bokeh.models import Slider

# Create first slider: slider1
slider1 = Slider(title='slider1', start=0, end=10, step=0.1, value=2)

# Create second slider: slider2
slider2 = Slider(title='slider2', start=10, end=100, step=1, value=20)

# Add slider1 and slider2 to a widgetbox
layout = widgetbox(slider1, slider2)

# Add the layout to the current document
curdoc().add_root(layout)

## slider

# Create ColumnDataSource: source
source = ColumnDataSource(data={
    'x': pri_fin_mat.index,
    'y': pri_fin_mat.Stocks
})

# Add a line to the plot
plot = figure()
plot.line('x', 'y', source=source)
Example #42
0
    count = dfyc.genre.value_counts()

    colors = [genre_color[x] for x in count.index.sort_values()]

    pyc = Donut(count,
                label='index',
                color=colors,
                height=400,
                width=400,
                hover_text='#songs')

    pyc.title.text = "#Songs w/o missing year and location = {}".format(
        len(dfyc))

    return p, py, pyc


controls = widgetbox([checkbox_year, year_slider], width=200)

a, b, c = create_figure()
layout = row(controls, a, b, c)

curdoc().add_root(layout)
curdoc().title = "Hottness_familiarity"

plots = {'1': a, '2': b, '3': c}

script, div = components(plots)
print(script)
print(div)
Example #43
0
                       yB=magblackbody_B,
                       yr=magblackbody_r,
                       yi=magblackbody_i,
                       yV=magblackbody_V,
                       yU=magblackbody_U)


button.callback = CustomJS(args=dict(source=source,
                                     vej=v_slider,
                                     name_v=text,
                                     mej=M_slider,
                                     myk=k_slider,
                                     myt0=T_slider,
                                     myb=bfield_slider,
                                     myp=pspin_slider,
                                     tmin=np.min(arrayoftimes)),
                           code=javaScript)

#for w in [M_slider,f_slider,v_slider, k_slider, T_slider]:
#    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = widgetbox(text, M_slider, v_slider, k_slider, T_slider, bfield_slider,
                   pspin_slider)
layout = row(plot, inputs, button)

output_file("MagnetarThing.html")

save(plot)
show(layout)
Example #44
0
def update():
    current = df[(df['salary'] >= slider.value[0]) & (df['salary'] <= slider.value[1])].dropna()
    source.data = {
        'name'             : current.name,
        'salary'           : current.salary,
        'years_experience' : current.years_experience,
    }

slider = RangeSlider(title="Max Salary", start=10000, end=110000, value=(10000, 50000), step=1000, format="0,0")
slider.on_change('value', lambda attr, old, new: update())

button = Button(label="Download", button_type="success")
button.callback = CustomJS(args=dict(source=source),
                           code=open(join(dirname(__file__), "download.js")).read())

columns = [
    TableColumn(field="name", title="Employee Name"),
    TableColumn(field="salary", title="Income", formatter=NumberFormatter(format="$0,0.00")),
    TableColumn(field="years_experience", title="Experience (years)")
]

data_table = DataTable(source=source, columns=columns, width=800)

controls = widgetbox(slider, button)
table = widgetbox(data_table)

curdoc().add_root(row(controls, table))
curdoc().title = "Export CSV"

update()
Example #45
0
tab_1 = Panel(child = p1, title = 'Setosa')
tab_2 = Panel(child = p2, title = 'Virginica')

from bokeh.models.widgets import Tabs
layout = Tabs(tabs = [tab1, tab2])
show(layout)


############# bokeh app
from bokeh.io import curdoc
from bokeh.layouts import widgetbox
from bokeh.models import Slider

# slider
slider = Slider(title ='my slider', start = 0, end = 10, step = 0.1, value = 2)
layout = column(p, widgetbox(slider))

curdoc().add_root(layout)

bokeh serve current.py

# callback
from bokeh.models import ColumnDataSource, Select

source = ColumnDataSource(data = {'x': iris['Sepal_Length'], 'y': iris['Sepal_Width']})
p = figure()
p.circle('x', 'y', source = source)

def update_plot(attr, old, new):
    if new == 'Petal_Length':
        source.data = {'x': 'Sepal_Length', 'y': 'Petal_Length'}
Example #46
0
    kdims = [x.value, y.value]

    opts, style = {}, {}
    opts['color_index'] = color.value if color.value != 'None' else None
    if size.value != 'None':
        opts['size_index'] = size.value
        opts['scaling_factor'] = (1./df[size.value].max())*200
    points = hv.Points(df, kdims=kdims, label=label).opts(plot=opts, style=style)
    return renderer.get_plot(points).state

def update(attr, old, new):
    layout.children[1] = create_figure()

x = Select(title='X-Axis', value='mpg', options=quantileable)
x.on_change('value', update)

y = Select(title='Y-Axis', value='hp', options=quantileable)
y.on_change('value', update)

size = Select(title='Size', value='None', options=['None'] + quantileable)
size.on_change('value', update)

color = Select(title='Color', value='None', options=['None'] + quantileable)
color.on_change('value', update)

controls = widgetbox([x, y, color, size], width=200)
layout = row(controls, create_figure())

curdoc().add_root(layout)
curdoc().title = "Crossfilter"
Example #47
0
color_bar = ColorBar(color_mapper=mapper,
                     major_label_text_align='left',
                     major_label_text_font_size='10pt',
                     label_standoff=2,
                     location=(0, 0),
                     formatter=formatter,
                     title="(ADU)",
                     title_text_baseline="alphabetic")

p.add_layout(color_bar, 'right')

p.xaxis.major_label_text_font_size = '0pt'  # turn off x-axis tick labels
p.yaxis.major_label_text_font_size = '0pt'  # turn off y-axis tick labels
p.xaxis.major_tick_line_color = None  # turn off x-axis major ticks
p.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks

p.yaxis.major_tick_line_color = None  # turn off y-axis major ticks
p.yaxis.minor_tick_line_color = None  # turn off y-axis minor ticks

#infos
info, nlines = write_info('getbias', tests['getbias'])
txt = PreText(text=info, height=nlines * 20, width=p.plot_width)
info_col = Div(text=write_description('getbias'), width=p.plot_width)
ptxt = column(widgetbox(info_col), p)

#output_notebook()

# End of Bokeh Block
curdoc().add_root(ptxt)
curdoc().title = "GETBIAS"
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')
plot.line('x', 'y', source=source_function2, color='green', line_width=3, line_alpha=0.6, legend='function 2')
plot.line('x', 'y', source=source_result, color='blue', line_width=3, line_alpha=0.6, legend='convolution')
plot.scatter('x', 'y', source=source_xmarker, color='black')
plot.line('x', 'y', source=source_xmarker, color='black', line_width=3)
plot.patch('x', 'y_pos', source=source_overlay, fill_color='blue', fill_alpha=.2)
plot.patch('x', 'y_neg', source=source_overlay, fill_color='red', fill_alpha=.2)

# calculate data
update_data()

# lists all the controls in our app
controls = widgetbox(x_value_input, function_type, function1_input, function2_input, width=400)

# make layout
curdoc().add_root(row(plot, controls, width=800))
Example #49
0
def refresh_doc(doc):
    def create_dataset(flat_type_info,default_year_1,default_year_2):
        #Subset to the datafrane
        price_df = sub_df1.loc[flat_type_info]
        #Reset index of price df
        price_df = price_df.reset_index()
        #Sort df according to min to max values
        price_df.sort_values(by=default_year_1,ascending=True,inplace= True,na_position='first')
        
        #Create a new df base on the sorted price df
        test_df=pd.DataFrame({'town':price_df['town'],'year_1':price_df[default_year_1],'year_2':price_df[default_year_2]})
        test_df['percent_change']=(price_df[default_year_2]-price_df[default_year_1])/price_df[default_year_1]*100
        test_df['name_year1']=default_year_1
        test_df['name_year2']=default_year_2
        
        return ColumnDataSource(test_df)
  
    def Hbarchart(src):
    
        source = src
        
        #Plot figure
        p = figure(y_range=source.data['town'], x_range=(0, getmaxprice+50000), plot_height=800, plot_width=800, 
                   title="Barchart of Average Median Resale Price for Selected Year 1 vs Selected Year 2",
                   toolbar_location=None, tools="")

        p.hbar(y=dodge('town', -0.15, range=p.y_range), right=src.column_names[2] , height=0.2, source=source,
               color="#00008b", legend='name_year1')

        p.hbar(y=dodge('town',  0.15, range=p.y_range), right=src.column_names[3] , height=0.2, source=source,
               color="#87cefa", legend='name_year2')

        # Hover tool with hline mode
        hover = HoverTool(tooltips=[('Town', '@town'),
                                    ('Median1', '@year_1'),
                                    ('Median2', '@year_2'),
                                    ('% Change', '@percent_change')],
                          mode='hline')
        # display a tooltip whenever the cursor is horizontally in line with a glyph

        p.add_tools(hover)

        p.y_range.range_padding = 0.1
        p.ygrid.grid_line_color = None
        p.yaxis.axis_label = 'Towns'
        p.xaxis.axis_label = 'Average Median Prices'
        p.legend.location = "top_right"
        p.legend.orientation = "vertical"
        
        return (p)


    def update(attr,old,new):
        # Get the room data for the graph
        flat_type_to_plot = room_selection.labels[room_selection.active]
        year_1_to_plot = year_1_selection.labels[year_1_selection.active]
        year_2_to_plot = year_2_selection.labels[year_2_selection.active]
           
        # Make a new dataset based on the selected # of rooms and years to plot
        new_src = create_dataset(flat_type_to_plot,year_1_to_plot,year_2_to_plot)

        # Update the source used to plot
        src.data.update(new_src.data)

    #Create radio buttons for room type / flat type selection
    room_selection = RadioGroup(labels=df1_idx_level_0, active=3)
    room_selection.on_change('active', update)
    default_room_type = room_selection.labels[room_selection.active]
    room_control = widgetbox(room_selection)

    #Create radio buttons for first year selection
    year_1_selection = RadioGroup(labels=df1_col_level_1, active=6)
    year_1_selection.on_change('active', update)
    default_year_1 = year_1_selection.labels[year_1_selection.active]
    year_1_control = widgetbox(year_1_selection)

    #Create radio buttons for second year selection
    year_2_selection = RadioGroup(labels=df1_col_level_1, active=10)
    year_2_selection.on_change('active', update)
    default_year_2 = year_2_selection.labels[year_2_selection.active]
    year_2_control = widgetbox(year_2_selection)
    
    src = create_dataset(default_room_type,default_year_1,default_year_2)
    
    plot = Hbarchart(src)

    l= layout([
        [room_control,year_1_control,year_2_control],
        [plot]])
    
    doc.add_root(l)
Example #50
0
def bokehGUI(ScoreBoard,
             MakerDictionary,
             offlineboard='None',
             curMeme="sustainability",
             curInfluencer='zbattiz',
             ApiRequest=False):

    MD = MakerDictionary
    SB = ScoreBoard
    if offlineboard: SB.import_board(offlineboard)
    BI = BokehControler(SB, MD)

    names = [k for k, v in SB.get_names().items()]
    category_codes = MD.categories.values()
    print(category_codes)

    # make this more generic:
    if not curInfluencer: curInfluencer = 'zbattiz'
    if not curMeme: curMeme = 'sustainability'

    BI.populateInfluencers(names, category_codes)
    BI.populateBoards(category_codes)
    BI.setActiveBoard(curMeme, BI.Boards.data.keys())
    BI.setActiveInfluencer(curInfluencer, BI.Influencers.data.keys())

    boards = BI.Boards
    board = BI.ActiveBoard
    influencers = BI.Influencers
    influencer = BI.ActiveInfluencer

    boardatr = ColumnDataSource(data=dict(legend=[curMeme]))
    influenceratr = ColumnDataSource(data=dict(legend=[curInfluencer]))

    #for k in BI.Boards.data.keys(): print(k, BI.Boards.data[k])

    # Drawing:::::::::::::

    ## Commom Tools::
    TOOLS = "tap,pan,wheel_zoom,reset,save"

    ## The Influencer Canvas::
    title = "Influencer"
    fig_influencer = figure(plot_width=700,
                            plot_height=500,
                            title=title,
                            tools=TOOLS,
                            toolbar_location="above",
                            toolbar_sticky=True,
                            active_drag="pan",
                            active_tap='tap',
                            active_scroll='wheel_zoom',
                            responsive=True)

    fig_influencer.axis.visible = False
    fig_influencer.border_fill_color = "whitesmoke"
    fig_influencer.border_fill_alpha = 0.3
    fig_influencer.min_border_top = 30
    fig_influencer.outline_line_width = 4
    fig_influencer.outline_line_alpha = 0.2
    fig_influencer.outline_line_color = "navy"
    fig_influencer.xgrid.visible = False
    fig_influencer.ygrid.visible = False

    ### Legend:::
    fig_influencer.circle(0,
                          0,
                          alpha=0.8,
                          color='olive',
                          legend='legend',
                          source=influenceratr)
    fig_influencer.legend.location = "top_left"
    fig_influencer.legend.label_text_font_size = "8pt"
    fig_influencer.legend.label_text_color = "red"

    ### Data:::
    fig_influencer.multi_line('xsegments',
                              'ysegments',
                              color="colors",
                              alpha=0.5,
                              line_width=2,
                              line_dash="dashed",
                              source=influencer)
    fig_influencer.circle('x',
                          'y',
                          color='colors',
                          size='sizes',
                          alpha=1,
                          source=influencer)
    labels = LabelSet(x='x',
                      y='y',
                      text='memes',
                      text_font_size='9pt',
                      level='glyph',
                      x_offset="offsets",
                      y_offset=0,
                      source=influencer,
                      render_mode='canvas')
    fig_influencer.add_layout(labels)

    ### Hover Tool:::
    infhover = HoverTool(
        tooltips=[("Score",
                   "@scores{0,0.000}"), ("Type",
                                         "per_tweet"), ("Ntweets", "@tweets")])
    fig_influencer.add_tools(infhover)

    ## The Board Canvas:::

    #for k in BI.ActiveBoard.data.keys(): print(k, BI.ActiveBoard.data[k])

    title_board = "Community Spirometer"
    fig_board = figure(plot_width=900,
                       plot_height=550,
                       title=title_board,
                       tools=TOOLS,
                       toolbar_location="above",
                       toolbar_sticky=True,
                       active_drag="pan",
                       active_tap='tap',
                       active_scroll='wheel_zoom',
                       responsive=True)
    fig_board.axis.visible = False
    fig_board.border_fill_color = "whitesmoke"
    fig_board.border_fill_alpha = 0.2
    fig_board.min_border_top = 30
    fig_board.outline_line_width = 6
    fig_board.outline_line_alpha = 0.2
    fig_board.outline_line_color = "navy"

    ### Legend:::
    fig_board.circle(0,
                     0,
                     alpha=0.8,
                     color='turquoise',
                     legend='legend',
                     source=boardatr)
    fig_board.legend.location = "top_left"
    fig_board.legend.label_text_font_size = "9pt"
    fig_board.legend.label_text_color = "red"

    ### Data:::
    fig_board.line('x',
                   'y',
                   alpha=0.4,
                   line_width=1,
                   line_dash="dashed",
                   source=board)
    fig_board.circle('x',
                     'y',
                     color='black',
                     size='levels',
                     alpha=1,
                     source=board)
    fig_board.circle('x',
                     'y',
                     color='colors',
                     size='sizes',
                     alpha=0.8,
                     source=board)
    labels = LabelSet(x='x',
                      y='y',
                      text='names',
                      text_font_size='7pt',
                      level='glyph',
                      x_offset='offsets',
                      y_offset=0,
                      source=board,
                      render_mode='canvas')
    fig_board.add_layout(labels)

    ### Hover Tool:::
    boardhover = HoverTool(tooltips=[("Name", "@names"), (
        "Phase",
        "@clusters"), ("Score",
                       "@scores{0,0.000}"), (
                           "Scoring type",
                           "per_tweet"), ("Number of tweets probed",
                                          "@tweets")])
    fig_board.add_tools(boardhover)

    # JavaScript Callbacks:::

    board.callback = CustomJS(args=dict(source=influencers,
                                        display=influencer,
                                        atr=influenceratr),
                              code="""
        var inds = cb_obj.selected['1d'].indices;
        var d1 = cb_obj.data;
        var d2 = source.data;
        var d3 = display.data;
        var d4 = atr.data;
        
        var ind = inds[0];
        console.log(ind);
        if (ind != null){
            d3['x'] = [];
            d3['y'] = [];
            d3['sizes'] = [];
            d3['scores'] = [];
            d3['names'] = [];
            d3['memes'] = [];
            d3['colors'] = [];
            d3['offsets'] = [];
            d3['xsegments'] = [];
            d3['ysegments'] = [];
            d3['tweets'] = [];
            d3_tags = [];
            
            var name = d1['names'][ind];
            console.log(name);
            d4['legend'] = [];
            d4['legend'].push(name);
            
            
            var start = d2['names'].indexOf(name);
            var end = d2['names'].lastIndexOf(name);
            
            console.log(start);
            console.log(end);

            for (var i = start; i <= end; i++) {
                d3['x'].push(d2['x'][i]);
                d3['y'].push(d2['y'][i]);
                d3['sizes'].push(d2['sizes'][i]);
                d3['scores'].push(d2['scores'][i]);
                d3['names'].push(d2['names'][i]);
                d3['memes'].push(d2['memes'][i]);
                d3['offsets'].push(d2['offsets'][i]);
                d3['colors'].push(d2['colors'][i]);
                d3['tweets'].push(d2['tweets'][i]);
                d3['xsegments'].push(d2['xsegments'][i]);
                d3['ysegments'].push(d2['ysegments'][i]);
            }
        }
        display.change.emit();
        atr.change.emit();
         """)

    influencer.callback = CustomJS(args=dict(source=boards,
                                             display=board,
                                             atr=boardatr),
                                   code="""
        var inds = cb_obj.selected['1d'].indices;
        var d1 = cb_obj.data;
        var d2 = source.data;
        var d3 = display.data;
        var d4 = atr.data;
        
        var ind = inds[0];
        console.log(ind)

        if (ind != null){
            d3['x'] = [];
            d3['y'] = [];
            d3['sizes'] = [];
            d3['scores'] = [];
            d3['levels'] = [];
            d3['clusters'] = [];
            d3['names'] = [];
            d3['memes'] = [];
            d3['offsets'] = [];
            d3['colors'] = [];
            d3['tweets'] = [];
            
            var meme = d1['memes'][ind];
            d4['legend'] = [];
            d4['legend'].push(meme)
            console.log(meme)
            
            var name = d1['names'][ind];
            var color = d1['colors'][ind]
            
            var start = d2['memes'].indexOf(meme);
            var end = d2['memes'].lastIndexOf(meme);
            
            console.log(start);
            console.log(end);
            
            for (var i = start; i <= end; i++) {
                d3['x'].push(d2['x'][i]);
                d3['y'].push(d2['y'][i]);
                d3['sizes'].push(d2['sizes'][i]);
                d3['scores'].push(d2['scores'][i]);
                d3['levels'].push(d2['levels'][i]);
                d3['clusters'].push(d2['clusters'][i]);
                d3['names'].push(d2['names'][i]);
                d3['memes'].push(d2['memes'][i]);
                d3['offsets'].push(d2['offsets'][i]);
                d3['tweets'].push(d2['tweets'][i]);
                if (d2['names'][i] == name){
                    d3['colors'].push(color);
                }
                else {
                    d3['colors'].push(d2['colors'][i]);
                }
            }
        }
        display.change.emit();
        atr.change.emit();
         """)

    # Adding additional Widgets and their events:::::

    ## Info Box::
    div_title = Div(text="""
                <h2> Sustainable Finance Spirometer</h2>
                <p><b>This Sprirometer infographics is one of the ways to observe opionion leaders and influencers,
                those who promote or debate on issues relevant to sustainable finance. </b>
                
                <p>Influential actors are placed rather outer branches of the spiral. See the lower interactive panel.
                An infleuncer's spiral profile, as of his/her contribution to the related debates,
                can be seen via the upper interactive panel.</p>
                
                <p>The data is collected from the tweets that are in the public domain.
                The latest tweets in English of an infleuncer is used for the analysis and visualizations. 
                The nodes on the spirometer (the lower panel) are resized according to the number of tweets
                by the corresponding influencer.</p>
                
                 <p>Influencers are clustered according to their sphere of influence. 
                 There are 4 or more distinct clusters/phases on each spiral.
                 Number of clusters and cluster membership is algorithmically generated from the data.
                 
                 The sequence of nodes with/without an inner circle denotes membership to the same cluster.
                <br/> <br/>
                </p> 
                """,
                    width=850,
                    height=220)
    title_box = widgetbox(div_title, sizing_mode='scale_both', responsive=True)

    ## Tips Box::
    div_tips = Div(text="""
            <p>Hover over the nodes in order to see the details. <b>Ntweets</b>
             denotes the number of tweeters collected for the profiling, <b>per_tweet</b>
             denotes that scores are computed per tweet.</p>
      
            <p>A new influencer can be added. Address bar can be used to query an influencer
            whose profile is not analyzed yet. Note that a twitter user name is the part after @ sign.
            For instance, the Twitter user <i>@bulentozel</i> can be added by appending <b>bulentozel</b> to the URL:
            <i>BASE_URL/gui/bulentozel</i>
            </p>
            <p>To query the users whose profiling has already been included, the search bar below can be used. </p>
            """,
                   width=200,
                   height=350)
    tips_box = widgetbox(div_tips, sizing_mode='scale_both', responsive=True)

    ## Query Box::

    callback_search = CustomJS(args=dict(boardWin=board,
                                         infList=influencers,
                                         infWin=influencer,
                                         atr=influenceratr),
                               code="""
        var bWin = boardWin.data;
        var iWin = infWin.data;
        var iL = infList.data;
        var query = cb_obj.value;
        var d4 = atr.data;
        
        console.log(query);
        
        var ind = iL['names'].indexOf(query);
        if (ind >= 0){
            var start = ind;
            var end = iL['names'].lastIndexOf(query);
            
            iWin['x'] = [];
            iWin['y'] = [];
            iWin['sizes'] = [];
            iWin['scores'] = [];
            iWin['names'] = [];
            iWin['memes'] = [];
            iWin['colors'] = [];
            iWin['offsets'] = [];
            iWin['xsegments'] = [];
            iWin['ysegments'] = [];
            iWin['tweets'] = [];
            
            for (var i = start; i <= end; i++) {
                iWin['x'].push(iL['x'][i]);
                iWin['y'].push(iL['y'][i]);
                iWin['sizes'].push(iL['sizes'][i]);
                iWin['scores'].push(iL['scores'][i]);
                iWin['names'].push(iL['names'][i]);
                iWin['memes'].push(iL['memes'][i]);
                iWin['offsets'].push(iL['offsets'][i]);
                iWin['colors'].push(iL['colors'][i]);
                iWin['tweets'].push(iL['tweets'][i]);
                iWin['xsegments'].push(iL['xsegments'][i]);
                iWin['ysegments'].push(iL['ysegments'][i]);
            }
            
            ind = bWin['names'].indexOf(query);
            if (ind > 0){
                var blength = bWin['colors'].length;
                bWin['colors'] = []
                for (i = 0; i < blength; i++) {
                    bWin['colors'].push('turquoise');
                }
                bWin['colors'][ind] = 'olive'
            }
            d4['legend'] = [];
            d4['legend'].push(query);
        }
        boardWin.change.emit();
        infWin.change.emit();
        atr.change.emit();
    """)
    text_input = AutocompleteInput(completions=names,
                                   title="Search an influencer:")
    text_input.js_on_change('value', callback_search)
    query_box = widgetbox(text_input,
                          sizing_mode='stretch_both',
                          responsive=True)

    # Tabular Data

    ## Info Box::
    div_scorebord_info = Div(text="""
                    <h3>Spirometer Details</h3>
                    <p>Tap to column names in order to sort accordingly.
                    </p>
                    """,
                             width=750,
                             height=50)
    title_table = widgetbox(div_scorebord_info,
                            sizing_mode='scale_both',
                            responsive=True)

    Nformatter = NumberFormatter()
    Nformatter.format = "0,0.000"
    columns = [
        TableColumn(field="names", title="Name"),
        TableColumn(field="memes", title="Category"),
        TableColumn(field="scores", title="Score", formatter=Nformatter),
        TableColumn(field="tweets", title="Number of Tweets")
    ]
    data_table = DataTable(source=boards,
                           columns=columns,
                           width=820,
                           height=500)
    table_box = widgetbox(data_table,
                          sizing_mode='stretch_both',
                          responsive=True)

    # Figures only layout::::
    if ApiRequest:
        layoutAPI = column(fig_influencer, fig_board)
        return (layoutAPI)

    # Overall Layout::::
    layout = column(title_box, row(fig_influencer,
                                   column(tips_box, query_box)), fig_board,
                    title_table, table_box)

    return (layout)
Example #51
0
from bokeh.models.widgets import Button, RadioButtonGroup, Select, Slider, DataTable, TableColumn, DateFormatter
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, HoverTool, CDSView, GroupFilter
from bokeh.models import Span, LabelSet
from functions import *

#from bokeh.io import output_file, show, vform

app = Flask(__name__)

# create some widgets
#rating = Slider(start=0, end=10, value=1, step=.1, title="Slider")
button_group = RadioButtonGroup(labels=["Average", "O/5", "5/5"], active=0)
#base_line = Select(title="minimal target :", value="Target", options=["IBM", "bar", "baz", "quux"])

w = widgetbox(button_group, width=300)

# Create the main plot
#
x = list(range(11))
y0 = x

hover = HoverTool(tooltips=[
    ("Name", "@index"),
])

#TOOLS = "box_select,lasso_select,hover,help"
TOOLS = "crosshair,help,pan,box_zoom,reset,box_select,wheel_zoom,lasso_select"

target = 'Target'
#Create a dictionary with the values from the summary dataframe
data = dict(
    dates=summary_df.index,
    high=summary_df.high,
    low=summary_df.low,
    precip=summary_df.low,
)

#Convert the dictionary to column data source format to be read into the table
data = ColumnDataSource(data)

#Set the column titles
columns = [
    TableColumn(field="dates", title="Month"),
    TableColumn(field="high", title="Average High Temperature"),
    TableColumn(field="low", title="Average Low Temperature"),
    TableColumn(field="precip", title="Total Precipitation"),
]

#Create the data table
data_table = DataTable(source=data, columns=columns, width=1400, height=500)

#Set the layout of the graphs and table
l = layout([
    [p, p1],
    [widgetbox(data_table)],
], )

#Show the html file created from Bokeh
show(l)
Example #53
0
def xy_compare(series, width=200, size = 9, color = "#31AADE"):

    # Dict when lazy because of json encoding of arg
    if isinstance(series, dict):
        df = pd.DataFrame(series)
    else:
        df = pd.DataFrame(series.to_dict())

    columns = list(df.columns)
    initial_x_key = columns[0]
    initial_y_key = columns[1]

    df['x'] = df[initial_x_key]
    df['y'] = df[initial_y_key]

    source = ColumnDataSource(df)

    def create_figure():
        p = figure(plot_height=600, plot_width=800, tools='pan,box_zoom,hover,reset')
        p.circle(x='x', y='y', color=color, size=size, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5, source=source)
        return p

    callback_x = CustomJS(args=dict(source=source), code="""
            
            var data = source.data;
            var f = cb_obj.value;

            var x = data['x']
            var x_src = data[f]
            for (var i = 0; i < x.length; i++) {
                x[i] = x_src[i]
            }
            source.change.emit();
            """)


    x = Select(title='X-Axis', value=initial_x_key, options=columns)
    x.js_on_change('value', callback_x)

    callback_y = CustomJS(args=dict(source=source), code="""
            
            var data = source.data;
            var f = cb_obj.value;

            var y = data['y']
            var y_src = data[f]
            for (var i = 0; i < y.length; i++) {
                y[i] = y_src[i]
            }
            source.change.emit();
            """)

    y = Select(title='Y-Axis', value=initial_y_key, options=columns)
    y.js_on_change('value', callback_y)

    controls = widgetbox([x, y], width=width)
    layout = row(controls, create_figure())

    script, div = components(layout)

    html = ''.join([script, div]).replace('\n', '')
    x = 'console.log("Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing")'
    html = html.replace(x, x+';')

    return html
Example #54
0
'''Certain elements, like data, input_field (slection object) have to be defined outside of the make_plot function otherwise the update_plot function does not work.'''

with open(fileDir + '\\Data\\merged_visuals_data.json', 'r',
          encoding='utf-8') as f:
    json_data = json.load(f)
#
geosource = GeoJSONDataSource(geojson=json_data)

input_field = 'Median_price'

# Call the plotting function
p = make_plot(input_field)

# Make a selection object from which users can choose: select
select = Select(title='Select Criteria:',
                value='Price',
                options=['Price', 'Median Price', 'Price per Square Metre'])
select.on_change('value', update_plot)

# Make a column layout of widgetbox(slider) and plot, and add it to the current document
layout = column(p, widgetbox(select))

curdoc().add_root(layout)
# Display the current document
output_notebook()
show(p)

#bokeh serve --show Downloader.ipynb -in anaconda prompt shows interactive map in local server

# In[ ]:
Example #55
0
N = 10
x = np.linspace(0, 4 * np.pi, N)
y = np.sin(x)
options = dict(tools="", toolbar_location=None, plot_height=300, plot_width=300)

p1 = figure(title="Line (300 x 100)", **options)
p1.plot_height = 100
p1.line(x, y)

p2 = figure(title="Annular wedge (100 x 300)", title_location='right', **options)
p2.plot_width = 100
p2.annular_wedge(x, y, 10, 20, 0.6, 4.1, inner_radius_units="screen", outer_radius_units="screen")

p3 = figure(title="Bezier (300 x 300)", **options)
p3.bezier(x, y, x + 0.4, y, x + 0.1, y + 0.2, x - 0.1, y - 0.2)

p4 = figure(title="Quad (300 x 300)", **options)
p4.quad(x, x - 0.2, y, y - 0.2)

spacer_1 = Spacer(width=100, height=100)
spacer_2 = Spacer(width=300, height=100)
paragraph = Paragraph(text="We build up a grid plot manually. Try changing the mode yourself.")

MODE = 'fixed'
widgets = widgetbox([paragraph], sizing_mode=MODE)
row_1 = row([spacer_1, p1, spacer_2], sizing_mode=MODE)
row_2 = row([p2, p3, p4], sizing_mode=MODE)
layout = column([widgets, row_1, row_2], sizing_mode=MODE)

show(layout)
Example #56
0
        'date': df.date,
        'dep': df.dep,
        'lat': df.lat,
        'long': df.long,
        'mag': df.mag,
        'reg1': df.reg1,
        'reg2': df.reg2,
        'reg3': df.reg3
    }


columns = [
    TableColumn(field="id", title="id", width=55),
    TableColumn(field="date", title="date"),
    TableColumn(field="dep", title="depth", width=35),
    TableColumn(field="lat", title="lat", width=55),
    TableColumn(field="long", title="long", width=55),
    TableColumn(field="mag", title="magnitude", width=55),
    TableColumn(field="reg1", title="reg1"),
    TableColumn(field="reg2", title="reg2"),
    TableColumn(field="reg3", title="reg3")
]

data_table = DataTable(source=source, columns=columns, width=1280)
table = widgetbox(data_table)

curdoc().add_root(column(plot, table))
curdoc().title = "Earth Shaking ..."

update()
Example #57
0
    "July", "August", "September", "October", "November", "December"
],
                         active=0)


def monthSel(active):
    if active == 0:
        p2.x_range.start = MonthTimestamps[0]
        p2.x_range.end = MonthTimestamps[12]
    else:
        p2.x_range.start = MonthTimestamps[active - 1]
        p2.x_range.end = MonthTimestamps[active]


radio_group.on_click(monthSel)
dPickWidget = widgetbox(button)
blank = widgetbox(radio_group, width=400)
p1Widget = widgetbox(checkbox1)
p2Widget = widgetbox(checkbox2)
l = layout([[
    column(slider,
           row(datePickStart, datePickEnd, height=210),
           dPickWidget,
           width=400), p1, p1Widget
], [blank, p2, p2Widget]])

legend1 = Legend(legends=[("Mon", [l_mon]), ("Tue", [l_tue]), ("Wed", [l_wed]),
                          ("Thu", [l_thu]), ("Fri", [l_fri]), ("Sat", [l_sat]),
                          ("Sun", [l_sun]), ("Deviation", [l_std])],
                 location=(0, -5))
Example #58
0
def generate_plots(ulog, px4_ulog, flight_mode_changes, db_data):
    """ create a list of bokeh plots (and widgets) to show """

    plots = []
    data = ulog.data_list

    # Heading
    sys_name = ''
    if 'sys_name' in ulog.msg_info_dict:
        sys_name = cgi.escape(ulog.msg_info_dict['sys_name']) + ' '
    div = Div(text="<h1>" + sys_name + px4_ulog.get_mav_type() + "</h1>",
              width=int(plot_width * 0.9))
    header_divs = [div]
    if db_data.description != '':
        div_descr = Div(text="<h4>" + db_data.description + "</h4>",
                        width=int(plot_width * 0.9))
        header_divs.append(div_descr)

    # airframe
    table_text = []
    if 'SYS_AUTOSTART' in ulog.initial_parameters:
        sys_autostart = ulog.initial_parameters['SYS_AUTOSTART']
        airframe_data = get_airframe_data(sys_autostart)

        if airframe_data is None:
            table_text.append(('Airframe', str(sys_autostart)))
        else:
            airframe_type = ''
            if 'type' in airframe_data:
                airframe_type = ', ' + airframe_data['type']
            table_text.append(
                ('Airframe', airframe_data.get('name') + airframe_type +
                 ' <small>(' + str(sys_autostart) + ')</small>'))

    # HW & SW
    if 'ver_hw' in ulog.msg_info_dict:
        sys_hw = cgi.escape(ulog.msg_info_dict['ver_hw'])
        table_text.append(('Hardware', sys_hw))

    release_str = ulog.get_version_info_str()
    if release_str is None:
        release_str = ''
        release_str_suffix = ''
    else:
        release_str += ' <small>('
        release_str_suffix = ')</small>'
    if 'ver_sw' in ulog.msg_info_dict:
        ver_sw = cgi.escape(ulog.msg_info_dict['ver_sw'])
        ver_sw_link = 'https://github.com/PX4/Firmware/commit/' + ver_sw
        table_text.append(
            ('Software Version', release_str + '<a href="' + ver_sw_link +
             '" target="_blank">' + ver_sw[:8] + '</a>' + release_str_suffix))

    if 'sys_os_name' in ulog.msg_info_dict and 'sys_os_ver_release' in ulog.msg_info_dict:
        os_name = cgi.escape(ulog.msg_info_dict['sys_os_name'])
        os_ver = ulog.get_version_info_str('sys_os_ver_release')
        if os_ver is not None:
            table_text.append(('OS Version', os_name + ', ' + os_ver))

    table_text.append(('Estimator', px4_ulog.get_estimator()))
    # dropouts
    dropout_durations = [dropout.duration for dropout in ulog.dropouts]
    if len(dropout_durations) > 0:
        total_duration = sum(dropout_durations) / 1000
        if total_duration > 5:
            total_duration_str = '{:.0f}'.format(total_duration)
        else:
            total_duration_str = '{:.2f}'.format(total_duration)
        table_text.append(
            ('Dropouts', '{:} ({:} s)'.format(len(dropout_durations),
                                              total_duration_str)))

    # logging duration
    m, s = divmod(int((ulog.last_timestamp - ulog.start_timestamp) / 1e6), 60)
    h, m = divmod(m, 60)
    table_text.append(
        ('Logging duration', '{:d}:{:02d}:{:02d}'.format(h, m, s)))

    # Wind speed, rating, feedback
    if db_data.wind_speed >= 0:
        table_text.append(('Wind Speed', db_data.wind_speed_str()))
    if len(db_data.rating) > 0:
        table_text.append(('Flight Rating', db_data.rating_str()))
    if len(db_data.feedback) > 0:
        table_text.append(('Feedback', db_data.feedback.replace('\n',
                                                                '<br/>')))
    if len(db_data.video_url) > 0:
        table_text.append(('Video', '<a href="' + db_data.video_url +
                           '" target="_blank">' + db_data.video_url + '</a>'))

    # generate the table
    divs_text = '<table>' + ''.join([
        '<tr><td class="left">' + a + ':</td><td>' + b + '</td></tr>'
        for a, b in table_text
    ]) + '</table>'
    header_divs.append(Div(text=divs_text, width=int(plot_width * 0.9)))
    plots.append(widgetbox(header_divs, width=int(plot_width * 0.9)))

    # FIXME: for now, we use Google maps directly without bokeh, because it's not working reliably
    # GPS map
    #    gps_plots = []
    #    gps_titles = []
    #    plot = plot_map(ulog, plot_config, map_type='google', api_key =
    #            get_google_maps_api_key(), setpoints=False)
    #    plot = None
    #    if plot is not None:
    #        gps_plots.append(plot)
    #        gps_titles.append('GPS Map: Satellite')
    #
    #    plot = plot_map(ulog, plot_config, map_type='plain', setpoints=True)
    #    if plot is not None:
    #        gps_plots.append(plot)
    #        gps_titles.append('GPS Map: Plain')
    #
    #    data_plot = DataPlot2D(data, plot_config, 'vehicle_local_position',
    #        x_axis_label = '[m]', y_axis_label='[m]', plot_height='gps_map')
    #    data_plot.add_graph('y', 'x', colors2[0], 'Estimated')
    #    data_plot.change_dataset('vehicle_local_position_setpoint')
    #    data_plot.add_graph('y', 'x', colors2[1], 'Setpoint')
    #    if data_plot.finalize() is not None:
    #        gps_plots.append(data_plot.bokeh_plot)
    #        gps_titles.append('Local Position')
    #
    #
    #    if len(gps_plots) >= 2:
    #        tabs = []
    #        for i in range(len(gps_plots)):
    #            tabs.append(Panel(child=gps_plots[i], title=gps_titles[i]))
    #        gps_plot_height=plot_config['plot_height']['gps_map'] + 30
    #        plots.append(Tabs(tabs=tabs, width=plot_width, height=gps_plot_height))
    #    elif len(gps_plots) == 1:
    #        plots.extend(gps_plots)

    # Position plot
    data_plot = DataPlot2D(data,
                           plot_config,
                           'vehicle_local_position',
                           x_axis_label='[m]',
                           y_axis_label='[m]',
                           plot_height='gps_map')
    data_plot.add_graph('y',
                        'x',
                        colors2[0],
                        'Estimated',
                        check_if_all_zero=True)
    data_plot.change_dataset('vehicle_local_position_setpoint')
    data_plot.add_graph('y', 'x', colors2[1], 'Setpoint')
    # groundtruth (SITL only)
    data_plot.change_dataset('vehicle_local_position_groundtruth')
    data_plot.add_graph('y', 'x', color_gray, 'Groundtruth')
    # GPS + position setpoints
    plot_map(ulog,
             plot_config,
             map_type='plain',
             setpoints=True,
             bokeh_plot=data_plot.bokeh_plot)
    if data_plot.finalize() is not None:
        plots.append(data_plot.bokeh_plot)
        curdoc().template_variables['has_position_data'] = True

    # initialize parameter changes
    changed_params = None
    if not 'replay' in ulog.msg_info_dict:  # replay can have many param changes
        if len(ulog.changed_parameters) > 0:
            changed_params = ulog.changed_parameters
            plots.append(None)  # save space for the param change button

    ### Add all data plots ###

    # Altitude estimate
    data_plot = DataPlot(data,
                         plot_config,
                         'vehicle_gps_position',
                         y_axis_label='[m]',
                         title='Altitude Estimate',
                         changed_params=changed_params)
    data_plot.add_graph([lambda data: ('alt', data['alt'] * 0.001)],
                        colors8[0:1], ['GPS Altitude'])
    data_plot.change_dataset('sensor_combined')
    data_plot.add_graph(['baro_alt_meter'], colors8[1:2],
                        ['Barometer Altitude'])
    data_plot.change_dataset('vehicle_global_position')
    data_plot.add_graph(['alt'], colors8[2:3], ['Fused Altitude Estimation'])
    data_plot.change_dataset('position_setpoint_triplet')
    data_plot.add_circle(['current.alt'],
                         [plot_config['mission_setpoint_color']],
                         ['Altitude Setpoint'])
    data_plot.change_dataset('actuator_controls_0')
    data_plot.add_graph([lambda data: ('thrust', data['control[3]'] * 100)],
                        colors8[6:7], ['Thrust * 100'])
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

    #plot_dropouts(data_plot.bokeh_plot, ulog.dropouts)
    # TODO: call range update callback on startup when plot loaded...

    if data_plot.finalize() is not None: plots.append(data_plot)

    # Roll/Pitch/Yaw angle & angular rate
    for axis in ['roll', 'pitch', 'yaw']:

        # angle
        axis_name = axis.capitalize()
        data_plot = DataPlot(data,
                             plot_config,
                             'vehicle_attitude',
                             y_axis_label='[deg]',
                             title=axis_name + ' Angle',
                             plot_height='small',
                             changed_params=changed_params)
        data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))],
                            colors2[0:1], [axis_name + ' Estimated'])
        data_plot.change_dataset('vehicle_attitude_setpoint')
        data_plot.add_graph(
            [lambda data: (axis + '_d', np.rad2deg(data[axis + '_d']))],
            colors2[1:2], [axis_name + ' Setpoint'])
        data_plot.change_dataset('vehicle_attitude_groundtruth')
        data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))],
                            [color_gray], [axis_name + ' Groundtruth'])
        plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

        if data_plot.finalize() is not None: plots.append(data_plot)

        # rate
        data_plot = DataPlot(data,
                             plot_config,
                             'vehicle_attitude',
                             y_axis_label='[deg/s]',
                             title=axis_name + ' Angular Rate',
                             plot_height='small',
                             changed_params=changed_params)
        data_plot.add_graph(
            [lambda data: (axis + 'speed', np.rad2deg(data[axis + 'speed']))],
            colors2[0:1], [axis_name + ' Rate Estimated'])
        data_plot.change_dataset('vehicle_rates_setpoint')
        data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))],
                            colors2[1:2], [axis_name + ' Rate Setpoint'])
        data_plot.change_dataset('vehicle_attitude_groundtruth')
        data_plot.add_graph(
            [lambda data: (axis + 'speed', np.rad2deg(data[axis + 'speed']))],
            [color_gray], [axis_name + ' Rate Groundtruth'])
        plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

        if data_plot.finalize() is not None: plots.append(data_plot)

    # Local position
    for axis in ['x', 'y', 'z']:
        data_plot = DataPlot(data,
                             plot_config,
                             'vehicle_local_position',
                             y_axis_label='[m]',
                             title='Local Position ' + axis.upper(),
                             plot_height='small',
                             changed_params=changed_params)
        data_plot.add_graph([axis], colors2[0:1],
                            [axis.upper() + ' Estimated'])
        data_plot.change_dataset('vehicle_local_position_setpoint')
        data_plot.add_graph([axis], colors2[1:2], [axis.upper() + ' Setpoint'])
        plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

        if data_plot.finalize() is not None: plots.append(data_plot)

    # Velocity
    data_plot = DataPlot(data,
                         plot_config,
                         'vehicle_local_position',
                         y_axis_label='[m/s]',
                         title='Velocity',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(['vx', 'vy', 'vz'], colors3, ['x', 'y', 'z'])
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

    if data_plot.finalize() is not None: plots.append(data_plot)

    # raw radio control inputs
    data_plot = DataPlot(data,
                         plot_config,
                         'rc_channels',
                         title='Raw Radio Control Inputs',
                         plot_height='small',
                         y_range=Range1d(-1.1, 1.1),
                         changed_params=changed_params)
    num_rc_channels = 8
    if data_plot.dataset:
        max_channels = np.amax(data_plot.dataset.data['channel_count'])
        if max_channels < num_rc_channels: num_rc_channels = max_channels
    legends = []
    for i in range(num_rc_channels):
        channel_names = px4_ulog.get_configured_rc_input_names(i)
        if channel_names is None:
            legends.append('Channel ' + str(i))
        else:
            legends.append('Channel ' + str(i) + ' (' +
                           ', '.join(channel_names) + ')')
    data_plot.add_graph(
        ['channels[' + str(i) + ']' for i in range(num_rc_channels)],
        colors8[0:num_rc_channels], legends)
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

    if data_plot.finalize() is not None: plots.append(data_plot)

    # actuator controls 0
    data_plot = DataPlot(data,
                         plot_config,
                         'actuator_controls_0',
                         y_start=0,
                         title='Actuator Controls 0',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(
        ['control[0]', 'control[1]', 'control[2]', 'control[3]'], colors8[0:4],
        ['Roll', 'Pitch', 'Yaw', 'Thrust'])
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)
    if data_plot.finalize() is not None: plots.append(data_plot)

    # actuator outputs
    data_plot = DataPlot(data,
                         plot_config,
                         'actuator_outputs',
                         y_start=0,
                         title='Actuator Outputs',
                         plot_height='small',
                         changed_params=changed_params)
    num_actuator_outputs = 8
    if data_plot.dataset:
        max_outputs = np.amax(data_plot.dataset.data['noutputs'])
        if max_outputs < num_actuator_outputs:
            num_actuator_outputs = max_outputs
    data_plot.add_graph(
        ['output[' + str(i) + ']' for i in range(num_actuator_outputs)],
        colors8[0:num_actuator_outputs],
        ['Output ' + str(i) for i in range(num_actuator_outputs)])
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)

    if data_plot.finalize() is not None: plots.append(data_plot)

    # raw acceleration
    data_plot = DataPlot(data,
                         plot_config,
                         'sensor_combined',
                         y_axis_label='[m/s^2]',
                         title='Raw Acceleration',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph([
        'accelerometer_m_s2[0]', 'accelerometer_m_s2[1]',
        'accelerometer_m_s2[2]'
    ], colors3, ['x', 'y', 'z'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # raw angular speed
    data_plot = DataPlot(data,
                         plot_config,
                         'sensor_combined',
                         y_axis_label='[deg/s]',
                         title='Raw Angular Speed (Gyroscope)',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph([
        lambda data:
        ('gyro_rad[0]', np.rad2deg(data['gyro_rad[0]'])), lambda data:
        ('gyro_rad[1]', np.rad2deg(data['gyro_rad[1]'])), lambda data:
        ('gyro_rad[2]', np.rad2deg(data['gyro_rad[2]']))
    ], colors3, ['x', 'y', 'z'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # magnetic field strength
    data_plot = DataPlot(data,
                         plot_config,
                         'sensor_combined',
                         y_axis_label='[gauss]',
                         title='Raw Magnetic Field Strength',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(
        ['magnetometer_ga[0]', 'magnetometer_ga[1]', 'magnetometer_ga[2]'],
        colors3, ['x', 'y', 'z'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # distance sensor
    data_plot = DataPlot(data,
                         plot_config,
                         'distance_sensor',
                         y_start=0,
                         y_axis_label='[m]',
                         title='Distance Sensor',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(['current_distance', 'covariance'], colors3[0:2],
                        ['Distance', 'Covariance'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # gps uncertainty
    # the accuracy values can be really large if there is no fix, so we limit the
    # y axis range to some sane values
    data_plot = DataPlot(data,
                         plot_config,
                         'vehicle_gps_position',
                         title='GPS Uncertainty',
                         y_range=Range1d(0, 40),
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(
        ['eph', 'epv', 'satellites_used', 'fix_type'], colors8[::2], [
            'Horizontal position accuracy [m]',
            'Vertical position accuracy [m]', 'Num Satellites used', 'GPS Fix'
        ])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # gps noise & jamming
    data_plot = DataPlot(data,
                         plot_config,
                         'vehicle_gps_position',
                         y_start=0,
                         title='GPS Noise & Jamming',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(['noise_per_ms', 'jamming_indicator'], colors3[0:2],
                        ['Noise per ms', 'Jamming Indicator'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # thrust and magnetic field
    data_plot = DataPlot(data,
                         plot_config,
                         'sensor_combined',
                         y_start=0,
                         title='Thrust and Magnetic Field',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph([
        lambda data:
        ('len_mag',
         np.sqrt(data['magnetometer_ga[0]']**2 + data['magnetometer_ga[1]']**2
                 + data['magnetometer_ga[2]']**2))
    ], colors2[0:1], ['Norm of Magnetic Field'])
    data_plot.change_dataset('actuator_controls_0')
    data_plot.add_graph([lambda data: ('thrust', data['control[3]'])],
                        colors2[1:2], ['Thrust'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # power
    # TODO: dischared in Ah?
    data_plot = DataPlot(data,
                         plot_config,
                         'battery_status',
                         y_start=0,
                         title='Power',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph([
        'voltage_v', 'voltage_filtered_v', 'current_a', lambda data:
        ('discharged_mah', data['discharged_mah'] / 100)
    ], colors8[::2], [
        'Voltage  [V]', 'Voltage filtered [V]', 'Current [A]',
        'Discharged Amount [mAh / 100]'
    ])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # estimator watchdog
    data_plot = DataPlot(data,
                         plot_config,
                         'estimator_status',
                         y_start=0,
                         title='Estimator Watchdog',
                         plot_height='small',
                         changed_params=changed_params)
    data_plot.add_graph(['nan_flags', 'health_flags', 'timeout_flags'],
                        colors3, [
                            'NaN Flags', 'Health Flags (vel, pos, hgt)',
                            'Timeout Flags (vel, pos, hgt)'
                        ])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # RC Quality
    data_plot = DataPlot(data,
                         plot_config,
                         'input_rc',
                         title='RC Quality',
                         plot_height='small',
                         y_range=Range1d(0, 1),
                         changed_params=changed_params)
    data_plot.add_graph(['rc_lost', lambda data: ('rssi', data['rssi'] / 100)],
                        colors3[0:2], ['RC Lost', 'RSSI [0, 1]'])
    if data_plot.finalize() is not None: plots.append(data_plot)

    # cpu load
    data_plot = DataPlot(data,
                         plot_config,
                         'cpuload',
                         title='CPU & RAM',
                         plot_height='small',
                         y_range=Range1d(0, 1),
                         changed_params=changed_params)
    data_plot.add_graph(['ram_usage', 'load'], [colors3[1], colors3[2]],
                        ['RAM Usage', 'CPU Load'])
    data_plot.add_span('load', line_color=colors3[2])
    data_plot.add_span('ram_usage', line_color=colors3[1])
    plot_flight_modes_background(data_plot.bokeh_plot, flight_mode_changes)
    if data_plot.finalize() is not None: plots.append(data_plot)

    # sampling: time difference
    try:
        data_plot = DataPlot(data,
                             plot_config,
                             'sensor_combined',
                             y_start=0,
                             y_axis_label='[us]',
                             title='Sampling Regularity of Sensor Data',
                             plot_height='small',
                             changed_params=changed_params)
        sensor_combined = ulog.get_dataset('sensor_combined').data
        sampling_diff = np.diff(sensor_combined['timestamp'])
        min_sampling_diff = np.amin(sampling_diff)

        plot_dropouts(data_plot.bokeh_plot, ulog.dropouts, min_sampling_diff)

        data_plot.add_graph(
            [lambda data: ('timediff', np.append(sampling_diff, 0))],
            [colors3[2]], ['delta t (between 2 samples)'])
        if data_plot.finalize() is not None: plots.append(data_plot)
    except:
        pass

    # exchange all DataPlot's with the bokeh_plot and handle parameter changes

    param_changes_button = Button(label="Hide Parameter Changes", width=170)
    param_change_labels = []

    # FIXME: this should be a CustomJS callback, not on the server. However this
    # did not work for me.
    def param_changes_button_clicked():
        """ callback to show/hide parameter changes """
        for label in param_change_labels:
            if label.visible:
                param_changes_button.label = 'Show Parameter Changes'
                label.visible = False
                label.text_alpha = 0  # label.visible does not work, so we use this instead
            else:
                param_changes_button.label = 'Hide Parameter Changes'
                label.visible = True
                label.text_alpha = 1

    param_changes_button.on_click(param_changes_button_clicked)

    jinja_plot_data = []
    for i in range(len(plots)):
        if plots[i] is None:
            plots[i] = widgetbox(param_changes_button,
                                 width=int(plot_width * 0.99))
        if isinstance(plots[i], DataPlot):
            if plots[i].param_change_label is not None:
                param_change_labels.append(plots[i].param_change_label)
            plots[i] = plots[i].bokeh_plot

            plot_title = plots[i].title.text
            fragment = 'Nav-'+plot_title.replace(' ', '-') \
                .replace('&', '_').replace('(', '').replace(')', '')
            jinja_plot_data.append({
                'model_id': plots[i].ref['id'],
                'fragment': fragment,
                'title': plot_title
            })

    # log messages
    log_times = []
    log_levels = []
    log_messages = []
    for m in ulog.logged_messages:
        m1, s1 = divmod(int(m.timestamp / 1e6), 60)
        h1, m1 = divmod(m1, 60)
        log_times.append("{:d}:{:02d}:{:02d}".format(h1, m1, s1))
        log_levels.append(m.log_level_str())
        log_messages.append(m.message)
    log_data = dict(times=log_times, levels=log_levels, messages=log_messages)
    source = ColumnDataSource(log_data)
    columns = [
        TableColumn(field="times",
                    title="Time",
                    width=int(plot_width * 0.15),
                    sortable=False),
        TableColumn(field="levels",
                    title="Level",
                    width=int(plot_width * 0.1),
                    sortable=False),
        TableColumn(field="messages",
                    title="Message",
                    width=int(plot_width * 0.75),
                    sortable=False),
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=plot_width,
                           height=300,
                           sortable=False,
                           selectable=False)
    div = Div(text="""<b>Logged Messages</b>""", width=int(plot_width / 2))
    plots.append(widgetbox(div, data_table, width=plot_width))

    curdoc().template_variables['plots'] = jinja_plot_data

    return plots
Example #59
0
    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.title.text = "%d movies selected" % len(df)
    source.data = dict(
        x=df[x_name],
        y=df[y_name],
        color=df["color"],
        title=df["Title"],
        year=df["Year"],
        revenue=df["revenue"],
        alpha=df["alpha"],
    )

controls = [reviews, boxoffice, genre, min_year, max_year, oscars, director, cast, x_axis, y_axis]
for control in controls:
    control.on_change('value', lambda attr, old, new: update())

sizing_mode = 'fixed'  # 'scale_width' also looks nice with this example

inputs = widgetbox(*controls, sizing_mode=sizing_mode)
l = layout([
    [desc],
    [inputs, p],
], sizing_mode=sizing_mode)

update()  # initial load of the data

curdoc().add_root(l)
curdoc().title = "Movies"
Example #60
0
    def tool_handler(self, doc):
        from bokeh.layouts import row, column, widgetbox
        from bokeh.models.mappers import LinearColorMapper
        from bokeh.models import widgets
        from bokeh.plotting import figure

        if len(self.arr.shape) != 2:
            raise AnalysisError(
                'Cannot use the band tool on non image-like spectra')

        arr = self.arr
        x_coords, y_coords = arr.coords[arr.dims[0]], arr.coords[arr.dims[1]]

        default_palette = self.default_palette

        self.app_context.update({
            'bands': {},
            'center_float': None,
            'data': arr,
            'data_range': {
                'x': (np.min(x_coords.values), np.max(x_coords.values)),
                'y': (np.min(y_coords.values), np.max(y_coords.values)),
            },
            'direction_normal': True,
            'fit_mode': 'mdc',
        })

        figures, plots, app_widgets = self.app_context['figures'], self.app_context['plots'], \
                                      self.app_context['widgets']
        self.cursor = [
            np.mean(self.data_range['x']),
            np.mean(self.data_range['y'])
        ]

        self.color_maps['main'] = LinearColorMapper(default_palette,
                                                    low=np.min(arr.values),
                                                    high=np.max(arr.values),
                                                    nan_color='black')

        main_tools = ["wheel_zoom", "tap", "reset"]
        main_title = 'Band Tool: WARNING Unidentified'

        try:
            main_title = 'Band Tool: {}'.format(arr.S.label[:60])
        except:
            pass

        figures['main'] = figure(tools=main_tools,
                                 plot_width=self.app_main_size,
                                 plot_height=self.app_main_size,
                                 min_border=10,
                                 min_border_left=50,
                                 toolbar_location='left',
                                 x_axis_location='below',
                                 y_axis_location='right',
                                 title=main_title,
                                 x_range=self.data_range['x'],
                                 y_range=self.data_range['y'])
        figures['main'].xaxis.axis_label = arr.dims[0]
        figures['main'].yaxis.axis_label = arr.dims[1]
        figures['main'].toolbar.logo = None
        figures['main'].background_fill_color = "#fafafa"
        plots['main'] = figures['main'].image(
            [arr.values.T],
            x=self.app_context['data_range']['x'][0],
            y=self.app_context['data_range']['y'][0],
            dw=self.app_context['data_range']['x'][1] -
            self.app_context['data_range']['x'][0],
            dh=self.app_context['data_range']['y'][1] -
            self.app_context['data_range']['y'][0],
            color_mapper=self.app_context['color_maps']['main'])

        # add lines
        self.add_cursor_lines(figures['main'])
        band_lines = figures['main'].multi_line(xs=[],
                                                ys=[],
                                                line_color='white',
                                                line_width=1)

        def append_point_to_band():
            cursor = self.cursor
            if self.active_band in self.app_context['bands']:
                self.app_context['bands'][self.active_band]['points'].append(
                    list(cursor))
                update_band_display()

        def click_main_image(event):
            self.cursor = [event.x, event.y]
            if self.pointer_mode == 'band':
                append_point_to_band()

        update_main_colormap = self.update_colormap_for('main')

        POINTER_MODES = [
            (
                'Cursor',
                'cursor',
            ),
            (
                'Band',
                'band',
            ),
        ]

        FIT_MODES = [
            (
                'EDC',
                'edc',
            ),
            (
                'MDC',
                'mdc',
            ),
        ]

        DIRECTIONS = [
            (
                'From Bottom/Left',
                'forward',
            ),
            ('From Top/Right', 'reverse'),
        ]

        BAND_TYPES = [(
            'Lorentzian',
            'Lorentzian',
        ), (
            'Voigt',
            'Voigt',
        ), (
            'Gaussian',
            'Gaussian',
        )]

        band_classes = {
            'Lorentzian': band.Band,
            'Gaussian': band.BackgroundBand,
            'Voigt': band.VoigtBand,
        }

        self.app_context['band_options'] = []

        def pack_bands():
            packed_bands = {}
            for band_name, band_description in self.app_context['bands'].items(
            ):
                if not band_description['points']:
                    raise AnalysisError('Band {} is empty.'.format(band_name))

                stray = None
                try:
                    stray = float(band_description['center_float'])
                except (KeyError, ValueError, TypeError):
                    try:
                        stray = float(self.app_context['center_float'])
                    except Exception:
                        pass

                packed_bands[band_name] = {
                    'name': band_name,
                    'band': band_classes.get(band_description['type'],
                                             band.Band),
                    'dims': self.arr.dims,
                    'params': {
                        'amplitude': {
                            'min': 0
                        },
                    },
                    'points': band_description['points'],
                }

                if stray is not None:
                    packed_bands[band_name]['params']['stray'] = stray

            return packed_bands

        def fit(override_data=None):
            packed_bands = pack_bands()
            dims = list(self.arr.dims)
            if 'eV' in dims:
                dims.remove('eV')
            angular_direction = dims[0]
            if isinstance(override_data, xr.Dataset):
                override_data = normalize_to_spectrum(override_data)
            return fit_patterned_bands(
                override_data if override_data is not None else self.arr,
                packed_bands,
                fit_direction='eV' if self.app_context['fit_mode'] == 'edc'
                else angular_direction,
                direction_normal=self.app_context['direction_normal'])

        self.app_context['pack_bands'] = pack_bands
        self.app_context['fit'] = fit

        self.pointer_dropdown = widgets.Dropdown(label='Pointer Mode',
                                                 button_type='primary',
                                                 menu=POINTER_MODES)
        self.direction_dropdown = widgets.Dropdown(label='Fit Direction',
                                                   button_type='primary',
                                                   menu=DIRECTIONS)
        self.band_dropdown = widgets.Dropdown(
            label='Active Band',
            button_type='primary',
            menu=self.app_context['band_options'])
        self.fit_mode_dropdown = widgets.Dropdown(label='Mode',
                                                  button_type='primary',
                                                  menu=FIT_MODES)
        self.band_type_dropdown = widgets.Dropdown(label='Band Type',
                                                   button_type='primary',
                                                   menu=BAND_TYPES)

        self.band_name_input = widgets.TextInput(placeholder='Band name...')
        self.center_float_widget = widgets.TextInput(
            placeholder='Center Constraint')
        self.center_float_copy = widgets.Button(label='Copy to all...')
        self.add_band_button = widgets.Button(label='Add Band')

        self.clear_band_button = widgets.Button(label='Clear Band')
        self.remove_band_button = widgets.Button(label='Remove Band')

        self.main_color_range_slider = widgets.RangeSlider(start=0,
                                                           end=100,
                                                           value=(
                                                               0,
                                                               100,
                                                           ),
                                                           title='Color Range')

        def add_band(band_name):
            if band_name not in self.app_context['bands']:
                self.app_context['band_options'].append((
                    band_name,
                    band_name,
                ))
                self.band_dropdown.menu = self.app_context['band_options']
                self.app_context['bands'][band_name] = {
                    'type': 'Lorentzian',
                    'points': [],
                    'name': band_name,
                    'center_float': None,
                }

                if self.active_band is None:
                    self.active_band = band_name

                self.save_app()

        def on_copy_center_float():
            for band_name in self.app_context['bands'].keys():
                self.app_context['bands'][band_name][
                    'center_float'] = self.app_context['center_float']
                self.save_app()

        def on_change_active_band(attr, old_band_id, band_id):
            self.app_context['active_band'] = band_id
            self.active_band = band_id

        def on_change_pointer_mode(attr, old_pointer_mode, pointer_mode):
            self.app_context['pointer_mode'] = pointer_mode
            self.pointer_mode = pointer_mode

        def set_center_float_value(attr, old_value, new_value):
            self.app_context['center_float'] = new_value
            if self.active_band in self.app_context['bands']:
                self.app_context['bands'][
                    self.active_band]['center_float'] = new_value

            self.save_app()

        def set_fit_direction(attr, old_direction, new_direction):
            self.app_context['direction_normal'] = new_direction == 'forward'
            self.save_app()

        def set_fit_mode(attr, old_mode, new_mode):
            self.app_context['fit_mode'] = new_mode
            self.save_app()

        def set_band_type(attr, old_type, new_type):
            if self.active_band in self.app_context['bands']:
                self.app_context['bands'][self.active_band]['type'] = new_type

            self.save_app()

        def update_band_display():
            band_names = self.app_context['bands'].keys()
            band_lines.data_source.data = {
                'xs': [[p[0] for p in self.app_context['bands'][b]['points']]
                       for b in band_names],
                'ys': [[p[1] for p in self.app_context['bands'][b]['points']]
                       for b in band_names],
            }
            self.save_app()

        self.update_band_display = update_band_display

        def on_clear_band():
            if self.active_band in self.app_context['bands']:
                self.app_context['bands'][self.active_band]['points'] = []
                update_band_display()

        def on_remove_band():
            if self.active_band in self.app_context['bands']:
                del self.app_context['bands'][self.active_band]
                new_band_options = [
                    b for b in self.app_context['band_options']
                    if b[0] != self.active_band
                ]
                self.band_dropdown.menu = new_band_options
                self.app_context['band_options'] = new_band_options
                self.active_band = None
                update_band_display()

        # Attach callbacks
        self.main_color_range_slider.on_change('value', update_main_colormap)

        figures['main'].on_event(events.Tap, click_main_image)
        self.band_dropdown.on_change('value', on_change_active_band)
        self.pointer_dropdown.on_change('value', on_change_pointer_mode)
        self.add_band_button.on_click(
            lambda: add_band(self.band_name_input.value))
        self.clear_band_button.on_click(on_clear_band)
        self.remove_band_button.on_click(on_remove_band)
        self.center_float_copy.on_click(on_copy_center_float)
        self.center_float_widget.on_change('value', set_center_float_value)
        self.direction_dropdown.on_change('value', set_fit_direction)
        self.fit_mode_dropdown.on_change('value', set_fit_mode)
        self.band_type_dropdown.on_change('value', set_band_type)

        layout = row(
            column(figures['main']),
            column(
                widgetbox(
                    self.pointer_dropdown,
                    self.band_dropdown,
                    self.fit_mode_dropdown,
                    self.band_type_dropdown,
                    self.direction_dropdown,
                ), row(
                    self.band_name_input,
                    self.add_band_button,
                ), row(
                    self.clear_band_button,
                    self.remove_band_button,
                ), row(self.center_float_widget, self.center_float_copy),
                widgetbox(
                    self._cursor_info,
                    self.main_color_range_slider,
                )))

        doc.add_root(layout)
        doc.title = 'Band Tool'
        self.load_app()
        self.save_app()