Example #1
0
def _internal_bokeh(doc, example=None):
    from bokeh.layouts import row
    import asyncio

    async def clock_retrieve(period_secs: float, ttyout=False) -> None:
        import asyncio

        while True:
            await asyncio.sleep(period_secs)
            clock(period_secs=None, ttyout=ttyout)  # calling itself synchronously

    # tick always in background but we retrieve its measurement every second.
    asyncio.get_running_loop().create_task(clock_retrieve(period_secs=1, ttyout=True))
    # TODO : turn off retrieval when document is detached ?

    clocksourceview = inspect.getsource(Clock)
    thissourceview = inspect.getsource(_internal_bokeh)

    doc.add_root(
        grid(
            [
                [PreText(text=clocksourceview), PreText(text=thissourceview)],
                # to help compare / visually debug
                [clock[["minute", "second"]].plot, clock[["minute", "second"]].table],
                # Note : even if we create multiple clock instances here,
                # the model is the same, and propagation will update all datasources...
            ]
        )
    )
Example #2
0
def Classification_metrics(clf,
                           X_train,
                           y_train,
                           X_test,
                           y_test,
                           exec_time,
                           algo_name=PreText(text="")):

    y_pred = clf.predict(X_test)
    rep = (classification_report(y_test, y_pred, output_dict=True))
    dfrep1 = pd.DataFrame(rep).transpose()
    dfrep1['index'] = dfrep1.index

    source = ColumnDataSource(dfrep1)
    columns = [
        TableColumn(field='index'),
        TableColumn(field='precision'),
        TableColumn(field='recall'),
        TableColumn(field='f1-score'),
        TableColumn(field='support')
    ]

    tet = DataTable(source=source, columns=columns, index_position=None)

    conf = "Confusion matrix : \n" + str(
        np.array(confusion_matrix(y_test,
                                  y_pred))) + " \n Classification report : "
    conf2 = PreText(text=conf, width=550)
    model_info = PreText(text=" Paramètres : " + str(clf.best_params_) +
                         "\n Temps d'execution de : {} sec".format(exec_time))
    learn = learning_graph(clf.best_estimator_, X_train, y_train)
    return column(pre5, algo_name, learn, model_info, conf2, tet)
Example #3
0
def livebokeh(doc):

    doc.add_root(
        layout([
            [PreText(text=inspect.getsource(LiveRandomWalk)), ld.plot],
            # to help compare / visually debug
            [
                [
                    PreText(text=inspect.getsource(simulate)),
                    PreText(text=inspect.getsource(livebokeh)),
                ],
                ld.table,
            ],
        ]))
def fridge(X,Y):
    start_time = time.time()
    name1 = PreText(text=" Ridge selected")
    target= select_cible.value 
    X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8) 
    #define the model and parameters
    ridge = Ridge(normalize=True)   
    params = {'alpha':[.01,.1,1.,10,100]}
    #Fit the model
    regR = GridSearchCV(ridge, param_grid=params, cv=5, n_jobs=6)
    regR.fit(X_train, y_train) #On applique sur les données d'apprentissage
    #predictions on train data
    y_train_predict=regR.predict(X_train)
    #predictions on test data
    y_pred = regR.predict(X_test)
    # Évaluation de l'algorithme
    print(regR.best_params_)#Meilleur paramètrage
    #Graphique
    p1 = figure( title="Prediction de la variable : %s " % target)
    p1.circle(range(len(y_pred)), y_pred[np.argsort(y_test)] , fill_alpha=0.8 , color = 'red', legend_label = "Prédiction")#,source=source)  
    p1.line(range(len(y_test)), np.sort(y_test) , color = 'blue', legend_label = "Echantillon test") #données réelles
    p1.plot_width = 900
 
    exec_time = round((time.time() - start_time),2)
    
    resu1 = row(p1, Regression_metrics(regR, X_train,y_train,X_test,y_test, exec_time, name1)) #column(blabla5,model_info,pre5,learn))
    return resu1
Example #5
0
    def create_info(displaySet, displayParam, ogCity):
        """
            Affiche un panneau textuel contenant des infomations sur le jeu de données
            affiché et la commune sélectionnée.
            Entrées :
                - displaySet : dataFrame contenant les données affichées
                - displayParam : paramètres que l'on souhaite aficher
                - ogCity : extract de la commune sélectionnée
            Sorties : 
                - figure contenant le texte à afficher.
        """
        stats = displaySet[displayParam].dropna().describe(
            percentiles=[0.5]).round(decimals=2)
        stats = stats[stats.index !=
                      'count']  #On supprime la variable "count" deja affichée

        # Modification de l'intitulé des colonnes
        stats.columns = ["Taux " + str(elt) for elt in data_yr]

        # Creation du texte
        infoText = [
            f"<b>Communes affichées</b> : {len(displaySet)}",
            f"<b>Commune sélectionnée</b> : {ogCity['nom']} ({ogCity['Code_DEP']})",
            "</br><b>Statistiques</b> : " + select_imp.value
        ]

        return [Div(text="</br>".join(infoText)), PreText(text=str(stats))]
Example #6
0
 def render_item(item: Tuple[str, str]):
     name, path = item
     path = Path(path)
     if path.is_file():
         content = load_process_output(path)
         content = PreText(text=content)
         return Panel(child=content, title=name)
Example #7
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            cleaner=Select(title="Cleaner:",
                           value='',
                           width=5,
                           options=WaveformCleanerFactory.subclass_names),
            extractor=Select(title="Extractor:",
                             value='',
                             width=5,
                             options=ChargeExtractorFactory.subclass_names),
            extractor_t0=TextInput(title="T0:", value=''),
            extractor_window_width=TextInput(title="Window Width:", value=''),
            extractor_window_shift=TextInput(title="Window Shift:", value=''),
            extractor_sig_amp_cut_HG=TextInput(title="Significant Amplitude "
                                               "Cut (HG):",
                                               value=''),
            extractor_sig_amp_cut_LG=TextInput(title="Significant Amplitude "
                                               "Cut (LG):",
                                               value=''),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=''))

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

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict['cleaner'], self.w_dl1_dict['extractor'],
            self.w_dl1_dict['extractor_t0'],
            self.w_dl1_dict['extractor_window_width'],
            self.w_dl1_dict['extractor_window_shift'],
            self.w_dl1_dict['extractor_sig_amp_cut_HG'],
            self.w_dl1_dict['extractor_sig_amp_cut_LG'],
            self.w_dl1_dict['extractor_lwt'])
Example #8
0
            def handle(doc):
                """
                Note that the handle must create a brand new bokeh model every time it is called.

                Reference: https://github.com/bokeh/bokeh/issues/8579
                """
                spinner = PreText(text="loading...")
                layout = column(spinner)

                def progress():
                    spinner.text += "."

                def load():
                    try:
                        bokeh_model = func(*args, **kwargs)
                        # remove spinner and its update
                        try:
                            doc.remove_periodic_callback(progress)
                        except Exception as e:
                            warnings.warn(
                                f"@servable: trying to remove periodic callback, got {type(e)}: {e}"
                            )
                        layout.children.append(bokeh_model)
                        layout.children.pop(0)
                    except Exception as e:
                        # exception handling
                        message = PreText(
                            text=f"{type(e)}: {e}\n{format_exc()}")
                        layout.children.append(message)

                doc.add_root(layout)
                doc.add_periodic_callback(progress, 5000)
                doc.add_timeout_callback(load, 500)
                doc.title = title or func.__name__
Example #9
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            extractor=Select(
                title="Extractor:",
                value="",
                width=5,
                options=BokehFileViewer.extractor_product.values,
            ),
            extractor_window_start=TextInput(title="Window Start:", value=""),
            extractor_window_width=TextInput(title="Window Width:", value=""),
            extractor_window_shift=TextInput(title="Window Shift:", value=""),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=""),
        )

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

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict["extractor"],
            self.w_dl1_dict["extractor_window_start"],
            self.w_dl1_dict["extractor_window_width"],
            self.w_dl1_dict["extractor_window_shift"],
            self.w_dl1_dict["extractor_lwt"],
        )
Example #10
0
    def document(doc):
        sliders = []
        pre = PreText(text='something')
        select = MultiSelect(title='Select the columns',
                             options=list(df.columns))
        button = Button(label='Update')
        for col in cols:
            MIN, MAX = df[col].min(), df[col].max()
            STEP = (MAX - MIN) / 100
            slider = RangeSlider(start=MIN,
                                 end=MAX,
                                 step=STEP,
                                 value=(MIN, MAX),
                                 title=col)
            sliders.append(slider)

        def update():
            values = []
            txt = '({col} > {low}) & ({col} < {high})'
            for slider in sliders:
                low, high = slider.value
                low, high = float(low), float(high)
                formula = txt.format(col=slider.title, low=low, high=high)
                values.append(formula)
            q = '&'.join(values)
            summary_cols = select.value
            text = df.query(q)[summary_cols].describe()
            pre.text = str(text)

        button.on_click(update)

        l = layout([column(sliders), [select, button]], pre)
        doc.add_root(l)
def flasso(X,Y):
    start_time = time.time()
    name2 = PreText(text=" Lasso selected")
    target= select_cible.value
    X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8) 
    #define the model and parameters
    lasso = Lasso(normalize=True)
    params = {'alpha':[1,.5,.1,.01]}
    #Fit the model
    regL = GridSearchCV(lasso, param_grid=params, cv=5, n_jobs=6)
    regL.fit(X_train, y_train) #On applique sur les données d'apprentissage
    #predictions on train data
    y_train_predict=regL.predict(X_train)
    #predictions on test data
    y_pred = regL.predict(X_test)
    # Évaluation de l'algorithme
    print(regL.best_params_)#Meilleur paramètrage
    #Graphique
    p2 = figure( title="Prediction de la variable : %s " % target)   
    p2.circle(range(len(y_pred)), y_pred[np.argsort(y_test)] , fill_alpha=0.8 , color = 'red', legend_label = "Prédiction")#,source=source)  
    p2.line(range(len(y_test)), np.sort(y_test) , color = 'blue', legend_label = "Echantillon test") #données réelles 
    p2.plot_width = 900
 
    exec_time = round((time.time() - start_time),2)
    
    resu2 = row(p2, Regression_metrics(regL, X_train,y_train,X_test,y_test, exec_time, name2))
    return resu2
Example #12
0
    def create_dl1_widgets(self):
        self.w_dl1_dict = dict(
            cleaner=Select(title="Cleaner:",
                           value='',
                           width=5,
                           options=BokehFileViewer.cleaner_product.values),
            extractor=Select(title="Extractor:",
                             value='',
                             width=5,
                             options=BokehFileViewer.extractor_product.values),
            extractor_t0=TextInput(title="T0:", value=''),
            extractor_window_width=TextInput(title="Window Width:", value=''),
            extractor_window_shift=TextInput(title="Window Shift:", value=''),
            extractor_lwt=TextInput(title="Local Pixel Weight:", value=''))

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

        self.wb_extractor = widgetbox(
            PreText(text="Charge Extractor Configuration"),
            self.w_dl1_dict['cleaner'], self.w_dl1_dict['extractor'],
            self.w_dl1_dict['extractor_t0'],
            self.w_dl1_dict['extractor_window_width'],
            self.w_dl1_dict['extractor_window_shift'],
            self.w_dl1_dict['extractor_lwt'])
Example #13
0
    def document(doc):
        condition = TextInput(title='Enter your condition')
        col = MultiSelect(title='Select the columns', options=list(df.columns))
        button = Button(label='Update')
        pre = PreText()
        pre.text = condition.value

        def update():
            cond = condition.value
            cols = col.value
            text = df.query(cond)[cols].describe()
            pre.text = str(text)

        button.on_click(update)

        l = layout([[[condition, button], col], pre])
        doc.add_root(l)
Example #14
0
def errorMessage(errText):
    pre = PreText(text="""Your text is initialized with the 'text' argument.

    The remaining Paragraph arguments are 'width' and 'height'. For this example,
    those values are 500 and 100 respectively.""",
                  width=500, height=100)
    pre = Paragraph(text=errText, width=500, height=100)
    return pre
Example #15
0
    def test_set_style(self, bokeh_model_page: BokehModelPage) -> None:
        para = PreText(text=text, style={'font-size': '26px'})
        page = bokeh_model_page(para)

        el = find_element_for(page.driver, para)
        assert 'font-size: 26px;' in el.get_attribute('style')

        assert page.has_no_console_errors()
Example #16
0
    def make_about_tab():
        pkg = pkg_resources.require('iplot')[0]
        text = "\n".join(pkg.get_metadata_lines('METADATA'))
        text += "\n\n"
        text += "sys.version:" + sys.version
        pretext = PreText(text=text, width=600, height=600)

        panel = Panel(child=widgetbox(pretext), title="About")
        return panel
Example #17
0
    def test_displays_div_as_text(self,
                                  bokeh_model_page: BokehModelPage) -> None:
        para = PreText(text=text)
        page = bokeh_model_page(para)

        el = find_element_for(page.driver, para, "div pre")
        assert el.get_attribute("innerHTML") == escape(text, quote=None)

        assert page.has_no_console_errors()
Example #18
0
def Regression_metrics(clf,
                       X_train,
                       y_train,
                       X_test,
                       y_test,
                       exec_time,
                       algo_name=PreText(text="")):
    y_train_predict = clf.predict(X_train)
    y_pred = clf.predict(X_test)
    model_info = PreText(
        text=" Paramètres : " + str(clf.best_params_) +
        " \n Le score R2 sur la base d'apprentissage est : {}".format(
            r2_score(y_train, y_train_predict)) +
        " \n Le score R2 sur la base du test est : {}".format(
            r2_score(y_test, y_pred)) +
        " \n Temps d'execution de : {} sec".format(exec_time))
    learn = learning_graph(clf.best_estimator_, X_train, y_train)
    return column(pre5, algo_name, learn, model_info)
Example #19
0
    def test_displays_div_as_text(self, bokeh_model_page) -> None:
        para = PreText(text=text, css_classes=["foo"])

        page = bokeh_model_page(para)

        el = page.driver.find_element_by_css_selector('.foo div pre')
        assert el.get_attribute("innerHTML") == escape(text, quote=None)

        assert page.has_no_console_errors()
Example #20
0
    def test_set_style(self, bokeh_model_page) -> None:
        para = PreText(text=text, css_classes=["foo"], style={'font-size': '26px'})

        page = bokeh_model_page(para)

        el = page.driver.find_element_by_css_selector('.foo div')
        assert 'font-size: 26px;' in el.get_attribute('style')

        assert page.has_no_console_errors()
Example #21
0
def _internal_bokeh(doc, example=None):
    import inspect

    moduleview = inspect.getsource(sys.modules[__name__])
    doc.add_root(
        layout([
            PreText(text=moduleview),
        ])  # TODO : niceties like pygments ??
    )
def fsgd(X,Y):
    start_time = time.time()
    blabla5 = PreText(text=" SGD selected")
    scaler = StandardScaler(with_mean=False, copy=True)
    Feature_norm = scaler.fit_transform(X) #in case different scaled data
    type_feature = np.dtype(Y).name
    if ('int' in type_feature) or ('float' in type_feature):
        #Regression
        X_train, X_test, y_train, y_test = train_test_split(Feature_norm, Y, train_size=0.8)  #or Feature_norm instead of X
        Regressor = SGDRegressor(max_iter=10**7//len(X_train)+1) #Model instance, empirically result for max_iter with 10**6
        params2 = {'alpha':[ 1e-3, 1e-4, 1e-5, 1e-6 ], 'penalty':['l1', 'l2'], 'loss':['squared_loss','huber','epsilon_insensitive']} #Paramètres à tester
        clf = GridSearchCV(Regressor, param_grid=params2, cv=5, n_jobs=6) #,scoring=scorer)
        clf.fit(X_train, y_train) #On applique sur les données d'apprentissage
        #predictions on train data
        y_train_predict=clf.predict(X_train)
        #predictions on test data
        y_pred = clf.predict(X_test)
        print(clf.best_params_)#Meilleur paramètrage
        end_time = time.time()
        exec_time = round(end_time - start_time, 2)
        p5 = figure(title="Prediction de la variable : %s " % select_cible.value)
        p5.circle(range(len(y_pred)), y_pred[np.argsort(y_test)] , fill_alpha=0.8 , color = 'red', legend_label = "Prédiction")#,source=source)  
        p5.line(range(len(y_test)), np.sort(y_test) , color = 'blue', legend_label = "Echantillon test") #données réelles
        p5.plot_width = 900
        resu5 = row(p5, Regression_metrics(clf, X_train,y_train,X_test,y_test, exec_time, blabla5)) #column(blabla5,model_info,pre5,learn))
        return resu5
    else :
        #Classification
        X_train, X_test, y_train, y_test = train_test_split(Feature_norm, Y, train_size=0.8, stratify = Y) #stratify to avoid missing classes
        Classifier = SGDClassifier(max_iter=10**7//len(X_train)+1) #Model instance, empirically result for max_iter with 10**6
        params = {'alpha':[ 1e-3, 1e-4, 1e-5, 1e-6 ], 'penalty':['l1', 'l2'], 'loss':['hinge','log']} #Paramètres à tester
        clf = GridSearchCV(Classifier, param_grid=params, cv=5, n_jobs=6)#scoring=scorer)
        clf.fit(X_train, y_train) #On applique sur les données d'apprentissage
        #predictions on train data
        y_train_predict=clf.predict(X_train)
        #predictions on test data
        y_pred=clf.predict(X_test)
        # Évaluation de l'algorithme
        print(clf.best_params_)
        end_time = time.time()
        exec_time = round(end_time - start_time, 2)
        #Graphique
        categ = y_test.astype("category")
        dico_tmp = dict(enumerate(categ.cat.categories))
        dico = dict((v, k) for k, v in dico_tmp.items())
        #on converti les categories en entier
        y_test_int = y_test.map(dico)
        y_pred_int = pd.Series(y_pred).map(dico)
        dico_bokeh = Paragraph(text=" Dictionnaire des correspondances (clef, valeur) : \n   "+str(dico),  width= 1000)
        #Graphiique
        p5 = figure( title="Prediction de la variable : %s " % select_cible.value, x_axis_label = "x" , y_axis_label = "y")
        p5.circle(range(len(y_test)), y_test_int, fill_alpha=0.8 , color = 'blue', legend_label = "Echantillon test") #données réelles
        p5.circle(range(len(y_pred)), y_pred_int, fill_alpha=0.4 , color = 'red', legend_label = "Prédiction")#,source=source)   
        p5.plot_width = 900
        resu5 = row(column(p5,dico_bokeh), Classification_metrics(clf, X_train,y_train,X_test,y_test, exec_time, blabla5)) #column(blabla5,model_info,pre5,learn))
        return resu5
Example #23
0
 def _setup_text_block(self):
     """
     :return:
     """
     self.text = PreText(
         text=""" """,
         style={'font-size': '10pt'},
         # width=600,
         height=450,
     )
Example #24
0
def fknn(X, Y):

    nomal = PreText(text=" KNN selected")
    start_time = time.time()
    X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8)

    #List Hyperparameters that we want to tune.
    leaf_size = list(range(1, 10))
    n_neighbors = list(range(1, 10, 2))
    p = [1, 2]
    #Convert to dictionary
    hyperparameters = dict(leaf_size=leaf_size, n_neighbors=n_neighbors, p=p)

    #Create new KNN object
    knn_2 = KNeighborsClassifier()

    #Fit the model
    clf = GridSearchCV(knn_2, hyperparameters, cv=10)
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    end_time = time.time()
    exec_time = round(end_time - start_time, 2)

    #Graphique
    categ = y_test.astype("category")
    dico_tmp = dict(enumerate(categ.cat.categories))
    dico = dict((v, k) for k, v in dico_tmp.items())
    #on converti les categories en entier
    y_test_int = y_test.map(dico)
    y_pred_int = pd.Series(y_pred).map(dico)
    dico_bokeh = Paragraph(
        text=" Dictionnaire des correspondances (clef, valeur) : \n   " +
        str(dico),
        width=1000)

    p7 = figure(title="Prediction de la variable : %s " % select_cible.value,
                x_axis_label="x",
                y_axis_label="y")
    p7.circle(range(len(y_pred)),
              y_pred_int,
              fill_alpha=0.8,
              color='red',
              legend_label="Prédiction")  #,source=source)
    p7.circle(range(len(y_test)),
              y_test_int,
              fill_alpha=0.4,
              color='blue',
              legend_label="Echantillon test")  #données réelles
    p7.plot_width = 900

    resu3 = row(
        column(p7, dico_bokeh),
        Classification_metrics(clf, X_train, y_train, X_test, y_test,
                               exec_time, nomal))
    return resu3
Example #25
0
def panel():
    'Assemble widgets and plots '
    global sample_size_slider, number_of_samples_slider 
    #print(f'panel means: {samples_ar.mean()} {current_sample_ar.mean()}')
    # kwargs = dict(subtitle= 'Population', plot_height = 160, line_width=3, line_color='grey')
    text_area = PreText(text=description, width=400)
    plots = column(
        plot_rug(pop_cds, subtitle="Distribution of Sample Averages", plot_height = 400, line_color='lightblue'),
        plot_rug(sample_cds, subtitle='Distribution of All Individuals Sampled.'))
    s_panel = row(plots, column(sample_size_slider, number_of_samples_slider, text_area, width=400))
    return s_panel
Example #26
0
    def modify_doc(doc):

        t1 = PreText(height=20, width=200)
        t2 = PreText(height=20, width=200)
        t3 = PreText(height=20, width=100)
        s1 = Slider(start=0, end=len(df), value=0, title='Start')
        s2 = Slider(start=1, end=len(df) - 1, value=len(df), title='Length')
        map = figure(plot_width=width,
                     plot_height=height,
                     x_axis_type='mercator',
                     y_axis_type='mercator',
                     match_aspect=True)
        map.add_tile(TILE)
        map.circle(x=N.SPHERICAL_MERCATOR_X,
                   y=N.SPHERICAL_MERCATOR_Y,
                   source=df,
                   name='map')
        elevation = figure(plot_width=width, plot_height=height // 10)
        elevation.line(x=N.DISTANCE,
                       y=N.ELEVATION,
                       source=df,
                       name='elevation')
        c = column(row(s1, s2), row(t1, t2, t3), map, elevation)

        def mkplot(l1, l2):
            l2 = min(len(df) - 1, l1 + l2)
            t1.text = '%9.5f,%9.5f' % (df.iloc[l1]['Longitude'],
                                       df.iloc[l1]['Latitude'])
            t2.text = '%9.5f,%9.5f' % (df.iloc[l2]['Longitude'],
                                       df.iloc[l2]['Latitude'])
            t3.text = '%4.2fkm' % (
                (df.iloc[l2]['Distance'] - df.iloc[l1]['Distance']) / 1000)
            get_renderer(map, 'map').data_source.data = df[l1:l2]
            get_renderer(elevation, 'elevation').data_source.data = df[l1:l2]

        s1.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        s2.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        doc.add_root(c)
Example #27
0
        def render_process(pid: int) -> Optional[Model]:
            process_data = node_data[node_data[PID_KEY] == pid]
            max_rss = process_data[RSS_KEY].max()
            avg_cpu = process_data[AVG_CPU_KEY].mean()
            process = [
                p for p in report.cluster.nodes[node.hostname].processes if p.pid == pid
            ]
            if not process:
                logging.warning(f"Process {node.hostname}/{pid} not found in cluster")
                return
            process = process[0]

            range = get_time_range(process_data[DATETIME_KEY])

            mib_divisor = 1024.0 * 1024
            mem = resample(
                process_data[RSS_KEY] / mib_divisor, process_data[DATETIME_KEY]
            )
            mem_figure = prepare_time_range_figure(range)
            mem_figure.yaxis[0].formatter = NumeralTickFormatter()
            mem_figure.yaxis.axis_label = "RSS (MiB)"
            mem_figure.y_range = Range1d(0, max_rss / mib_divisor + 100.0)
            mem_figure.add_tools(HoverTool(tooltips=[("RSS (MiB)", "@rss")]))

            data = ColumnDataSource(dict(rss=mem, x=mem.index))
            mem_figure.line(
                x="x", y="rss", color="red", legend_label="Memory", source=data
            )

            cpu = resample(process_data[AVG_CPU_KEY], process_data[DATETIME_KEY])
            cpu_figure = prepare_time_range_figure(range)
            cpu_figure.yaxis[0].formatter = NumeralTickFormatter(format="0 %")
            cpu_figure.yaxis.axis_label = "Avg. CPU usage (%)"
            cpu_figure.y_range = Range1d(0, 1)
            cpu_figure.add_tools(HoverTool(tooltips=[("Avg. CPU usage", "@cpu")]))

            data = ColumnDataSource(dict(cpu=cpu / 100.0, x=cpu.index))
            cpu_figure.line(
                x="x", y="cpu", color="blue", legend_label="CPU usage (%)", source=data
            )

            summary = PreText(
                text=f"""
PID: {pid}
Key: {process.key}
Max. RSS: {humanize.naturalsize(max_rss, binary=True)}
Avg. CPU: {avg_cpu:.02f} %
""".strip()
            )

            columns = [summary, mem_figure, cpu_figure]
            return Panel(child=Column(children=columns), title=process.key)
Example #28
0
def _internal_bokeh(doc, example=None):

    # Note: if launched by package, the result of _internal_example is passed via kwargs
    random_data_model = example[0]
    view = example[1]
    fview = example[2]

    moduleview = inspect.getsource(sys.modules[__name__])

    doc.add_root(
        layout([[  # we want one row with two columns
            [PreText(text=moduleview)],
            [fview.plot, random_data_model.view.table, view.plot],
        ]]))
Example #29
0
 def load():
     try:
         bokeh_model = func(*args, **kwargs)
         # remove spinner and its update
         try:
             doc.remove_periodic_callback(progress)
         except Exception:
             pass
         layout.children.append(bokeh_model)
         layout.children.pop(0)
     except Exception as e:
         # exception handling
         message = PreText(text=f"{type(e)}: {e}\n{format_exc()}")
         layout.children.append(message)
Example #30
0
    def modify_doc(doc):

        t1 = PreText(height=20, width=200)
        t2 = PreText(height=20, width=200)
        t3 = PreText(height=20, width=100)
        s1 = Slider(start=0, end=len(df), value=0, title='Start')
        s2 = Slider(start=1, end=len(df) - 1, value=len(df), title='Length')
        f = figure(plot_width=width,
                   plot_height=height,
                   x_axis_type='mercator',
                   y_axis_type='mercator')
        c = column(row(s1, s2), row(t1, t2, t3), f)

        def mkplot(l1, l2):
            l2 = min(len(df) - 1, l1 + l2)
            t1.text = '%9.5f,%9.5f' % (df.iloc[l1]['Longitude'],
                                       df.iloc[l1]['Latitude'])
            t2.text = '%9.5f,%9.5f' % (df.iloc[l2]['Longitude'],
                                       df.iloc[l2]['Latitude'])
            t3.text = '%4.2fkm' % (
                (df.iloc[l2]['Distance'] - df.iloc[l1]['Distance']) / 1000)
            f = figure(plot_width=width,
                       plot_height=height,
                       x_axis_type='mercator',
                       y_axis_type='mercator')
            f.add_tile(TILE)
            f.circle(x='Spherical Mercator X',
                     y='Spherical Mercator Y',
                     source=df[l1:l2])
            c.children[2] = f

        s1.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        s2.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        doc.add_root(c)