示例#1
0
def test_layout_sizing_mode(sizing_mode):
    p1, p2, p3, p4 = figure(), figure(), figure(), figure()

    lyt.layout([[p1, p2], [p3, p4]], sizing_mode=sizing_mode)

    for p in p1, p2, p3, p4:
        assert p1.sizing_mode == sizing_mode
示例#2
0
文件: UI.py 项目: MikeWoodward/UT330B
    def time_tab(self):

        """The date and time setting and getting tab"""

        self.time_status = Div(text="", width=self.page_width)

        time_connect = Button(label='Connect to UT330',
                              button_type="success")

        time_disconnect = Button(label='Disconnect from UT330',
                                 button_type="success")

        time_get = Button(label='Get UT330 date and time',
                          button_type="success")

        self.time_compare = Div(text="", width=self.page_width)

        time_set = Button(label='Set the UT330 date and time',
                          button_type="success")

        time_connect.on_click(self.time_connect)
        time_disconnect.on_click(self.time_disconnect)
        time_get.on_click(self.time_get)
        time_set.on_click(self.time_set)

        l = layout([self.time_status],
                   [time_connect, time_disconnect],
                   [time_get, self.time_compare],
                   [time_set])

        return Panel(child=l, title="Date and time setting")
示例#3
0
    def create(self):
        for _ in range(self.num_cameras):
            cam = BokehEventViewerCamera(self)
            cam.enable_pixel_picker(self.num_waveforms)
            cam.create_view_widget()
            cam.update_view_widget()
            cam.add_colorbar()

            self.cameras.append(cam)
            self.camera_layouts.append(cam.layout)

        for iwav in range(self.num_waveforms):
            wav = BokehEventViewerWaveform(self)
            active_color = self.cameras[0].active_colors[iwav]
            wav.fig.select(name='line')[0].glyph.line_color = active_color
            wav.enable_time_picker()
            wav.create_view_widget()
            wav.update_view_widget()

            self.waveforms.append(wav)
            self.waveform_layouts.append(wav.layout)

        self.layout = layout([
            [column(self.camera_layouts), column(self.waveform_layouts)],
        ])
示例#4
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)
示例#5
0
def test_layout_simple():
    p1, p2, p3, p4 = figure(), figure(), figure(), figure()

    grid = layout([[p1, p2], [p3, p4]], sizing_mode='fixed')

    assert isinstance(grid, Column)
    for r in grid.children:
        assert isinstance(r, Row)
示例#6
0
def test_layout_nested():
    p1, p2, p3, p4, p5, p6 = figure(), figure(), figure(), figure(), figure(), figure()

    grid = layout([[[p1, p1], [p2, p2]], [[p3, p4], [p5, p6]]], sizing_mode='fixed')

    assert isinstance(grid, Column)
    for r in grid.children:
        assert isinstance(r, Row)
        for c in r.children:
            assert isinstance(c, Column)
    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
示例#8
0
def test_layout_nested():
    p1, p2, p3, p4, p5, p6 = figure(), figure(), figure(), figure(), figure(), figure()

    grid = lyt.layout([[[p1, p1], [p2, p2]], [[p3, p4], [p5, p6]]], sizing_mode='fixed')

    assert isinstance(grid, lyt.Column)
    for row in grid.children:
        assert isinstance(row, lyt.Row)
        for col in row.children:
            assert isinstance(col, lyt.Column)
示例#9
0
	def output_charts(self,name,period, bot,top,fast_k,fast_d):
		candlestick = self.candlestick(name)
		rsi = self.rsi(candlestick,period,bot,top)
		stoch_rsi = self.stoch_rsi(candlestick,period,fast_k,fast_d)
		macd = self.macd(candlestick)

		self.plot_results(candlestick,rsi,stoch_rsi,macd)

		l=layout([[candlestick], [rsi],[stoch_rsi],[macd]])
		output_file("charts/"+name.replace("/","")+".html",title="Crypto chart for "+name)
		#show(l)
		save(l)
示例#10
0
    def setup(self):
        self.log_format = "%(levelname)s: %(message)s [%(name)s.%(funcName)s]"
        kwargs = dict(config=self.config, tool=self)

        default_url = get_dataset_path("gamma_test.simtel.gz")
        EventSourceFactory.input_url.default_value = default_url
        self.reader = EventSourceFactory.produce(**kwargs)
        self.seeker = EventSeeker(self.reader, **kwargs)

        self.extractor = ChargeExtractorFactory.produce(**kwargs)
        self.cleaner = WaveformCleanerFactory.produce(**kwargs)

        self.r1 = CameraR1CalibratorFactory.produce(
            eventsource=self.reader,
            **kwargs
        )
        self.dl0 = CameraDL0Reducer(**kwargs)
        self.dl1 = CameraDL1Calibrator(
            extractor=self.extractor,
            cleaner=self.cleaner,
            **kwargs
        )

        self.viewer = BokehEventViewer(**kwargs)

        # Setup widgets
        self.viewer.create()
        self.viewer.enable_automatic_index_increment()
        self.create_previous_event_widget()
        self.create_next_event_widget()
        self.create_event_index_widget()
        self.create_goto_event_index_widget()
        self.create_event_id_widget()
        self.create_goto_event_id_widget()
        self.create_telid_widget()
        self.create_channel_widget()
        self.create_dl1_widgets()
        self.update_dl1_widget_values()

        # Setup layout
        self.layout = layout([
            [self.viewer.layout],
            [
                self.w_previous_event,
                self.w_next_event,
                self.w_goto_event_index,
                self.w_goto_event_id
            ],
            [self.w_event_index, self.w_event_id],
            [self.w_telid, self.w_channel],
            [self.wb_extractor]
        ])
示例#11
0
    def setup(self):
        self.log_format = "%(levelname)s: %(message)s [%(name)s.%(funcName)s]"

        self.reader = EventSource.from_config(parent=self)
        self.seeker = EventSeeker(self.reader, parent=self)

        self.extractor = ImageExtractor.from_name(
            self.extractor_product,
            parent=self
        )
        self.r1 = CameraR1Calibrator.from_eventsource(
            eventsource=self.reader,
            parent=self
        )
        self.dl0 = CameraDL0Reducer(parent=self)
        self.dl1 = CameraDL1Calibrator(
            extractor=self.extractor,
            parent=self
        )

        self.viewer = BokehEventViewer(parent=self)

        # Setup widgets
        self.viewer.create()
        self.viewer.enable_automatic_index_increment()
        self.create_previous_event_widget()
        self.create_next_event_widget()
        self.create_event_index_widget()
        self.create_goto_event_index_widget()
        self.create_event_id_widget()
        self.create_goto_event_id_widget()
        self.create_telid_widget()
        self.create_channel_widget()
        self.create_dl1_widgets()
        self.update_dl1_widget_values()

        # Setup layout
        self.layout = layout([
            [self.viewer.layout],
            [
                self.w_previous_event,
                self.w_next_event,
                self.w_goto_event_index,
                self.w_goto_event_id
            ],
            [self.w_event_index, self.w_event_id],
            [self.w_telid, self.w_channel],
            [self.wb_extractor]
        ])
示例#12
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
示例#13
0
文件: UI.py 项目: MikeWoodward/UT330B
    def device_data_tab(self):

        """Reading device data"""
        self.data_status = Div(text="", width=self.page_width)

        data_connect = Button(label='Connect to UT330',
                              button_type="success")
        data_read = Button(label='Read data',
                           button_type="success")
        data_write = Button(label='Write data to disk',
                            button_type="success")
        data_erase = Button(label='Erase data',
                            button_type="success")
        data_disconnect = Button(label='Disconnect from UT330',
                                 button_type="success")

        data_connect.on_click(self.data_connect)
        data_read.on_click(self.data_read)
        data_write.on_click(self.data_write)
        data_erase.on_click(self.data_erase)
        data_disconnect.on_click(self.data_disconnect)

        if self.device_connected:
            self.data_status.text = ('UT330 device connected. The Read, '
                                     'Write, Erase, and Disconnect buttons '
                                     'will work.')
        else:
            self.data_status.text = ('UT330 device is <strong>NOT</strong> '
                                     'connected. The '
                                     'Read, Write, Erase, and Disconnect '
                                     'buttons will <strong>not work</strong>. '
                                     'Press the '
                                     'Connect button if the UT330 is '
                                     'connected on a USB port.')

        # Layout
        l = layout([[self.data_status],
                    [data_connect, data_disconnect],
                    [data_read, data_write, data_erase]],
                   width=self.page_width)

        return Panel(child=l,
                     title="Read from device")
示例#14
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,
                                     )
示例#15
0
    def makedoc(doc):
        source = ColumnDataSource(dataframe)
        prepare_xy(source, settings)  # get the default embedding columns
        embed = embedding(source, settings)
        image_plot, image_holder = selected_images()
        table = empty_table(dataframe)
        controls = [button_save_table(table), button_print_page()]
        radio_buttons = switch_embeddings_button_group(settings)

        def load_selected(attr, old, new):
            """Update images and table to display selected data."""
            print('new index: ', new)
            # Update images & table
            if len(new) == 1:  # could be empty selection
                update_image_canvas_single(new[0], data=dataframe,
                                           source=image_holder)
            elif len(new) > 1:
                update_image_canvas_multi(new, data=dataframe,
                                          source=image_holder)
            reset_plot_axes(image_plot)  # effectively resets zoom level
            update_table(new, dataframe, table)

        def new_embedding(attr, old, new):
            embedding = list(settings['embeddings'])[radio_buttons.active]
            update_embedding(source, embedding, settings)

        source.selected.on_change('indices', load_selected)
        radio_buttons.on_change('active', new_embedding)

        page_content = layout([
            radio_buttons,
            [embed, image_plot],
            controls,
            [table]
            ], sizing_mode="scale_width")
        doc.title = 'Bokeh microscopium app'
        doc.add_root(page_content)
示例#16
0
def gapminder_plot_bokeh(datos_e,
                         datos_pca,
                         year_i,
                         X_data_df,
                         grad_per,
                         etiquetas_glo,
                         periodos_incluir,
                         k,
                         imp_periods_var,
                         centroids_ite,
                         scaler_es,
                         title='Titulo',
                         xlabel='Eje x',
                         ylabel='Eje y'):

    ### Lista years
    years_plot = []
    for o in range(periodos_incluir + 1):
        years_plot.append(year_i + o)

    ### Dataframes necesarias
    pca1 = pd.DataFrame(columns=years_plot)
    pca2 = pd.DataFrame(columns=years_plot)

    ### PCA de cada year
    for year in years_plot:
        filtro = datos_e['Date'] == year

        ### Los que usare para el PCA seran
        X_data_pca_y = np.array(datos_pca[filtro])

        pca1[year] = X_data_pca_y[:, 0]
        pca2[year] = X_data_pca_y[:, 1]

    ### Nombres de los individuos
    pca1.index = X_data_df.country
    pca2.index = X_data_df.country

    ### Grados de pertenencia
    grados_pert = pd.DataFrame(columns=years_plot)

    ##### Grados de pertenencia de cada year
    coun = 0
    for year in years_plot:
        grados_pert[year] = np.max(
            grad_per[coun],
            axis=1) * 40  ### Aumento escala para que se vean bien
        coun = coun + 1
    grados_pert.index = X_data_df.country

    ##### Cluster al que pertenece cada dato en cada periodo de tiempo
    etiqs_plot = []
    couu = 0
    for year in years_plot:
        eti = pd.DataFrame()
        eti['region'] = [str(i)[0] for i in list(etiquetas_glo[couu])
                         ]  ### Solo 1 caracter
        eti.index = X_data_df.country

        etiqs_plot.append(eti)
        couu = couu + 1

    ##### Regions_list son los id de los cluster
    regions_list = []
    for cu in range(k):
        regions_list.append(str(cu))

    ### fertility df seria componente principal 1
    ### life expectancy df seria componente principal 2
    ### population_df_size es el maximo grado de pertenencia
    ### regions_df es el cluster id al que se asigno cada uno
    ### years es la lista de years a modelar
    ### regions list seria el "nombre " de cada cluster (top variables mas importantes)

    ### Consolidar data
    df = pd.concat(
        {
            'Componente_1': pca1,
            'Componente_2': pca2,
            'Grado_Pertenencia': grados_pert
        },
        axis=1)

    ### Construir data
    data = {}

    counta = 0
    for year in years_plot:
        df_year = df.iloc[:, df.columns.get_level_values(1) == year]
        df_year.columns = df_year.columns.droplevel(1)
        data[year] = df_year.join(
            etiqs_plot[counta].region).reset_index().to_dict('series')
        counta = counta + 1

    source = ColumnDataSource(data=data[years_plot[0]])

    ############### Para las labels ########################

    #### Numero de variables a plotear
    num_v_plot = 4

    #### Nombres variables
    nomb_v = datos_e.columns[2:]

    #### Desestandarizar centroides
    centroids_ito = scaler_es.inverse_transform(centroids_ite)

    #### Consolidar strings de las legends de cada iteracion
    strings_legends = []
    c = 0
    for y in years_plot:
        esta_iter = []
        estas_imp = imp_periods_var[c]
        cc = 0
        for clu in estas_imp:
            ### Variables mas importantes
            orden_v = np.argsort(clu)[::-1][:num_v_plot]

            ### Construir string
            stri = ''

            ### Numero observaciones cluster
            stri = stri + 'Num_obs: ' + str(
                len(np.where(etiquetas_glo[c] == cc)[0])) + ', '

            ### Variables importantes
            for i in orden_v:
                stri = stri + nomb_v[i][:12] + ': ' + str(
                    np.around(centroids_ito[c][cc][i], 2)) + ', '
            stri = stri[:-2]
            esta_iter.append(stri)
            cc = cc + 1
        strings_legends.append(esta_iter)
        c = c + 1

    #### PLoteos
    global plot
    plot = figure(title=title,
                  y_range=(-5, 7),
                  plot_height=520,
                  plot_width=900)
    plot.xaxis.ticker = SingleIntervalTicker(interval=1)
    plot.xaxis.axis_label = xlabel
    plot.yaxis.ticker = SingleIntervalTicker(interval=20)
    plot.yaxis.axis_label = ylabel

    label = Label(x=1.1,
                  y=18,
                  text=str(years_plot[0]),
                  text_font_size='70pt',
                  text_color='#eeeeee')
    plot.add_layout(label)

    color_mapper = CategoricalColorMapper(palette=Spectral6,
                                          factors=regions_list)
    global r

    r = plot.circle(
        x='Componente_1',
        y='Componente_2',
        size='Grado_Pertenencia',
        source=source,
        fill_color={
            'field': 'region',
            'transform': color_mapper
        },
        fill_alpha=0.8,
        line_color='#7c7e71',
        line_width=0.5,
        line_alpha=0.5,
        #        legend_group='region',
    )

    from bokeh.models import Legend, LegendItem

    global legend

    items_son = []
    co = 0
    for a in strings_legends[0]:
        color_ = list(etiquetas_glo[0]).index(co)
        items_son.append(LegendItem(label=a, renderers=[r], index=color_))
        co = co + 1

    legend = Legend(items=items_son)
    plot.add_layout(legend)

    plot.add_tools(
        HoverTool(tooltips="@country",
                  show_arrow=False,
                  point_policy='follow_mouse'))

    def animate_update():
        year = slider.value + 1
        if year > years_plot[-1]:
            year = years_plot[0]
        slider.value = year

    def slider_update(attrname, old, new):
        year = slider.value
        label.text = str(year)
        source.data = data[year]
        pos = years_plot.index(year)
        global legend
        global r
        global plot

        items_son = []
        bo = 0
        for a in strings_legends[pos]:
            color_ = list(etiquetas_glo[pos]).index(bo)
            items_son.append(LegendItem(label=a, renderers=[r], index=color_))
            bo = bo + 1
        legend.items = items_son
        plot.add_layout(legend)

    slider = Slider(start=years_plot[0],
                    end=years_plot[-1],
                    value=years_plot[0],
                    step=1,
                    title="Year")
    slider.on_change('value', slider_update)

    callback_id = None

    def animate():
        global callback_id
        if button.label == '► Play':
            button.label = '❚❚ Pause'
            callback_id = curdoc().add_periodic_callback(animate_update, 1000)
        else:
            button.label = '► Play'
            curdoc().remove_periodic_callback(callback_id)

    button = Button(label='► Play', width=60)
    button.on_click(animate)

    layout_plot = layout([
        [plot],
        [slider, button],
    ])

    curdoc().add_root(layout_plot)
    curdoc().title = "Gapminder"

    return None
示例#17
0
 def build_layout(list_of_columns):
     return layout(list_of_columns)
示例#18
0
    # Alarmas
    for index, _ in enumerate(warning_devices):
        warning_devices[index]['cooldown'] -= 1

        if warning_devices[index]['cooldown'] <= 0:
            warning_devices.remove(warning_devices[index])
            changeWarningList()

    if not warning_devices:
        alarm.visible = False
        alarm_list.visible = False

    t += 1


layout = layout([[fig_tanque3, fig_tanque4], [fig_tanque1, fig_tanque2],
                 [fig_vol1, fig_vol2]])

panel1 = Panel(child=row(
    Column(
        label1,
        row(Column(dataRecordingButton, dataRecordingLabel),
            Column(extensionsDropdown)), refEst1, refEst2,
        row(Column(valvula1Label, Kp1, Ki1, Kd1, Kw1),
            Column(valvula2Label, Kp2, Ki2, Kd2, Kw2)),
        row(alarm, alarm_list)), layout),
               title='Modo Automático')
panel2 = Panel(child=row(
    Column(
        label2,
        row(Column(dataRecordingButton, dataRecordingLabel),
            Column(extensionsDropdown)),
示例#19
0
def sim():
    #VARIABLE INITIALIZATION

    #CLINICAL VARIABLES

    #Glucose level/concentration of the blood in mg/dL
    glucose_blood_level = 100.0
    
    #Glucose present in the blood in mg
    glucose_blood = 4617.5
    
    #Glycogen stored in the liver in mg
    glycogen_liver = 100000
    
    #Glycogen stored in the muscles in mg
    glycogen_muscles = 500000

    #Insulin present in the blood in μU/mL
    insulin_blood = 15.0

    #Glucagon present in the blood in in pg/mL
    glucagon_blood = 20.00

    #Amount of mg of carbohydrate that one unit of insulin will metabolize/cover
    carb_insulin_ratio = 15000

    #Grams of glycogen that one unit/one pg of glucagon will release
    #NOT FACTUAL, FOR SIMULATION TESTING PURPOSES ONLY
    glycogenolysis_ratio = 1

    #Grams of glycogen that one gram of glucose will synthesize
    #NOT FACTUAL, FOR SIMULATION TESTING PURPOSES ONLY
    glycogenesis_ratio = 1

    #Grams of glucose released from one gram of glycogen
    #NOT FACTUAL, FOR SIMULATION TESTING PURPOSES ONLY
    glycogen_to_glucose_ratio = 1

    #Nonessential (burnable) fat stored in adipose tissue in grams
    fat_nonessential = 16983.0

    #Essential (non-burnable) fat stored in adipose tissue in grams
    fat_essential = 2830.0

    #Total fat in adipose tissue in grams
    fat_total = 19813.0

    #Number used to represent metabolic activity of the body
    #NOT FACTUAL, FOR SIMULATION OF METABOLIC ACTIVITY
    #TO ENHANCE REALISM OF SIMULATION ONLY
    metabolic_rate = 3

    #Volume of blood in dL
    blood_volume = 46.175

    #Insulin Sensitivity
    insulin_sensitivity = 1

    currentTime = 0






    #DATA FOR GRAPHING

    #Blood Glucose Level
    bgDataX = []
    bgDataY = []

    #Blood Glucose Level within target range (crrently unused)
    bgNormDataX = []
    bgNormDataY = []

    #Blood Glucose Level higher than tgarget range (currently unused)
    bgHighDataX = []
    bgHighDataY = []

    #Blood GLucose Level lower than target range (currently unused)
    bgLowDataX = []
    bgLowDataY = []

    #Blood Insulin Concentration
    insulinDataX = []
    insulinDataY = []

    #Blood Glucagon Concentration
    glucagonDataX = []
    glucagonDataY = []

    #Rate of Change Prediction
    ROC_predictionX = []
    ROC_predictionY = []

    #Metabolic Rate
    metabolic_rateX = []
    metabolic_rateY = []

    #GLycogen in liver
    glycogenDataX = []
    glycogenDataY = []



    #Loop the program forever.
    while(1==1):

        #CALCULATE NUMBERS


        currentTime+=1
        #currentTime = str(datetime.now())
        #currentTime = currentTime.replace("-", "")
        #currentTime = currentTime.replace(":", "")
        #currentTime = currentTime.replace(".", "")
        #currentTime = currentTime.replace(" ", "")

        #glucose_blood_level = (glucose_blood_level - insulin_blood + (glucagon_blood*12.5) - (metabolic_rate))
        #- (carb_insulin_ratio*insulin_blood) + (glycogenolysis_ratio*glucagon_blood*glycogen_to_glucose_ratio))
        if glycogen_liver > 0:
            #Release glycogen & convert to glucose
            glycogen_liver -= (glucagon_blood*glycogenolysis_ratio)
            glucose_blood += (glucagon_blood*glycogenolysis_ratio*glycogen_to_glucose_ratio)

        if glycogen_liver < 100000:
            #Absorb glucose & convert to glycogen
            glycogen_liver += ((insulin_blood/1000000)*carb_insulin_ratio*glycogenesis_ratio)
            glucose_blood -= ((insulin_blood/1000000*blood_volume/10)*carb_insulin_ratio)
    
        glucose_blood -= metabolic_rate*10
        glucose_blood_level = (glucose_blood/blood_volume)
        #glycogen_liver -+ (insulin_blood*
        #insulin_blood = insulin_blood - insulin_blood
        #glucagon_blood = glucagon_blood - glucagon_blood
        if glucose_blood_level < 0.0:
            glucose_blood_level = 0.0


        insulinDataX.append(currentTime)
        insulinDataY.append(insulin_blood)

        glucagonDataX.append(currentTime)
        glucagonDataY.append(glucagon_blood)

        bgDataX.append(currentTime)
        bgDataY.append(glucose_blood_level)

        metabolic_rateX.append(currentTime)
        metabolic_rateY.append(metabolic_rate)

        glycogenDataX.append(currentTime)
        glycogenDataY.append(glycogen_liver)

        #nan = float('nan')


        if glucose_blood_level >= 80 and glucose_blood_level <= 180:
            bgNormDataX.append(currentTime)
            bgNormDataY.append(glucose_blood_level)

        if glucose_blood_level > 180:
            bgHighDataX.append(currentTime)
            bgHighDataY.append(glucose_blood_level)

        if glucose_blood_level < 80:
            bgLowDataX.append(currentTime)
            bgLowDataY.append(glucose_blood_level)


        if len(bgDataX) >=3:
            bgRateOfChange = ((bgDataY[-1] - bgDataY[-2]) + (bgDataY[-2] - bgDataY[-3]))/2
            #Steady

            #ROC Prediction
            ROC_predictionX = []
            ROC_predictionY = []
            iterations = 1
            for x in range (0,6):
                ROC_predictionX.append(currentTime + iterations)
                ROC_predictionY.append(glucose_blood_level + (bgRateOfChange*iterations))
                iterations += 1

            if bgRateOfChange < 1 and bgRateOfChange > -1:
                ROC_arrows_WB = "→"
                ROC_arrows = "-> steady"

            #Rising
            if bgRateOfChange >= 1 and bgRateOfChange < 2:
                ROC_arrows_WB = "↗"
                ROC_arrows = "/^ slowly rising"
            if bgRateOfChange >= 2 and bgRateOfChange > 3:
                ROC_arrows_WB = "↑"
                ROC_arrows = "^|^ rising"
            if bgRateOfChange >= 3:
                ROC_arrows_WB = "⇈"
                ROC_arrows = "^|^ ^|^ rapidly rising"

            #Falling
            if bgRateOfChange <= -1 and bgRateOfChange > -2:
                ROC_arrows_WB = "↘"
                ROC_arrows = "\\v slowly falling"
            if bgRateOfChange <= -2 and bgRateOfChange > -3:
                ROC_arrows_WB = "↓"
                ROC_arrows = "v|v falling"
            if bgRateOfChange <= -3:
                ROC_arrows_WB = "⇊  RAPIDLY FALLING!"
                ROC_arrows = "v|v v|v RAPIDLY FALLING /!\\"
        else:
            bgRateOfChange = 0
            ROC_arrows_WB = "N/A"
            ROC_arrows = "N/A"
            
        
        ROC_widget = Paragraph(text=ROC_arrows_WB, width=50, height=25)



        #UPDATE DISPLAY

        #Clear the terminal window
        if sysPlatform() == "Windows":
            osSystem('cls')

        else:
            osSystem("clear")
    


        #Print basic textual UI to the terminal window
        print ("Diabetes/Body Energy Simulation Project")
        print ("2015 - 2016, created by John Kozlosky")
        print ("")
        print ("Blood glucose level: " + str(round(glucose_blood_level, 2)) + "mg/dL " + ROC_arrows)
        print ("Blood glucose: " + str(round((glucose_blood/1000), 2)) + "g")
        print ("Glycogen: " + str(round((glycogen_liver/1000), 2)) + "g hepatic, " + str(round(glycogen_muscles, 2)/1000) + "g muscular")
        print ("Blood insulin: " + str(round(insulin_blood, 2)) + "uU/mL")
        print ("Blood glucagon: " + str(round(glucagon_blood, 2)) + "pg/mL")
        #print ("Fat: " + str(round(fat_total)) + "g total, " + str(round(fat_nonessential)) + "g nonessential, " + str(round(fat_essential)) + "g essential")
        print ("Metabolic activity level: " + str(round(metabolic_rate, 4)))
        print ("")



        #Make graphs using Bokeh
        #Blood glucose level
        if len(bgDataX) >= 100:
            bgGraph = figure()#x_axis_type="datetime")
            bgGraph.line(bgDataX[-100:], bgDataY[-100:], color = "black")
            bgGraph.circle(bgDataX[-100:], bgDataY[-100:], fill_color = "white", line_color = "black", size = 8)
            bgGraph.circle(ROC_predictionX, ROC_predictionY, fill_color = "white", line_color = "gray", size = 8)
            #bgGraph.circle(bgNormDataX[0,100], bgNormDataY[0,100], fill_color = "white", line_color = "black", size = 8)
            #bgGraph.circle(bgHighDataX[0,100], bgNormDataY[0,100], fill_color = "white", line_color = "yellow", size = 8)
            #bgGraph.circle(bgLowDataX[0,100], bgLowDataY[0,100], fill_color = "white", line_color = "red", size = 8)
            bgGraph.title.text = "Blood Glucose"
            bgGraph.xaxis.axis_label = "Time"
            bgGraph.yaxis.axis_label = "Blood Glucose (mg/dL)"
            #bgGraph.yaxis.bounds = (0, 400)

        else:
            bgGraph = figure()#x_axis_type="datetime")
            bgGraph.line(bgDataX, bgDataY, color = "black")
            bgGraph.circle(bgDataX, bgDataY, fill_color = "white", line_color = "black", size = 8)
            bgGraph.circle(ROC_predictionX, ROC_predictionY, fill_color = "white", line_color = "gray", size = 8)
            #bgGraph.circle(bgNormDataX, bgNormDataY, fill_color = "white", line_color = "black", size = 8)
            #bgGraph.circle(bgHighDataX, bgNormDataY, fill_color = "white", line_color = "yellow", size = 8)
            #bgGraph.circle(bgLowDataX, bgLowDataY, fill_color = "white", line_color = "red", size = 8)
            bgGraph.title.text = "Blood Glucose"
            bgGraph.xaxis.axis_label = "Time"
            bgGraph.yaxis.axis_label = "Blood Glucose (mg/dL)"
            #bgGraph.yaxis.bounds = (0, 400)

        #Insulin
        if len(insulinDataX) >= 100:
            insulinGraph = figure()#x_axis_type="datetime")
            insulinGraph.line(insulinDataX[-100:], insulinDataY[-100:], color = "CadetBlue")
            insulinGraph.circle(insulinDataX[-100:], insulinDataY[-100:], fill_color = "white", line_color = "CadetBlue", size = 8)
            insulinGraph.title.text = "Insulin"
            insuinGraph.xaxis.axis_label = "Time"
            insulinGraph.yaxis.axis_label = "Blood Insulin (μU/mL)"
            #insulinGraph.yaxis.bounds = (0, 400)

        else:
            insulinGraph = figure()#x_axis_type="datetime")
            insulinGraph.line(insulinDataX, insulinDataY, color = "CadetBlue")
            insulinGraph.circle(insulinDataX, insulinDataY, fill_color = "white", line_color = "CadetBlue", size = 8)
            insulinGraph.title.text = "Insulin"
            insulinGraph.xaxis.axis_label = "Time"
            insulinGraph.yaxis.axis_label = "Blood Insulin (μU/mL)"
            #insulinGraph.yaxis.bounds = (0, 400)

        #Glucagon
        if len(glucagonDataX) >= 100:
            glucagonGraph = figure()#x_axis_type="datetime"
            glucagonGraph.line(glucagonDataX[-100:], glucagonDataY[-100:], color = "GoldenRod")
            glucagonGraph.circle(glucagonDataX[-100:], glucagonDataY[-100:], fill_color = "white", line_color = "GoldenRod", size = 8)
            glucagonGraph.title.text = "Glucagon"
            glucagonGraph.xaxis.axis_label = "Time"
            glucagonGraph.yaxis.axis_label = "Blood Glucagon (pg/mL)"
            #glucagonGraph.yaxis.bounds = (0, 700)

        else:
            glucagonGraph = figure()#x_axis_type="datetime")
            glucagonGraph.line(glucagonDataX, glucagonDataY, color = "GoldenRod")
            glucagonGraph.circle(glucagonDataX, glucagonDataY, fill_color = "white", line_color = "GoldenRod", size = 8)
            glucagonGraph.title.text = "Glucagon"
            glucagonGraph.xaxis.axis_label = "Time"
            glucagonGraph.yaxis.axis_label = "Blood Glucagon (pg/mL)"
            #glucagonGraph.yaxis.bounds = (0, 700)

        #Metabolic rate
        if len(metabolic_rateX) >= 100:
            metabolicGraph = figure()
            metabolicGraph.line(metabolic_rateX[-100:], metabolic_rateY[-100:], color = "black")
            metabolicGraph.circle(metabolic_rateX[-100:], metabolic_rateY[-100:], fill_color = "white", line_color = "black", size = 8)
            metabolicGraph.title.text = "Metabolic Rate"
            metabolicGraph.xaxis.axis_label = "Time"
            metabolicGraph.yaxis.axis_label = "Metabolic Rate (simulated number)"

        else:
            metabolicGraph = figure()
            metabolicGraph.line(metabolic_rateX, metabolic_rateY, color = "black")
            metabolicGraph.circle(metabolic_rateX, metabolic_rateY, fill_color = "white", line_color = "black", size = 8)
            metabolicGraph.title.text = "Metabolic Rate"
            metabolicGraph.xaxis.axis_label = "Time"
            metabolicGraph.yaxis.axis_label = "Metabolic Rate (simulated number)"
        
        #Hepatic Glycogen
        if len(glycogenDataX) >= 100:
            glycogenGraph = figure()
            glycogenGraph.line(glycogenDataX[-100:], glycogenDataY[-100:], color = "black")
            glycogenGraph.circle(glycogenDataX[-100:], glycogenDataY[-100:], fill_color = "white", line_color = "black", size = 8)
            glycogenGraph.title.text = "Hepatic Glycogen"
            glycogenGraph.xaxis.axis_label = "Time"
            glycogenGraph.yaxis.axis_label = "Hepatic Glycogen (mg)"

        else:
            glycogenGraph = figure()
            glycogenGraph.line(glycogenDataX, glycogenDataY, color = "black")
            glycogenGraph.circle(glycogenDataX, glycogenDataY, fill_color = "white", line_color = "black", size = 8)
            glycogenGraph.title.text = "Hepatic Glycogen"
            glycogenGraph.xaxis.axis_label = "Time"
            glycogenGraph.yaxis.axis_label = "Hepatic Glycogen (mg)"

        #Combine the blood glucose, insulin, and glucagon graphs into a grid
        #grid = gridplot([bgGraph, insulinGraph, glucagonGraph], ncols=2, plot_width=600, plot_height=350)

        grid = layout([
          [bgGraph],
          [insulinGraph, glucagonGraph],
          [metabolicGraph, glycogenGraph],
          [widgetbox(ROC_widget)],
        ], sizing_mode='stretch_both')

        #Write the graphs to an HTML file
        output_file('infoGraph.html')



        #GET USER COMMAND

        command = str(input(">"))

        if command == "set bg":
            glucose_blood = float(input("New blood glucose: "))*blood_volume

        if command == "set insulin":
            insulin_blood = float(input("New insulin level: "))

        if command == "set glucagon":
            glucagon_blood = float(input("New glucagon level: "))

        if command == "set glycogen_liver":
            glycogen_liver = float(input("New hapatic glycogen level: "))

        if command == "set glycogen_muscles":
            glycogen_muscles = float(input("New muscular glycogen level: "))

        if command == "set fat_total":
            fat_total = float(input("New total fat: "))

        if command == "set fat_nonessential":
            fat_nonessential = float(input("New nonessential fat: "))

        if command == "set fat_essential":
            fat_essential = float(input("New essential fat: "))

        if command == "set metabolic_rate":
            metabolic_rate = float(input("New metabolic activity level: "))

        if command == "set blood_volume":
            blood_volume = float(input("New blood volume: "))

        #if command == "inject bolus":
            #bolus = float(input("Novolog bolus size (U): "))

        #if command == "ingest carb":
            #carb = float(input("Ingest carbs (g): "))

        if command == "show":
            show(grid)

        if command == "exit":
            if input("Are you sure you want to exit? (y/n): ") == "y":
                exit()


        if command == "help":
            print("SIMULATION CONTROL")
            print("-----------------------")
            print("set bg - set new value for blood glucose level")
            print("set insulin - set new value for blood insulin level")
            print("set glucagon - set new value for blood glucagon level")
            print("set glycogen_liver - set new value for glycogen in liver")
            print("set glycogen_muscles - set new value for glycogen in muscles")
            print("set metabolic_rate - set metabolic activity level")
            print("")
            print("OTHER")
            print("----------------------")
            print("help - show this menu")
            print("exit - exit the program")
            print("show - display graphs")
            print("")
            osSystem('pause')
示例#20
0
    def cones_bokeh(self, windows=[30, 60, 90, 120], quantiles=[0.25, 0.75]):
        """Plots volatility cones
        Parameters
        ----------
        windows : [int, int, ...]
            List of rolling windows for which to calculate the estimator cones
        quantiles : [lower, upper]
            List of lower and upper quantiles for which to plot the cones
        """
        top_q, median, bottom_q, realized, min, max, f, data = self.cones_prepare_data(
            windows, quantiles)
        colors_list = ['orange', 'blue', 'pink', 'black', 'red', 'green']
        methods_list = [
            'x', 'diamond', 'x', 'square', 'inverted_triangle',
            'inverted_triangle'
        ]
        line_dash_list = [
            'dotted', 'dotdash', 'dotted', 'solid', 'dashed', 'dashed'
        ]
        xs = [windows, windows, windows, windows, windows, windows]
        ys = [top_q, median, bottom_q, realized, min, max]
        legends_list = [
            str(int(quantiles[1] * 100)) + " Prctl", 'Median',
            str(int(quantiles[0] * 100)) + " Prctl", 'Realized', 'Min', 'Max'
        ]
        title = self._estimator + ' (' + self._symbol + ', daily from ' + self._last_date + ' days back ' + str(
            self._num_days_back) + ')'
        p = figure(title=title,
                   plot_width=700,
                   plot_height=500,
                   toolbar_sticky=False,
                   x_axis_label="Days",
                   y_axis_label="Volatility",
                   toolbar_location="below")
        legend_items = []
        for (colr, leg, x, y, method,
             line_dash) in zip(colors_list, legends_list, xs, ys, methods_list,
                               line_dash_list):
            # call dynamically the method to plot line, circle etc...
            renderers = []
            if method:
                renderers.append(getattr(p, method)(x, y, color=colr, size=4))
            renderers.append(p.line(x, y, color=colr, line_dash=line_dash))
            legend_items.append((leg, renderers))
        # doesnt work: legend = Legend(location=(0, -30), items=legend_items)
        legend = Legend(location=(0, -30), items=legend_items)
        p.add_layout(legend, 'right')

        from bokeh.charts import BoxPlot
        df = pandas.DataFrame({"data": data[0], "group": 0})
        df = df.append(pandas.DataFrame({"data": data[1], "group": 1}))
        df = df.append(pandas.DataFrame({"data": data[2], "group": 2}))
        df = df.append(pandas.DataFrame({"data": data[3], "group": 3}))
        p2 = BoxPlot(df,
                     values='data',
                     label='group',
                     title="Boxplot Summary (" + self._last_date + ") (" +
                     self._symbol + ")",
                     toolbar_location="below",
                     legend="bottom_right",
                     plot_width=600,
                     plot_height=400,
                     toolbar_sticky=False)
        from bokeh.models.ranges import DataRange1d
        p2.y_range = DataRange1d(np.min(df['data'] - 0.01),
                                 np.max(df['data'] + 0.01))

        layout1 = layout([[p, p2]])
        script, div = components(layout1)
        save_graph_to_db(script,
                         div,
                         self._symbol,
                         self._expiry,
                         self._last_date,
                         self._num_days_back,
                         self._resample,
                         self._estimator,
                         name="VOLEST")
        return layout1
示例#21
0
        bid_price = list_price + add_price
    elif zipcode in MEDIUM_HOT:
        add_price = (np.random.randint(5, 10, None, int)/100)*list_price
        bid_price = list_price + add_price
    else:
        add_price = (np.random.randint(5, 10, None, int) / 100) * list_price
        bid_price = list_price - add_price

    return bid_price

def submit():
    """
    these are made up coefficients for now
    """
    value = bidding_price(float(ZIPCODE.value), float(LISTPRICE.value))
    OUTPUT.text = 'Your suggested bidding price is: ' + str(int(value)) + ' $'

def reset():
    """
    This function resets the output
    """
    OUTPUT.text = None

BUTTON_1.on_click(submit)
BUTTON_2.on_click(reset)

LAY_OUT = layout(children=[[LOGO], [LISTPRICE, ZIPCODE], [BUTTON_1], [BUTTON_2], [OUTPUT]],
                 sizing_mode='fixed')
curdoc().add_root(LAY_OUT)
curdoc().title = "Predict the bidding price of your first home"
示例#22
0
                                      text="Solid average boiling point",
                                      render_mode="css",
                                      text_font_size="10px")

#Add labels to figure
f.add_layout(label_span_gas_average_boil)
f.add_layout(label_span_liquid_average_boil)
f.add_layout(label_span_solid_average_boil)


# create function
def update_span(attr, old, new):
    span_solid_boil.location = float(select.value)


# add select widgets
# options can be a list
options = [(str('solid_average_boil'), 'Solid Average Boiling Pt'),
           (str('solid_min_boil'), 'Solid Minimum Boiling Pt'),
           (str('solid_max_boil'), 'Solid Max Boilt Pt')]
select = Select(title='Span Values', options=options)

# select.on_change('active', update_span)
select.on_change('value', update_span)

lay_out = layout([[select]])

# curdoc is current document
curdoc().add_root(f)
curdoc().add_root(lay_out)
示例#23
0
    source.data = { value: [cb_obj.value] }
""")
exposure_controls.append(sn_slider)

noise_slider = Slider(title="Noise to Add In",
                      value=500,
                      start=0.0,
                      end=1000.0,
                      step=50.0,
                      callback_policy='mouseup')
noise_slider.callback = CustomJS(args=dict(source=fake_callback_source3),
                                 code="""
    source.data = { value: [cb_obj.value] }
""")
#exposure_controls.append(noise_slider)

sp.set_plot_options(
    plot.state
)  # plot.state has bokeh type Figure, so can be manipulated in the usual way

astro_tab = Panel(child=Column(children=astro_controls), title='Stars')
exposure_tab = Panel(child=Column(children=exposure_controls),
                     title='Exposure')
info_tab = Panel(child=Div(text=h.help(), width=300), title='Info')
visual_tab = Panel(child=Column(children=[widget]), title='Visuals')
controls = Tabs(tabs=[astro_tab, exposure_tab, visual_tab, info_tab],
                width=400)

layout = layout([[controls, plot.state]], sizing_mode='fixed')
curdoc().add_root(layout)
示例#24
0

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],
        [inputs, data_table],
    ],
    sizing_mode=sizing_mode)

tab1 = Panel(child=inputs, title="Settings")
tab2 = Panel(child=data_table, title="Table")
tab3 = Panel(child=p, title="Plot")

tabs = Tabs(tabs=[tab1, tab2, tab3])

update()  # initial load of the data

curdoc().add_root(tabs)
curdoc().title = "Movies"
示例#25
0
                        row[5] == str(srna.end)) and (
                        row[7] == str(srna.strand)):
                    q_exp = {"_".join([row[3], row[4], row[5], row[7]]): [
                             float(row[10]), float(row[11]), float(row[12]),
                             float(row[13]), float(row[14]), float(row[15]),
                             float(row[16]), float(row[17]), float(row[18]),
                             float(row[19]), float(row[20]), float(row[21]),
                             float(row[22]), float(row[23])]}
                    q_info = "_".join([row[3], row[4], row[5], row[7], row[9]])
        name = get_filename(q_info)
        if "/" in name:
            name = "_".join([name.replace("/", "_or_"), str(srna.start),
                             str(srna.end), str(srna.strand)])
        else:
            name = "_".join([name, str(srna.start), str(srna.end),
                             str(srna.strand)])
        p1 = plot(name + "_positive", q_info, q_exp, names,
                  name + "_positive.png", infos, exps, args.pos_cut, genes,
                  gos, members, "Correlation")
        p2 = plot(name + "_negative", q_info, q_exp, names,
                  name + "_negative.png", infos, exps, args.neg_cut, genes,
                  gos, members, "Anti-correlation")
        grid = gridplot([p1, p2], ncols=2)
        table = gen_table(members)
        l = layout([[grid], [widgetbox(table)]])
        save(l)
        fh.close()

if __name__ == "__main__":
    main()
示例#26
0
def compare_models():
    grid1 = request.args.get('grid1', grid_list['name'][0])
    grid2 = request.args.get('grid2', grid_list['name'][1])
    join = request.args.get('join', 'path')

    grid1_df, columns1 = read_summary(grid1, {})
    grid2_df, columns2 = read_summary(grid2, {})

    # select only columns available in both grids
    grid_columns = [value for value in columns1 if value in columns2]
    grid1_df = grid1_df[grid_columns]
    grid2_df = grid2_df[grid_columns]

    # make sure noL3 isn't an issue when joining.
    grid1_df['path'] = grid1_df['path'].apply(lambda x: x.replace('_noL3', ''))
    grid2_df['path'] = grid2_df['path'].apply(lambda x: x.replace('_noL3', ''))

    # merge the data frames
    grid_df = pd.merge(grid1_df,
                       grid2_df,
                       how='inner',
                       on=join,
                       suffixes=('_1', '_2'))

    # add the x1, y1, x2 and y2 default columns necessary for the plot to work
    start_pars = {
        'x1': 'M1_init_1',
        'y1': 'q_init_1',
        'x2': 'M1_init_2',
        'y2': 'q_init_2',
    }
    for par in start_pars.keys():
        grid_df[par] = grid_df[start_pars[par]]

    grid_source = ColumnDataSource(data=grid_df)

    # obtain the individual tracks
    track1_df, track_columns = get_track_from_grid(grid1_df.iloc[0], grid1,
                                                   history_pars)
    track1_source = ColumnDataSource(data=track1_df)
    track2_df, track_columns = get_track_from_grid(grid2_df.iloc[0], grid2,
                                                   history_pars)
    track2_source = ColumnDataSource(data=track2_df)

    disp_pars = {
        'x1': 'M1_init',
        'y1': 'q_init',
        'x2': 'M1_init',
        'y2': 'q_init',
    }

    # grid comparison plots
    plot, p1, p2 = plotting.make_comparison_plot(grid_source,
                                                 disp_pars,
                                                 titles=[grid1, grid2])
    controls, control_dict = plotting.make_comparison_controls(
        grid_source, [track1_source, track2_source], p1, p2, disp_pars,
        grid_columns)
    comparison_layout = layout([[plot], [controls]])

    # track plots
    history_plots, figures = plotting.make_history_plots(
        [track1_source, track2_source], history_pars)
    history_controls = plotting.make_history_controls(
        [track1_source, track2_source], history_pars, track_columns, figures)
    history_layout = layout([[history_controls], [history_plots]])

    script, div = components((comparison_layout, history_layout))

    return render_template('compare_models.html',
                           grid1=grid1,
                           grid2=grid2,
                           grids=grid_list['name'],
                           join=join,
                           columns=grid_columns,
                           script=script,
                           comparison_plot=div[0],
                           history_plot=div[1])
示例#27
0
def homepage():
    grid_name = request.args.get('grid', grid_list['name'][0])

    summary_df, summary_columns = read_summary(grid_name, start_pars)
    evolution_df, evolution_columns = get_track_from_grid(
        summary_df.iloc[0], grid_name, history_pars)

    # get the data sources
    source = ColumnDataSource(data=summary_df)
    evolution_source = ColumnDataSource(data=evolution_df)
    parameters = summary_df.columns.values.tolist()
    for p in ['x1', 'y1', 'z1', 'x2', 'y2', 'z2']:
        parameters.remove(p)
    values = [0 for i in parameters]
    table_source = ColumnDataSource(data={
        'parameters': parameters,
        'values': values
    })

    # Setup plot
    plot, p1, p2 = plotting.make_summary_plot(source, table_source, start_pars)
    cm_plot, cm_p1, cm_p2 = plotting.make_Gaia_CM_diagram(source, table_source)
    controls, button, dl_button, control_dict = plotting.make_summary_controls(
        source, evolution_source, p1, p2, start_pars, summary_columns)
    table = plotting.make_summary_table(table_source)

    hr_plot = plotting.make_HR_diagram(evolution_source)
    center_plot = plotting.make_center_track(evolution_source)

    history_plots, figures = plotting.make_history_plots([evolution_source],
                                                         history_pars)
    history_controls = plotting.make_history_controls([evolution_source],
                                                      history_pars,
                                                      evolution_columns,
                                                      figures)

    # create layout
    summary_controls = layout([[plot], [controls]])
    table_header = Div(text="<h2>Selected Model</h2>",
                       height=40,
                       sizing_mode="stretch_width")
    table_button = layout([[table_header], [table],
                           [Spacer(width=10, height=20)], [button],
                           [dl_button]])

    tab1 = Panel(child=summary_controls, title="Grid summary")
    tab2 = Panel(child=cm_plot, title="Gaia Color-Magnitude")
    tab_plot = Tabs(tabs=[tab1, tab2])

    summary_layout = layout(
        [[tab_plot, Spacer(width=40, height=10), table_button]])

    properties_plot = gridplot([[hr_plot, center_plot]],
                               toolbar_location='right')

    history_plot = layout([[history_controls], [history_plots]])

    script, div = components((summary_layout, properties_plot, history_plot))

    # Render the page
    return render_template('home.html',
                           script=script,
                           summary_div=div[0],
                           properties_div=div[1],
                           history_div=div[2],
                           grids=grid_list['name'],
                           selected_grid=grid_name)
                             y_range=(0, 100),
                             plot_width=600,
                             plot_height=300,
                             tools=[BoxZoomTool(), ResetTool()],
                             title="Similar Words")
word_cloud_stream_1.toolbar.logo = None
word_cloud_stream_1.axis.visible = False
word_cloud_stream_1.xgrid.grid_line_color = None
word_cloud_stream_1.ygrid.grid_line_color = None

source_cloud_1 = ColumnDataSource(data=dict(x=[], y=[], word=[], font_size=[]))
word_cloud_stream_1.text(x='x',
                         y='y',
                         text='word',
                         text_font_size='font_size',
                         source=source_cloud_1)
plot_word_cloud(relevantWords)

wgt_select = column(widgetbox(rad_text), widgetbox(radio_group))
wgt_but = column(widgetbox(button_go), widgetbox(user_text))
wgt_search = row(children=[widgetbox(search_1)])
wgt_media_1 = row(widgetbox(button_play), widgetbox(dur_text))
wgt_media_2 = row(widgetbox(sldr_rate), widgetbox(date_range_slider))

doc = curdoc()

layout = layout([wgt_search, wgt_select, wgt_but],
                [[[plot_tweet], [wgt_media_1], [wgt_media_2]],
                 [[plot_trend], [word_cloud_stream_1]]])

doc.add_root(layout)
          color='green',
          legend='old next shorter shot')
plot.line('rx_far', 'ry_far',
          source=source_far,
          line_width=1,
          line_alpha=.6,
          line_dash=[4, 4],
          color='red',
          legend='old next farther sh')

# insert picture of cannon and target
target_position = np.random.rand() * 10
bv_help.draw_target_at(plot, target_position)
bv_help.draw_cannon(plot)

columns = [
    TableColumn(field="shot_alpha", title="Alpha"),
    TableColumn(field="shot_error", title="Error")
]

data_table = DataTable(source=source_datatable, columns=columns, width=350, height=50)

# calculate data
update_data()

# make layout
curdoc().add_root(layout(children=[[plot],
                                   [widgetbox(buttonShort, buttonFar)],
                                   [widgetbox(data_table)]],
                         sizing_mode='fixed'))
def bkapp(dfile,
          pcol,
          app_name,
          server_static_root,
          title='Sketch-map',
          pointsize=10,
          jmol_settings=""):
    global cv, controls, selectsrc, columns, button, slider, n, xcol, ycol, ccol, rcol, plt_name, indx, ps, jmolsettings, appname, lay, server_prefix, periodic_checkbox, pss, frac, alphas, grid, marker
    appname = app_name
    server_prefix = server_static_root
    ps = pointsize
    jmolsettings = jmol_settings
    #initialise data
    datafile = join(appname, 'data', dfile)
    cv = smap(name=title)
    cv.read(datafile)
    n = len(cv.data)
    columns = [i for i in cv.columns]

    # set up selection options
    tcol = pcol[0] - 1
    xcol = Select(title='X-Axis',
                  value=columns[tcol],
                  options=columns,
                  width=50)
    xcol.on_change('value', update)
    tcol = pcol[1] - 1
    ycol = Select(title='Y-Axis',
                  value=columns[tcol],
                  options=columns,
                  width=50)
    ycol.on_change('value', update)
    roptions = ['None']
    for option in columns:
        roptions.append(option)
    rcol = Select(title='Size', value='None', options=roptions, width=50)
    rcol.on_change('value', update)
    if (len(pcol) > 2):
        tcol = pcol[2] - 1
        ccol = Select(title='Color',
                      value=columns[tcol],
                      options=roptions,
                      width=50)
    else:
        ccol = Select(title='Color', value='None', options=roptions, width=50)
    ccol.on_change('value', update)

    marker_options = [
        'circle', 'diamond', 'triangle', 'square', 'asterisk', 'cross',
        'inverted_triangle', 'variable'
    ]
    marker = Select(title='Marker',
                    value='circle',
                    options=marker_options,
                    width=50)
    marker.on_change('value', update)

    periodic_checkbox = CheckboxGroup(labels=["Periodic Palette"], active=[])
    periodic_checkbox.on_change('active', update)

    grid = CheckboxGroup(labels=["Show Axis"], active=[0])
    grid.on_change('active', update)

    plt_name = Select(title='Palette',
                      width=50,
                      value='Inferno256',
                      options=[
                          "Magma256", "Plasma256", "Spectral6", "Inferno256",
                          "Viridis256", "Greys256", "cosmo"
                      ])
    plt_name.on_change('value', update)

    pss = Slider(start=0,
                 end=50,
                 value=ps,
                 step=1,
                 callback_policy='mouseup',
                 title="Point Size",
                 width=150)
    pss.on_change('value', update)

    frac = Slider(start=0,
                  end=1,
                  value=1.0,
                  step=0.1,
                  callback_policy='mouseup',
                  title="Fraction Of Data Loaded",
                  width=200)
    frac.on_change('value', update)

    alphas = Slider(start=0,
                    end=1,
                    value=0.75,
                    step=0.1,
                    callback_policy='mouseup',
                    title="Point Alpha",
                    width=150)
    alphas.on_change('value', update)

    xm = widgetbox(xcol, width=170, sizing_mode='fixed')
    ym = widgetbox(ycol, width=170, sizing_mode='fixed')
    cm = widgetbox(ccol, width=170, sizing_mode='fixed')
    mm = widgetbox(marker, width=170, sizing_mode='fixed')
    cp = widgetbox(periodic_checkbox, width=100, sizing_mode='fixed')
    gc = widgetbox(grid, width=100, sizing_mode='fixed')
    rm = widgetbox(rcol, width=170, sizing_mode='fixed')
    pm = widgetbox(plt_name, width=170, sizing_mode='fixed')
    psw = widgetbox(pss, width=210, height=50, sizing_mode='fixed')
    asl = widgetbox(alphas, width=210, height=50, sizing_mode='fixed')
    fw = widgetbox(frac, width=270, height=50, sizing_mode='fixed')
    controls = Column(
        Row(xm, ym, cm, rm, pm, mm, width=1050, sizing_mode='scale_width'),
        Row(gc, fw, psw, asl, cp, width=1050, sizing_mode='fixed'))

    # create plot and slider

    plotpanel = create_plot()
    # full layout
    lay = layout([
        [controls],
        [plotpanel],
    ], sizing_mode='fixed')
    return lay
示例#31
0
def output_components(prefix, order, maxaln):
    rinfo = "{0}.rinfo".format(prefix)
    comp = "{0}.comp".format(prefix)

    def plot_read_dist(rinfo):
        df = pd.read_table(rinfo)
        data = df[['length', 'mapper', 'count']].groupby(['length',
                                                          'mapper']).count()
        data = data.apply(lambda s: s / data.sum() * 100, axis=1).reset_index()
        p = Bar(data,
                plot_width=500,
                plot_height=400,
                label='length',
                values='count',
                agg='sum',
                stack=cat(columns='mapper', sort=False),
                legend='top_right',
                color=color(columns='mapper',
                            palette=["#f98283", "#a4a4a4"],
                            sort=False),
                xlabel='read length (nt)',
                ylabel='proportion (%)',
                ygrid=False,
                tooltips=[('length', '@length'), ('mapper', '@mapper'),
                          ('percent', '@height')])
        p.toolbar.logo = None
        p.outline_line_color = None
        return p

    rdist = plot_read_dist(rinfo)

    df = pd.read_table(comp, index_col=0)
    total = df.sum()
    total = total * 100 / total.sum()
    df = df.apply(lambda s: s * 100 / s.sum(), axis=1)
    df = df.reset_index()
    #ftypes = df.columns[1:].tolist()
    ftypes = order
    colors = sns.color_palette("hls", len(ftypes)).as_hex()
    bar = Bar(df,
              values=blend(*ftypes, name="ftypes", labels_name="ftype"),
              x_range=rdist.x_range,
              y_range=(0, 100),
              label=cat(columns='rlen', sort=False),
              stack=cat(columns='ftype', sort=False),
              xlabel='read length (nt)',
              ylabel='proportion (%)',
              legend="top_right",
              ygrid=False,
              width=500,
              height=400,
              color=color(columns='ftype', palette=colors, sort=False),
              fill_alpha=1,
              tooltips=[("length", "@rlen"), ("feature", "@ftype"),
                        ("percent", "@height")])
    bar.toolbar.logo = None
    bar.outline_line_color = None

    start_angles = {}
    end_angles = {}
    start = 0
    for ftype in ftypes:
        end = 2 * pi * total[ftype] / 100
        start_angles[ftype] = start
        end_angles[ftype] = start + end
        start += end

    colors = dict(zip(ftypes, colors))
    df = pd.DataFrame(total).reset_index()
    df.columns = ["ftype", "percent"]
    df["start"] = df.apply(lambda s: start_angles[s["ftype"]], axis=1)
    df["end"] = df.apply(lambda s: end_angles[s["ftype"]], axis=1)
    df["color"] = df.apply(lambda s: colors[s["ftype"]], axis=1)
    df["x"] = df.apply(lambda s: 1.2 * cos(
        (start_angles[s["ftype"]] + end_angles[s["ftype"]]) / 2),
                       axis=1)
    df["y"] = df.apply(lambda s: 1.2 * sin(
        (start_angles[s["ftype"]] + end_angles[s["ftype"]]) / 2),
                       axis=1)
    df["text"] = df.apply(lambda s: "{0:.3f}%".format(s["percent"]), axis=1)
    source = ColumnDataSource(data=df)

    pie = figure(width=400,
                 height=400,
                 x_range=(-1.4, 1.4),
                 y_range=(-1.4, 1.4))
    pie.toolbar.logo = None
    wr = pie.annular_wedge(x=0,
                           y=0,
                           inner_radius=0.5,
                           outer_radius=1,
                           start_angle="start",
                           end_angle="end",
                           fill_color="color",
                           line_color="#ffffff",
                           line_width=0.5,
                           source=source)

    pie.axis.visible = False
    pie.grid.grid_line_color = None
    pie.outline_line_color = None

    hover = HoverTool(tooltips=[("feature", "@ftype"),
                                ("percent", "@percent")],
                      renderers=[wr])
    pie.add_tools(hover)

    text_props = {
        "source": source,
        "angle": 0,
        "color": "black",
        "text_align": "center",
        "text_baseline": "middle",
        "text_font_size": "8pt",
        "text_font_style": "normal"
    }
    pie.text(x="x", y="y", text="text", **text_props)

    empty = figure(width=400,
                   height=400,
                   x_range=(-1.1, 1.1),
                   y_range=(-1.1, 1.1))
    empty.toolbar.logo = None
    empty.axis.visible = False
    empty.grid.grid_line_color = None
    empty.outline_line_color = None
    empty.toolbar_location = None

    stat = get_stat(prefix, maxaln)
    source = ColumnDataSource(data=stat)
    columns = [
        TableColumn(field="Statistics", title="Statistics", width=200),
        TableColumn(field="Number of reads",
                    title="Number of reads",
                    formatter=NumberFormatter(format="0,0"),
                    width=150),
        TableColumn(field="Proportion",
                    title="Proportion",
                    formatter=NumberFormatter(format="0.000%"),
                    width=100),
    ]
    data_table = DataTable(source=source,
                           columns=columns,
                           width=450,
                           row_headers=False)

    script, div = components(
        layout([[data_table, rdist], [pie, bar]], sizing_mode="scale_width"))
    return script, div
示例#32
0
        </div>
    </div>
    """)
f2.add_tools(hover2)
w2 = column([text21, text22, f2])
# section 3: Cantidad de Itinerarios Trasladados
text31 = Div(text='<h3>Itinerarios Trasladados x Mes</h3>',
             width=wf,
             height=20)
text32 = Div(text=' ', width=wf, height=20)
f3 = figure(title=' ',
            plot_height=hf,
            plot_width=wf,
            tools='pan,box_zoom,reset',
            toolbar_location="above")
f3.xaxis.axis_label = 'mes del año'
f3.yaxis.axis_label = 'cantidad de itinerarios'
f3.add_tools(hover)
line3 = f3.line(x=[0, 1], y=[0, 1], line_color="blue", line_width=2, alpha=1)
w3 = column([text31, text32, f3])
# section 4
title2 = Div(text=""" <h3>Distribución de Dias Facturaddos x Mes</h3> """,
             width=1000,
             height=40)
# update plots
update_plots()

# Dashboard <<<<<<<<<<<<<<<<<<<<<<<<<<<
dashboard = layout([[title1], [w1, w2, w3]], sizing_mode='fixed')
save(dashboard, title='Agenda 2018')
示例#33
0
    print(fval)
    text = text_input.value
    print(text)
    df1 = pd.DataFrame(df, columns=fval)
    y = df['churn']
    x_train_original, x_test_original, y_train_original, y_test_original = train_test_split(
        df1, y, test_size=0.25)
    clf = svm.LinearSVC(random_state=0)
    clf.fit(x_train_original, y_train_original)
    predictions = clf.predict(x_test_original)
    print("Accuracy =", accuracy_score(y_test_original, predictions))
    #print(np.unique(predictions))
    tn, fp, fn, tp = confusion_matrix(y_test_original, predictions).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, text_input]
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, div, p]])

#update()  # initial load of the data

curdoc().add_root(l)
curdoc().title = "Churn"
    'color': 'white',
    'font': '15px bold arial, sans-serif',
    'background-color': 'green',
    'text-align': 'center',
    'border-radius': '7px'
}
SinText = PreText(text='Valor del Seno: 0.00 ', width=300, style=estilo)
CosText = PreText(text='Valor del Coseno: 0.00', width=300, style=estilo)

t = 0


def MainLoop(
):  # Funcion principal que se llama cada cierto tiempo para mostrar la informacion
    global t, sin, cos
    update = dict(time=[t], sin=[sin[t]], cos=[cos[t]])
    DataSource.stream(new_data=update,
                      rollover=100)  # Se ven los ultimos 100 datos
    SinText.text = 'Valor del Seno: {}'.format(round(sin[t], 2))
    CosText.text = 'Valor del Coseno: {}'.format(round(cos[t], 2))
    t += 1


l = layout([[fig_sin], [SinText, CosText]])

curdoc().add_root(l)
curdoc().title = "Dashboard Ejemplo"
curdoc().add_periodic_callback(
    MainLoop, 100
)  # Cada 300 milisegundos se llama a la funcion y se actualiza el grafico
示例#35
0
文件: main.py 项目: spmcelrath/demos
plot.legend.background_fill_alpha = 0.5
plot.legend.location = "bottom_right"
main_plot = row(plot, width=1100, height=1000)
main_plot.sizing_mode = "fixed"
inputs = column(*controls, width=240, height=1000)
inputs.sizing_mode = "fixed"
plots = column([hist_p, iqr_p, index_select, index_p, ewi_p, stats_table],
               width=420,
               height=1000)
plots.sizing_mode = "fixed"

print(stock_ohlc_df.isnull().values.any())
print(ohlc_df.isnull().values.any())
print(data.isnull().values.any())
print(hs.isnull().values.any())
print(returns_df.isnull().values.any())

print(stock_ohlc_df.dtypes)
print(ohlc_df.dtypes)
print(data.dtypes)
print(hs.dtypes)
print(returns_df.dtypes)

TOOLTIPS = [("ticker", "@name"), ("name", "@full_name"), ("Sector", "@sector")]
plot.add_tools(HoverTool(tooltips=TOOLTIPS, renderers=[graph_renderer]),
               TapTool(), LassoSelectTool())

l = layout([[inputs, main_plot, plots]], sizing_mode="scale_both")

doc.add_root(l)
示例#36
0
output_file("js_on_change.html")

x = [x * 0.005 for x in range(0, 200)]
y = x

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

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6, color='red')

callback = CustomJS(args=dict(source=source),
                    code="""
    var data = source.data;
    var f = cb_obj.value
    var x = data['x']
    var y = data['y']
    for (var i = 0; i < x.length; i++) {
        y[i] = Math.pow(x[i], f)
    }
    source.change.emit();
""")

slider = Slider(start=0.1, end=4, value=1, step=.1, title="power")
slider.js_on_change('value', callback)

lay = layout([slider], [plot])

content = interact_plot_grid(lay)

description = 'Interact Plot'
示例#37
0
文件: UI.py 项目: MikeWoodward/UT330B
    def offset_tab(self):

        """Reading/writing device offsets"""

        # True if the offset device data has been read, false otherwise
        self.offset_device_read = False

        offset_status_h = Div(text="<strong>Status</strong>")
        self.offset_status = Div(text="", width=self.page_width)

        # Connect to device button
        # ========================
        offset_controls_h = Div(text="<strong>Device controls</strong>")
        offset_connect = Button(label='Connect to UT330',
                                button_type="success")
        offset_read = Button(label='Read offset', button_type="success")
        offset_write = Button(label='Write offset', button_type="success")
        offset_disconnect = Button(label='Disconnect from UT330',
                                   button_type="success")

        offset_connect.on_click(self.offset_connect)
        offset_read.on_click(self.offset_read)
        offset_write.on_click(self.offset_write)
        offset_disconnect.on_click(self.offset_disconnect)

        # Offsets
        # =======
        offset_offsets_h = Div(text="<strong>Offsets</strong>")
        self.offset_t_current = TextInput(title="Temperature current")
        self.offset_h_current = TextInput(title="Humidity current")
        self.offset_p_current = TextInput(title="Pressure current")

        self.offset_t = TextInput(title="Temperature offset")
        self.offset_h = TextInput(title="Humidity offset")
        self.offset_p = TextInput(title="Pressure offset")

        # Values to widgets
        # =================
        if self.device_connected:
            self.offset_connected()
        else:
            self.offset_not_connected()

        if self.device_connected:
            self.offset_status.text = ('UT330 device connected. The Read, '
                                       'Write, and Disconnect buttons '
                                       'will work.')
        else:
            self.offset_status.text = ('UT330 device is <strong>NOT</strong> '
                                       'connected. The '
                                       'Read, Write, and Disconnect buttons '
                                       'will <strong>not work</strong>. '
                                       'Click the '
                                       'Connect button if the UT330 is '
                                       'connected on a USB port.')
        # Layout
        # ======
        l = layout([[offset_status_h],
                    [self.offset_status],
                    [offset_controls_h],
                    [offset_connect,
                     offset_read,
                     offset_write,
                     offset_disconnect],
                    [offset_offsets_h],
                    [self.offset_t_current,
                     self.offset_h_current,
                     self.offset_p_current],
                    [self.offset_t,
                     self.offset_h,
                     self.offset_p]],
                   width=self.page_width)

        return Panel(child=l,
                     title="Read/write offset")
def TabGraficosTiempoTotal(DatosBokeh):
    """
        LAYOUT
    """
    from source.visualisation.plot.PLT_Altitud import Altitud
    from source.visualisation.plot.PLT_Cadencia import Cadencia
    from source.visualisation.plot.PLT_DesnivelPositivoAcumulado import DesnivelPositivoAcumulado
    from source.visualisation.plot.PLT_FrecuenciaCardiaca import FrecuenciaCardiaca
    from source.visualisation.plot.PLT_Pendiente import Pendiente
    from source.visualisation.plot.PLT_Ritmo import Ritmo
    from source.visualisation.plot.PLT_Temperatura import Temperatura
    from source.visualisation.plot.PLT_Zancada import Zancada

    MetricasAuxiliares = [
        'FRECUENCIA CARDIACA', 'RITMO', 'ALTITUD', 'CADENCIA', 'TEMPERATURA',
        'PENDIENTE', 'DESNIVEL POSITIVO', 'LONGITUD ZANCADA'
    ]

    dict_MetricasAuxiliares = {
        'FRECUENCIA CARDIACA': 'FrecuenciaCardiaca[ppm]',
        'RITMO': 'Velocidad[m/s]',
        'ALTITUD': 'Altitud[m]',
        'CADENCIA': 'Cadencia[ppm]',
        'TEMPERATURA': 'Temperatura[ºC]',
        'LONGITUD ZANCADA': 'LongitudZancada[m]',
        'PENDIENTE': 'Pendiente[%]',
        'DESNIVEL POSITIVO': 'DesnivelPositivo[m]'
    }

    MetricasDisponibles = []
    for Metrica in MetricasAuxiliares:
        for key in dict_MetricasAuxiliares:
            if Metrica == key and dict_MetricasAuxiliares[
                    key] in DatosBokeh.column_names:
                MetricasDisponibles.append(key)

    ListadoGraficas = []

    MetricaPrincipal = 'FRECUENCIA CARDIACA'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaFC = FrecuenciaCardiaca(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaFC)

    MetricaPrincipal = 'RITMO'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaVEL = Ritmo(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaVEL)

    MetricaPrincipal = 'ALTITUD'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaALT = Altitud(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaALT)

    MetricaPrincipal = 'CADENCIA'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaCAD = Cadencia(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaCAD)

    MetricaPrincipal = 'TEMPERATURA'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaTMP = Temperatura(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaTMP)

    MetricaPrincipal = 'PENDIENTE'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaPEN = Pendiente(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaPEN)

    MetricaPrincipal = 'DESNIVEL POSITIVO'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaDPA = DesnivelPositivoAcumulado(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaDPA)

    MetricaPrincipal = 'LONGITUD ZANCADA'
    if dict_MetricasAuxiliares[MetricaPrincipal] in DatosBokeh.column_names:
        GridGraficaZAN = Zancada(DatosBokeh, 'TiempoTotal', [
            Metricas
            for Metricas in MetricasDisponibles if Metricas != MetricaPrincipal
        ])
        ListadoGraficas.append(GridGraficaZAN)

    GraficasTiempoTotal = layout(ListadoGraficas, sizing_mode='stretch_both')

    return GraficasTiempoTotal
示例#39
0
import matplotlib
matplotlib.use('Agg')
from bokeh.models.widgets import Panel, Tabs
from bokeh.io import show, curdoc
from bokeh.layouts import layout
import rubric
import interactive_mcdm
import features_checklist
import instructions
# import swing_table

doc = curdoc()

doc.title = "Decision Making Model"

rubric = rubric.p
mcdm = interactive_mcdm.app_layout
features = features_checklist.p
instr = instructions.app_layout
# swing = swing_table.swing_table

instr_tab = Panel(child=instr, title="Instructions")
tab1 = Panel(child=rubric, title="Rubric")
tab2 = Panel(child=features, title="Features Checklist")
tab3 = Panel(child=mcdm, title="MCDM")

tabs = Tabs(tabs=[instr_tab, tab1, tab2, tab3], width=400)  #, tab4])

app_layout = layout([tabs])
doc.add_root(app_layout)
示例#40
0
    offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset", callback=callback)
    callback.args["offset"] = offset_slider

    widgets = WidgetBox(amp_slider, freq_slider, phase_slider, offset_slider)
    return [widgets, plot]


def linked_panning():
    N = 100
    x = np.linspace(0, 4 * np.pi, N)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.sin(x) + np.cos(x)

    s1 = figure(tools=tools)
    s1.circle(x, y1, color="navy", size=8, alpha=0.5)
    s2 = figure(tools=tools, x_range=s1.x_range, y_range=s1.y_range)
    s2.circle(x, y2, color="firebrick", size=8, alpha=0.5)
    s3 = figure(tools='pan, box_select', x_range=s1.x_range)
    s3.circle(x, y3, color="olive", size=8, alpha=0.5)
    return [s1, s2, s3]

l = layout([
    bollinger(),
    slider(),
    linked_panning(),
], sizing_mode='stretch_both')

show(l)
示例#41
0
# Add widgets and their callbacks

from bokeh.models.widgets import Button, TextInput

changeA_button = Button(label='UpdateFig A')
changeA_button.on_click(update_figure_A)

changeB_button = Button(label='UpdateFig B')
changeB_button.on_click(update_figure_B)

widgets = [changeA_button, changeB_button]

from bokeh.layouts import widgetbox
widgetBox = widgetbox(*widgets, sizing_mode='fixed')

# Add figure and widgets to a layout
###########################################################################
from bokeh.layouts import layout
layout = layout( [[fig], [widgetBox]], sizing_mode='fixed')

###########################################################################
# Add layout to current document

from bokeh.io import curdoc
curdoc().add_root(layout)

from bokeh.client import push_session
session = push_session(curdoc())
session.show()  # open the document in a browser

session.loop_until_closed()  # run forever
示例#42
0
def slider_update(attrname, old, new):
    year = slider.value
    label.text = str(year)
    source.data = data[year]

slider = Slider(start=years[0], end=years[-1], value=years[0], step=1, title="Year")
slider.on_change('value', slider_update)

callback_id = None

def animate():
    global callback_id
    if button.label == '► Play':
        button.label = '❚❚ Pause'
        callback_id = curdoc().add_periodic_callback(animate_update, 200)
    else:
        button.label = '► Play'
        curdoc().remove_periodic_callback(callback_id)

button = Button(label='► Play', width=60)
button.on_click(animate)

layout = layout([
    [plot],
    [slider, button],
], sizing_mode='scale_width')

curdoc().add_root(layout)
curdoc().title = "Gapminder"
示例#43
0
def get_hl():
    return list(map(lambda x: keys[x], hlsel.active))

def _update():
    ds.set_num_dp(int(nslider.value))
    df = ds.get_dataframe()
    if 0 in rselect.active:
        df = nat_unit.apply(df)
    if 1 in rselect.active:
        df = jbif.dfmap_zeromean(df)
    gt.update_graph(df, highlight=get_hl())
    gf.update_graph(jbif.dfmap_fft(df, indep_var='Time'), highlight=get_hl())
    gs.update_graph(df, highlight=get_hl())

def update():
    try:
        _update()
    except Exception as e:
        print(e)
        print(traceback.format_exc())

box = widgetbox(rselect, nslider, hlsel,  sizing_mode='fixed')
grid = gridplot([[gt.make_new_graph(), gf.make_new_graph()],
                 [gs.make_new_graph(), None]])

l = layout([desc], [box, grid])

curdoc().add_root(l)
curdoc().add_periodic_callback(update, 500)
示例#44
0
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.js_on_event("menu_item_click", CustomJS(code="console.log('dropdown: ' + this.item, this.toString())"))

#Toggle button GUI
toggle = Toggle(label="Button", button_type="success")
toggle.js_on_click(CustomJS(code="""
    console.log('toggle: active=' + this.active, this.toString())
"""))
OPTIONS = ["Attribute1", "Attribute2", "Attribute3", "Attribute4"]
multi_choice = MultiChoice(value=["foo", "baz"], options=OPTIONS)
multi_choice.js_on_change("value", CustomJS(code="""
    console.log('multi_choice: value=' + this.value, this.toString())
"""))

#GUI Left column
controls = [dropdown, spinner, toggle]
inputs = column(*controls, sizing_mode='fixed', height=250, width=350)
l1 = layout([[inputs, p1]], sizing_mode='fixed', height=600, width=150)
l2 = layout([[inputs, p2]], sizing_mode='fixed', height=600, width=150)
l3 = layout([[inputs, p3]], sizing_mode='fixed', height=600, width=150)
#Tab setup
tab1 = Panel(child=l1, title="Bar chart1")
tab2 = Panel(child=l2, title="Bar chart2")
tab3 = Panel(child=l3, title="Heat map")

tabs = Tabs(tabs=[tab1, tab2, tab3])

show(tabs)


示例#45
0
        temp = data.set_index("title").T.reindex(index=col_order)
        details.text = temp.style.render()
    else:
        details.text = "Selection Details"


# Setup functions for each control so that changes will be captured and data
# updated as required
controls = [province, price_max, title]

for control in controls:
    control.on_change("value", lambda attr, old, new: update())

# If the source is changed to a selection, execute that selection process
source.on_change("selected", selection_change)

# The final portion is to layout the parts and get the server going

# Build a box for all the controls
inputs = widgetbox(*controls, sizing_mode="fixed")

# Define a simple layout
l = layout([[desc], [inputs, p], [details]], sizing_mode="fixed")

# Update the data and instantiate the service
update()
curdoc().add_root(l)

# Show the title in the browser bar
curdoc().title = "Australian Wine Analysis"
示例#46
0
    def submit_ranks(self):

        self.weight_sliders = OrderedDict()

        ranks = []

        for k in self.chosen_criteria:

            if not self.ranking[k][1].value:

                self.ranking[k][1].button_type = "danger"

                self.ranking[k].append(
                    PreText(
                        text="Please enter a rank for all chosen criteria"))

                self.app_layout.children.pop(1)

                self.app_layout.children.append(
                    layout([[Spacer(width=300), self.swing_table],
                            *[self.ranking[k] for k in self.ranking.keys()],
                            [self.rank_submit], [self.clear_button]]))

            else:

                ranks.append(self.ranking[k][1].value)

        if len(ranks) == len(self.ranking.keys()):

            if len(ranks) != len(list(set(ranks))):

                dup_values = []

                for crit, count in Counter(ranks).items():

                    if count > 1:

                        dup_values.append(crit)

                for k in self.ranking.keys():

                    if self.ranking[k][1].value in dup_values:

                        self.ranking[k][1].button_type = "danger"

                        self.ranking[k].append(
                            PreText(
                                text=
                                "Please enter unique ranks for each criteria"))

                self.app_layout.children.pop(1)

                self.app_layout.children.append(
                    layout([[Spacer(width=300), self.swing_table],
                            *[self.ranking[k] for k in self.ranking.keys()],
                            [self.rank_submit], [self.clear_button]]))

            else:

                for k in self.ranking.keys():

                    self.ranking[k][1].button_type = "primary"

                temp_list = []

                for r in np.argsort(ranks):

                    temp_list.append(self.chosen_criteria[r])

                self.chosen_criteria = temp_list

                self.add_weight_changes()
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.layouts import layout
from bokeh.models import Toggle, BoxAnnotation, CustomJS

# We set-up the same standard figure with two lines and now a box over top
p = figure(plot_width=600, plot_height=200, tools='')
visible_line = p.line([1, 2, 3], [1, 2, 1], line_color="blue")
invisible_line = p.line([1, 2, 3], [2, 1, 2], line_color="pink")

box = BoxAnnotation(left=1.5, right=2.5, fill_color='green', fill_alpha=0.1)
p.add_layout(box)

# We write JavaScript to link toggle with visible property of box and line
code = '''\
object.visible = toggle.active
'''

callback1 = CustomJS(code=code, args={})
toggle1 = Toggle(label="Green Box", button_type="success", callback=callback1)
callback1.args = {'toggle': toggle1, 'object': box}

callback2 = CustomJS(code=code, args={})
toggle2 = Toggle(label="Pink Line", button_type="success", callback=callback2)
callback2.args = {'toggle': toggle2, 'object': invisible_line}

output_file("styling_visible_annotation_with_interaction.html")

show(layout([p], [toggle1, toggle2]))
示例#48
0
                  y="exam_grades",
                  text="student_names",
                  x_offset=5,
                  y_offset=5,
                  source=source)

f.add_layout(labels)

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


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


# Create Radio Button Group widget
options = ["average_grades", "exam_grades", "student_names"]

radio_button_group = RadioButtonGroup(labels=options)

radio_button_group.on_change("active", update_labels)

#create layout
lay_out = layout([[radio_button_group]])

# Add to curdoc
curdoc().add_root(f)
curdoc().add_root(lay_out)
示例#49
0
    p.add_tools(HoverTool(tooltips=None, renderers=[cr], mode='hline'))
    return p

def intro():
    return Div(text="""
        <h3>Welcome to Layout!</h3>
        <p>Hopefully you'll see from the code, that the layout tries to get out of your way
        and do the right thing. Of course, it might not always, so please report bugs as you
        find them and attach them to the epic we're creating <a href="">here</a>.</p>
        <p>This is an example of <code>scale_width</code> mode (happy to continue the conversations
        about what to name the modes). In <code>scale_width</code> everything responds to the width
        that's available to it. Plots alter their height to maintain their aspect ratio, and widgets
        are allowed to grow as tall as they need to accomodate themselves. Often times widgets
        stay the same height, but text is a good example of a widget that doesn't.</p>
        <h4>I want to stress that this was all written in python. There is no templating or
        use of <code>bokeh.embed</code>.</h4>
    """)


l = layout(
    [
        [intro()],
        [text(), scatter()],
        [text()],
        [hover_plot(), text()],
    ],
    sizing_mode='scale_width'
)

show(l)
示例#50
0
slider = Slider(start=years[0],
                end=years[-1],
                value=years[0],
                step=1,
                title="Year")
slider.on_change('value', slider_update)

callback_id = None


def animate():
    global callback_id
    if button.label == '► Play':
        button.label = '❚❚ Pause'
        callback_id = curdoc().add_periodic_callback(animate_update, 200)
    else:
        button.label = '► Play'
        curdoc().remove_periodic_callback(callback_id)


button = Button(label='► Play', width=60)
button.on_event('button_click', animate)

layout = layout([
    [plot],
    [slider, button],
], sizing_mode='scale_width')

curdoc().add_root(layout)
curdoc().title = "Gapminder"
示例#51
0
    def plot(self):
        def update():
            self.refresh_ticks += 1
            self.query(self.selected_color, self.selected_year, self.selected_month)

            self.hot_map_update()
            self.trip_hour_update()
            self.trip_distance_update()
            self.trip_fare_update()
            self.tasks_stat_update()
            # self.resource_usage_update()

        def on_select():
            BOROUGHS_CODE = {v: k for k, v in NYCBorough.BOROUGHS.items()}
            self.selected_color = 'green' if color.active == 1 else 'yellow'
            pickup.label = 'Pickups' if pickup.active else 'Dropoffs'
            self.selected_type = pickup.label
            self.selected_borough = BOROUGHS_CODE[borough.value]
            borough.label = borough.value
            self.selected_year = int(year.value)
            self.selected_month = int(month.value)

        def on_submit():
            self.logger.debug('submit (%s, %s, %s, %s, %s)' % \
                (self.selected_type,
                 NYCBorough.BOROUGHS[self.selected_borough],
                 self.selected_color,
                 self.selected_year, self.selected_month))
            self.tasks.create_tasks(
                self.selected_color,
                self.selected_year,
                self.selected_month)

        cwd = os.path.dirname(__file__)
        desc = Div(text=open(
            os.path.join(cwd, "description.html")).read(), width=1000)

        # Create input controls
        color = RadioButtonGroup(labels=['Yellow', 'Green'], active=1)
        color.on_change('active', lambda attr, old, new: on_select())

        pickup = Toggle(label='Pickups', button_type="primary", active=True)
        pickup.on_change('active', lambda attr, old, new: on_select())

        # BUG: Dropdown menu value cannot be integer, i.e., ('Mahattan', '1')
        borough_menu = [('All Boroughs', 'All Boroughs'), None,
            ('Manhattan', 'Manhattan'), ('Bronx', 'Bronx'), ('Brooklyn', 'Brooklyn'),
            ('Queens', 'Queens'), ('Staten Island', 'Staten Island')]
        # https://github.com/bokeh/bokeh/issues/4915
        borough = Dropdown(label="Boroughs", button_type="warning",
            menu=borough_menu, value='All Boroughs')
        borough.on_change('value', lambda attr, old, new: on_select())

        year = Select(title="Year:", value=str(self.selected_year),
            options=[str(y) for y in range(MIN_DATE['green'].year, MAX_DATE['green'].year+1)])
        year.on_change('value', lambda attr, old, new: on_select())

        month = Select(title="Month:", value=str(self.selected_month),
            options=[str(m) for m in range(1, 13)])
        month.on_change('value', lambda attr, old, new: on_select())

        submit = Button(label="Submit", button_type="success")
        submit.on_click(on_submit)

        controls = [color, pickup, borough, year, month, submit]

        self.query(self.selected_color, self.selected_year, self.selected_month)
        self.hot_map_init()
        self.trip_hour_init()
        self.trip_distance_init()
        self.trip_fare_init()
        self.tasks_stat_init()
        self.resource_usage_init()

        rightdown_row = row([self.trip_distance, self.trip_fare])
        right_column = column([self.trip_hour, rightdown_row])
        inputs = widgetbox(*controls, width=140, sizing_mode="fixed")
        l = layout([
            [desc],
            [inputs, self.hot_map, right_column],
            [self.tasks_stat, self.resource_usage],
        ], sizing_mode="fixed")

        curdoc().add_root(l)
        curdoc().add_periodic_callback(update, 5000)
        curdoc().title = "NYC Taxi Data Explorer"
示例#52
0
文件: main.py 项目: cvalencia09/bokeh
def animate_update():
    year = slider.value + 1
    if year > len(all_df_dict):
        year = 0
    slider.value = year


def animate():
    global callback_id
    if button.label == '► Play':
        button.label = '❚❚ Pause'
        callback_id = curdoc().add_periodic_callback(animate_update, 200)
    else:
        button.label = '► Play'
        curdoc().remove_periodic_callback(callback_id)


button = Button(label='► Play', width=60)
button.on_click(animate)

layout = layout([
    [p],
    [slider, button],
], sizing_mode='fixed')

curdoc().add_root(layout)
curdoc().title = "renta"
"""
in terminal use: bokeh serve --show myapp.py

"""
示例#53
0
def test_layout_kwargs():
    p1, p2, p3, p4 = figure(), figure(), figure(), figure()

    grid = layout([[p1, p2], [p3, p4]], sizing_mode='fixed', name='simple')

    assert grid.name == 'simple'
示例#54
0
                     select_astalt,
                     select_he,
                     select_ascites,
                     select_hcc,
                     confint_slider,
                     width=00)

coltable = column(table_description, table, sizing_mode="stretch_both")
colestimates = column(p,
                      coltable,
                      width=600,
                      height=600,
                      sizing_mode="stretch_both")

rowdisp = row(colcontrols, colestimates, sizing_mode="stretch_both")
lay = layout([[heading], [rowdisp]])

#############################################################
##deployment code
#############################################################

curdoc().add_root(lay)
curdoc().title = "Cirrhosis Mortality Model Risk Scoring"

#bokeh serve C:/Users/ketam/CMMscore/main.py --show
###server deployment
###https://docs.bokeh.org/en/latest/docs/reference/command/subcommands/serve.html
#
#run in cmd
#navigate to directory CMMscore direcotory
#bokeh serve main.py --show
示例#55
0
def animate_update():
    year = slider.value + 1
    if year > end:
        year = start
    slider.value = year

def slider_update(attrname, old, new):
    plot.update(slider.value)

slider = Slider(start=start, end=end, value=0, step=1, title="Year")
slider.on_change('value', slider_update)

def animate():
    if button.label == '► Play':
        button.label = '❚❚ Pause'
        curdoc().add_periodic_callback(animate_update, 200)
    else:
        button.label = '► Play'
        curdoc().remove_periodic_callback(animate_update)

button = Button(label='► Play', width=60)
button.on_click(animate)

# Combine the bokeh plot on plot.state with the widgets
layout = layout([
    [plot.state],
    [slider, button],
], sizing_mode='fixed')

curdoc().add_root(layout)
示例#56
0
p_args = parser.parse_args()

rFP = renderFocalPlane(db=p_args.db)

if p_args.emulate is not None:
    rc = rFP.set_emulation(config_spec=p_args.emulate)
else:
    rFP.current_run = p_args.run

rFP.current_test = p_args.test

# don't set single mode yet!

rFP.set_mode(p_args.mode)

if p_args.hook is not None:
    rFP.load_user_module(name=p_args.hook)

m_lay = rFP.render()

if p_args.png is not None:
    export_png(rFP.map_layout, p_args.png)

if rFP.map_layout is None:  # handle startup screen case
    rFP.layout = layout(rFP.interactors)
else:
    rFP.layout = layout(rFP.interactors, rFP.map_layout)

curdoc().add_root(rFP.layout)
curdoc().title = "Focal Plane Heat Map"
示例#57
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"
示例#58
0
    def __init__(self):

        ### Methods
        self.args = Settings()
        self.index = None
        self.data_getter = None
        self.filter = None
        self._data = None
        self._model_type = None
        self._model_dir = os.path.join(self.args.models_path, 'unique_object')
        self.controls = {}
        self.scene_plotter = ScenePlotter(self._set_head_selection)
        self.known_dir_list = ['unique_object', 'multi_object', 'multi_pred']
        self.model_types = ['mono', 'multi_obj', 'multi_pred']
        self.model_types_labels = [
            "Mono-object", "Multi-objects", "Multi-pred"
        ]
        self.model_sub_types = [
            'CV', 'CA', 'Bicycle', 'CV_LSTM', 'CA_LSTM', 'Bicycle_LSTM',
            'nn_attention'
        ]
        self.know_dataset_list = ['NGSIM', 'Argoverse', 'Fusion']

        ### initialization of the interface

        ## Model type selector

        def update_select_net():
            if self._model_dir is not None:
                file_list = [
                    fn for fn in os.listdir(self._model_dir)
                    if os.path.isfile(os.path.join(self._model_dir, fn))
                ]
                file_list.sort(key=lambda fn: os.stat(
                    os.path.join(self._model_dir, fn)).st_mtime,
                               reverse=True)
                file_list = [os.path.splitext(fn)[0] for fn in file_list]
                self.controls['net'].options = file_list
                # print(self._model_dir)
                # print('file_list')
                # print(file_list)
                if len(file_list) > 0:
                    self.controls['net'].value = file_list[0]
                else:
                    self.controls['net'].value = None

        def update_model_type():

            self._model_type = self.model_types[
                self.controls['multi_mono_object'].active]
            self._model_dir = os.path.join(
                self.args.models_path,
                self.known_dir_list[self.controls['multi_mono_object'].active])

            existing_types = [
                type for type in self.model_sub_types
                if os.path.isdir(os.path.join(self._model_dir, type))
            ]
            self.controls['model_sub_type'].options = existing_types
            print('existing types')
            print(existing_types)
            if len(existing_types) > 0 and not self.controls[
                    'model_sub_type'].value in existing_types:
                self.controls['model_sub_type'].value = existing_types[0]
                return
            set_model_sub_type()
            update_select_net()

        def set_model_sub_type():
            if self.controls['model_sub_type'].value is not None:
                self._model_dir = os.path.join(
                    self._model_dir, self.controls['model_sub_type'].value)
                self.args.model_type = self.controls['model_sub_type'].value
            else:
                self._model_dir = None

        def update_multi_mono_object(attr, old, new):
            update_model_type()
            print(self._model_dir)
            self._set_data_getter()
            print('___')

        dir_list = [
            fn for fn in os.listdir(self.args.models_path)
            if os.path.isdir(os.path.join(self.args.models_path, fn))
        ]
        dir_list = [
            value for value in dir_list if value in self.known_dir_list
        ]
        if not dir_list:
            raise RuntimeError(
                f'It appears that there is no known saved models in the model path {self.args.models_path}'
            )
        else:
            active_num = np.argwhere(
                dir_list[0] == np.array(self.known_dir_list))[0, 0]
        multi_mono_object = RadioButtonGroup(labels=self.model_types_labels,
                                             active=active_num)
        self.controls['multi_mono_object'] = multi_mono_object
        multi_mono_object.on_change('active', update_multi_mono_object)

        ## Model sub type selector
        dir_to_look = os.path.join(self.args.models_path, dir_list[0])
        sub_dir_list = [
            fn for fn in os.listdir(dir_to_look)
            if os.path.isdir(os.path.join(dir_to_look, fn))
        ]
        sub_dir_list = [
            value for value in sub_dir_list if value in self.model_sub_types
        ]
        if not dir_list:
            raise RuntimeError(
                f'It appears that there is no known saved models subtype in the model path {dir_to_look}'
            )
        else:
            active_num = np.argwhere(
                sub_dir_list[0] == np.array(self.model_sub_types))[0, 0]
        model_sub_type = Select(title='Select model type:',
                                value=self.model_sub_types[active_num],
                                options=self.model_sub_types)
        self.controls['model_sub_type'] = model_sub_type
        model_sub_type.on_change('value',
                                 lambda att, old, new: update_model_type())

        ## Model selector
        select = Select(title="Select parameter file:", value=None, options=[])
        self.controls['net'] = select
        select.on_change('value',
                         lambda att, old, new: self._set_data_getter())

        ## Select dataset to use
        select = Select(title='Dataset:',
                        value=self.know_dataset_list[0],
                        options=self.know_dataset_list)
        self.controls['dataset'] = select
        select.on_change(
            'value',
            lambda att, old, new: self._set_data_getter(change_index=True))

        ## Set what to draw
        checkbox_group = CheckboxGroup(labels=[
            'Draw lanes', 'Draw history', 'Draw true future', 'Draw forecast',
            'Draw forecast covariance'
        ],
                                       active=[0, 1, 2, 3, 4])
        self.controls['check_box'] = checkbox_group
        checkbox_group.on_change(
            'active', lambda att, old, new:
            (self._update_cov(), self._update_lanes(), self._update_path()))

        ## Set the number of pred
        n_pred = Slider(start=1,
                        end=6,
                        step=1,
                        value=1,
                        title='Number of prediction hypothesis')
        self.controls['n_pred'] = n_pred
        n_pred.on_change(
            'value', lambda att, old, new:
            (self._update_cov(), self._update_path()))

        ## Sequence ID input
        text_input = TextInput(title="Sequence ID to plot:", value="Random")
        self.controls['sequence_id'] = text_input

        ## Head selection input
        multi_select_head = MultiSelect(
            title='Attention head multiple selection:', value=[], options=[])
        self.controls['Head_selection'] = multi_select_head
        multi_select_head.on_change('value',
                                    self.scene_plotter.set_active_heads)

        ## Refresh all sample
        button = Button(label="Refresh", button_type="success")
        self.controls['refresh'] = button
        button.on_click(lambda event: (self._set_index(), self._set_data()))
        # button.js_on_click(CustomJS(args=dict(p=self.image), code="""p.reset.emit()"""))

        update_multi_mono_object(None, None, None)

        ## Set the interface layout
        inputs = column(*(self.controls.values()), width=320, height=1000)
        inputs.sizing_mode = "fixed"
        lay = layout([[inputs, self.scene_plotter.get_image()]],
                     sizing_mode="scale_both")
        curdoc().add_root(lay)

        self.scene_plotter._tap_on_veh('selected', [], [0])
示例#59
0
nextTrial_button .on_click(next_trial_cb)

prevTrial_button= Button(label='-trial')
prevTrial_button.on_click(prev_trial_cb)

from bokeh.layouts import row
buttonBox = row(label_saccade_button, label_pursuit_button, label_fixation_button, remove_button)
trialSelectBox = row(prevTrial_button, trial_text, nextTrial_button)
#, sizing_mode='scale_width'

###########################################################################
# Get the HTML description header
from os.path import dirname, join
desc = bkM.Div(text=open(join(dirname(__file__), "description.html")).read(), width=800)

###########################################################################
# Add desc, figure and widgets to a layout
from bokeh.layouts import layout
layout = layout([[desc], [fig], [buttonBox],[trialSelectBox]])

###########################################################################
# Add layout to current document
from bokeh.io import curdoc
curdoc().add_root(layout)

# from bokeh.client import push_session
# session = push_session(curdoc())
# session.show()  # open the document in a browser

# session.loop_until_closed()  # run forever
示例#60
0
    p.add_tools(HoverTool(tooltips=None, renderers=[cr], mode='hline'))
    return p

def intro():
    return Div(text="""
        <h3>Welcome to Layout!</h3>
        <p>Hopefully you'll see from the code, that the layout tries to get out of your way
        and do the right thing. Of course, it might not always, so please report bugs as you
        find them and attach them to the epic we're creating <a href="">here</a>.</p>
        <p>This is an example of <code>scale_width</code> mode (happy to continue the conversations
        about what to name the modes). In <code>scale_width</code> everything responds to the width
        that's available to it. Plots alter their height to maintain their aspect ratio, and widgets
        are allowed to grow as tall as they need to accomodate themselves. Often times widgets
        stay the same height, but text is a good example of a widget that doesn't.</p>
        <h4>I want to stress that this was all written in python. There is no templating or
        use of <code>bokeh.embed</code>.</h4>
    """)


l = layout(
    [
        [intro()],
        [text(), scatter()],
        [text()],
        [hover_plot(), text()],
    ],
    sizing_mode='scale_width'
)

show(l)