Ejemplo n.º 1
0
def gen_upd_plot(event):
    try:
        ls_tab = []
        if inp_gen_upd.label != "Update":
            cmst_upd = get_dataset()

            for k in cmst_upd.time_selector:
                pdf_ts[k] = bmo.ColumnDataSource(data=cmst_upd.get_pandas_df(k))

                # Create panel
                ls_tab.append(create_panel(k))

            tabs = bo.layouts.column([
                bo.layouts.row([inp_xaxis, inp_yaxis]),
                bo.layouts.row([bmo.widgets.Tabs(tabs=ls_tab, width=800)]),
            ])
            l.children[-1] = tabs
            inp_gen_upd.label = "Update"

        else:
            cmst_upd = get_dataset()

            pdf_ts_upd = {}
            for k in cmst_upd.time_selector:
                pdf_ts_upd = bmo.ColumnDataSource(data=cmst_upd.get_pandas_df(k))
                pdf_ts[k].data.update(pdf_ts_upd.data)

                dct_buttons[k].callback = bmo.CustomJS(args=dict(source=pdf_ts[k], filename="{}_{}_{}.csv".format(k, inp_time_mean.value, inp_exp.value)),
                                                       code=open(join(dirname(__file__), "download.js")).read())

        hide_spinner()
    except:
        div_spinner.text="""
Ejemplo n.º 2
0
    def __init__(self, names, initial_size, width=900, height=480):
        # Call this once to raise an error early if necessary:
        self._colors = colors.colors(len(names))

        self._start = time.perf_counter()
        self._initial_size = initial_size
        self._sources = collections.OrderedDict(
            [
                (
                    name,
                    {
                        "hist": bm.ColumnDataSource(
                            data={"top": [], "left": [], "right": []}
                        ),
                        "pdf": bm.ColumnDataSource(data={"x": [], "y": []}),
                        "stddev": bm.ColumnDataSource(
                            data={"base": [], "lower": [], "upper": []}
                        ),
                        "median": bm.ColumnDataSource(data={"x": [], "y": []}),
                    },
                )
                for name in names
            ]
        )
        self._width = width
        self._height = height
        self._plot = None
        self._elapsed_rendering_seconds = 0.0
        self._describe_widget = ipdisplay.HTML("")
        self._display_id = str(uuid.uuid1())
Ejemplo n.º 3
0
    def create_ColumnDataSource(self):
        # Get contour paths
        cdata, ctext = self.get_contours()

        # Create ColumnDataSource
        self.ColumnDataSource = bm.ColumnDataSource(cdata)
        self.ColumnDataSourceText = bm.ColumnDataSource(ctext)
Ejemplo n.º 4
0
    def total_6t(self, match):
        self.cds_r = bk_models.ColumnDataSource(self.df_new_6t("red", match))
        all_teams = list(pd.unique(self.data.schedule.team.sort_values()))
        self.cds_b = bk_models.ColumnDataSource(self.df_new_6t("blue", match))
        r_teams = self.cds_r.column_names[1:4]
        b_teams = self.cds_b.column_names[1:4]
        tasks = self.cds_r.data['task']
        plt_name = "Six Team Power Cells Placed: Match " + match

        self.plt_pc = bk_plotting.figure(title=plt_name,
                                         x_range=tasks,
                                         plot_width=700,
                                         plot_height=300,
                                         toolbar_location=None,
                                         tools="hover",
                                         tooltips="$name- @task: @$name")

        self.plt_pc.vbar_stack(r_teams,
                               x=bk_transform.dodge('task',
                                                    -0.17,
                                                    range=self.plt_pc.x_range),
                               width=0.3,
                               source=self.cds_r,
                               legend_label=[" " + x for x in r_teams],
                               color=bk_palettes.Reds3)
        self.plt_pc.vbar_stack(b_teams,
                               x=bk_transform.dodge('task',
                                                    0.17,
                                                    range=self.plt_pc.x_range),
                               width=0.3,
                               source=self.cds_b,
                               color=bk_palettes.Blues3,
                               legend_label=[" " + x for x in b_teams])
        return self.plt_pc
Ejemplo n.º 5
0
    def plot3(model, name, searchfor: str):
        m1 = model[0]
        m2 = model[1]

        if len(model)>2:
            m3 = model[2]
        else:
            m3 = None

        dfp1 = m1.result_df(searchfor)
        dfp2 = m2.result_df(searchfor)
        source1 = bmod.ColumnDataSource(dfp1)
        source2 = bmod.ColumnDataSource(dfp2)

        if m3:
            dfp3 = m3.result_df(searchfor)
            source3 = bmod.ColumnDataSource(dfp3)

        #print(dfp1.values.max())
        #print(dfp2.values.max())
        #print(dfp3.values.max())
        if m3:
            yrange =[0.0, max(dfp1.values.max(), dfp2.values.max(), dfp3.values.max()) ]
        else:
            yrange =[0.0, max(dfp1.values.max(), dfp2.values.max()) ]

        TOOLS = 'pan,box_zoom, box_select,reset'   # wheel_zoom,
#                                                                                                                                                                      545         500
        left =   bplt.figure(title=name[0], x_axis_label='time', y_axis_label='', y_range=yrange, x_axis_type="datetime", toolbar_location="above", tools=TOOLS, width=545, height=500)
        for i,col in enumerate(sorted(list(dfp1.columns))):
            left.line    (x="index", y=col,      source=source1, legend=" "+col,     line_width=2, line_color=COLORS[i],    alpha=0.6)

        middle = bplt.figure(title=name[1], x_axis_label='time', y_axis_label='', y_range=yrange, x_axis_type="datetime", toolbar_location="above", tools=TOOLS, width=545, height=500)
        for i,col in enumerate(sorted(list(dfp2.columns))):
            middle.line  (x="index", y=col,      source=source2, legend=" "+col,     line_width=2, line_color=COLORS[i],    alpha=0.6)

#        left.legend.location = "center_right"
        left.legend.background_fill_alpha = 0.4
#        middle.legend.location = "center_right"
        middle.legend.background_fill_alpha = 0.4

        if m3:
            right =  bplt.figure(title=name[2], x_axis_label='time', y_axis_label='', y_range=yrange, x_axis_type="datetime", toolbar_location="above", tools=TOOLS, width=545, height=600)
            for i,col in enumerate(sorted(list(dfp3.columns))):
                right.line   (x="index", y=col,      source=source3, legend=" "+col,     line_width=2, line_color=COLORS[i],    alpha=0.6)

#            right.legend.location = "top_left"
            right.legend.background_fill_alpha = 0.4

        if m3:
            p = bokeh.layouts.gridplot([[left,middle,right]])
        else:
            p = bokeh.layouts.gridplot([[left,middle]])

        bokeh.plotting.show(p)
Ejemplo n.º 6
0
 def draw(group):
     name = group.columns[0][0]
     color = _colors[name]
     group.columns = group.columns.droplevel(0)
     group = group.dropna()
     quantile_source = bm.ColumnDataSource(
         pd.DataFrame(
             data={
                 "lower": group["25%"],
                 "upper": group["75%"]
             },
             index=group.index,
         ).dropna().reset_index())
     extreme_source = bm.ColumnDataSource(
         pd.DataFrame(
             data={
                 "lower": group["min"],
                 "upper": group["max"]
             },
             index=group.index,
         ).dropna().reset_index())
     plot.line(group.index, group["50%"], line_color=color, legend=name)
     plot.add_layout(
         bm.Band(
             base="time",
             lower="lower",
             upper="upper",
             source=quantile_source,
             fill_color=color,
             fill_alpha=0.2,
         ))
     plot.add_layout(
         bm.Band(
             base="time",
             lower="lower",
             upper="upper",
             source=extreme_source,
             fill_color=color,
             fill_alpha=0.025,
         ))
     plot.line("time",
               "lower",
               line_color=color,
               alpha=0.5,
               source=extreme_source)
     plot.line("time",
               "upper",
               line_color=color,
               alpha=0.5,
               source=extreme_source)
Ejemplo n.º 7
0
    def __init__(self, readers, rule):
        self.readers = readers
        self.rule = rule

        self.source = bom.ColumnDataSource(self.aligned())

        f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end'),
                       tooltips=[('', '$data_y')])

        for reader, color in zip(readers, cycle(Category10_10)):
            p = registry.parse_prefix(reader.prefix)
            label = dict(legend_label=p.label) if p.label else dict()
            f.varea(x='_time',
                    y1=f'{reader.prefix}.μ-',
                    y2=f'{reader.prefix}.μ+',
                    color=color,
                    alpha=.2,
                    source=self.source,
                    **label)
            f.line(x='_time',
                   y=f'{reader.prefix}.μ',
                   color=color,
                   source=self.source,
                   **label)

        default_tools(f)
        x_zeroline(f)
        styling(f)
        p = registry.parse_prefix(readers[0].prefix)
        if p.label:
            legend(f)
        f.title = bom.Title(text=p.group)

        self.figure = f
Ejemplo n.º 8
0
def create_nodes_data_source(network: nx.Graph, layout) -> bm.ColumnDataSource:  # pylint: disable=unused-argument

    nodes, nodes_coordinates = zip(*sorted([x for x in layout.items()]))
    nodes_xs, nodes_ys = list(zip(*nodes_coordinates))
    nodes_source = bm.ColumnDataSource(
        dict(x=nodes_xs, y=nodes_ys, name=nodes, node_id=nodes))
    return nodes_source
Ejemplo n.º 9
0
def structure_jsmol(cif_str):
    from jsmol_bokeh_extension import JSMol
    import bokeh.models as bmd

    script_source = bmd.ColumnDataSource()

    info = dict(
        height="100%",
        width="100%",
        use="HTML5",
        #serverURL="https://chemapps.stolaf.edu/jmol/jsmol/php/jsmol.php",
        #j2sPath="https://chemapps.stolaf.edu/jmol/jsmol/j2s",
        serverURL="detail/static/jsmol/php/jsmol.php",
        j2sPath="detail/static/jsmol/j2s",
        #serverURL="https://www.materialscloud.org/discover/scripts/external/jsmol/php/jsmol.php",
        #j2sPath="https://www.materialscloud.org/discover/scripts/external/jsmol/j2s",
        script="""
set antialiasDisplay ON;
load data "cifstring"

{}

end "cifstring"
""".format(cif_str))

    applet = JSMol(
        width=600,
        height=600,
        script_source=script_source,
        info=info,
        js_url="detail/static/jsmol/JSmol.min.js",
    )

    return applet
Ejemplo n.º 10
0
def bokeh_brushed():
    """these are taken EXACTLY from
    http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html

    """
    # prepare some date
    N = 300
    x = np.linspace(0, 4 * np.pi, N)
    y0 = np.sin(x)
    y1 = np.cos(x)

    # NEW: create a column data source for the plots to share
    source = bkm.ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))

    # create a new plot and add a renderer
    left = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    left.circle('x', 'y0', source=source)

    # create another new plot and add a renderer
    right = bkp.figure(tools=BOKEH_TOOLS, width=350, height=350, title=None)
    right.circle('x', 'y1', source=source)

    # put the subplots in a gridplot
    p = bkp.gridplot([[left, right]])

    return bke.components(p)
Ejemplo n.º 11
0
def point_chart():
    try:
        df_temp = rt.ranking_df()
        df_new = df_temp.filter([
            'avgHatchPoints', 'avgCargoPoints', 'avgClimbPoints',
            'avgHabPoints'
        ],
                                axis=1)
        points_cds = bmodels.ColumnDataSource(df_new)
        tm_col_name = points_cds.column_names[0]
        task = points_cds.column_names[1:]
        tooltips = [("", "team: @index"), ("", "$name: @$name")]
        p = plt.figure(title='Points Chart',
                       x_range=points_cds.data[tm_col_name],
                       plot_width=1100,
                       plot_height=350,
                       tooltips=tooltips,
                       toolbar_location="above")
        hr = p.vbar_stack(task,
                          x=tm_col_name,
                          width=0.4,
                          source=points_cds,
                          color=bpalettes.RdBu4)
        legend = bokeh.models.Legend(items=[(x, [hr[task.index(x)]])
                                            for x in task],
                                     location=(0, 0))
        p.add_layout(legend, 'right')
        p.xaxis.major_label_orientation = 3.14 / 4
        return p
    except Exception:
        # raise err
        # print(err)
        print("The points chart has fallen and cannot get up!")
Ejemplo n.º 12
0
def draw_tsne(df,
              fp,
              alpha=0.69,
              width=1200,
              height=1000,
              show=True,
              title="Homer Embeddings"):
    """ draws an interactive plot for data points with auxilirary info on hover """
    output_file(fp, title=title)

    src = bm.ColumnDataSource(df)
    y = df['y']
    mapper = linear_cmap(field_name='y',
                         palette=Category20_9,
                         low=min(y),
                         high=max(y))
    fig = pl.figure(active_scroll='wheel_zoom',
                    width=width,
                    height=height,
                    title=title)

    fig.scatter('x',
                'y',
                size=10,
                line_color=mapper,
                color=mapper,
                fill_alpha=alpha,
                source=src)

    fig.add_tools(bm.HoverTool(tooltips=[("token", "@word")]))
    pl.save(fig, title=title)
    if show:
        pl.show(fig)
Ejemplo n.º 13
0
def plot_list(figure, x_list, y_list, country, RGBs):
    country = [country] * len(x_list)
    data = {"year": x_list, "value": y_list, "country": country}
    source = bkm.ColumnDataSource(data=data)

    RGB, RGBs = get_random_rgb(RGBs)
    line = figure.line("year",
                       "value",
                       source=source,
                       color=RGB,
                       alpha=0.5,
                       muted_color=RGB,
                       muted_alpha=0)
    circle = figure.circle("year",
                           "value",
                           source=source,
                           line_color=RGB,
                           alpha=0.5,
                           fill_color="white",
                           muted_line_color=RGB,
                           muted_fill_color="white",
                           muted_alpha=0)

    # Done, return
    return (line, circle, RGBs)
Ejemplo n.º 14
0
    def total_1t(self, team, tasks):
        self.cds = bk_models.ColumnDataSource(self.df_new_1t(team, tasks))
        tasks = self.cds.column_names
        tasks = tasks[1:]
        matches = self.cds.data['match']
        plt_title = "Team " + team
        num_tasks = len(tasks)
        if num_tasks == 0:
            colors = []
        elif num_tasks == 1:
            colors = ['#5900b3']
        elif num_tasks == 2:
            colors = ['#5900b3', '#e6b800']
        else:
            colors = bk_palettes.Category20[len(tasks)]
        self.pcplot = bk_plotting.figure(x_range=matches,
                                         plot_height=250,
                                         title=plt_title,
                                         tools="hover",
                                         tooltips="$name: @$name")

        glyphs = self.pcplot.vbar_stack(tasks,
                                        x='match',
                                        width=0.4,
                                        source=self.cds,
                                        color=colors)
        legend_items = [(tasks[i], [glyphs[i]])
                        for i in range(0, len(tasks), 1)]
        legend = bk_models.Legend(items=legend_items, location='center')
        self.pcplot.add_layout(legend, 'right')
        return self.pcplot
Ejemplo n.º 15
0
    def __init__(self):
        self.inp_cif = pn.widgets.FileInput(name='CIF', accept='.cif')
        self.btn_cif = pn.widgets.Button(name='Parse CIF', button_type='primary')
        self.btn_cif.on_click(self.on_click_parse)
        self.ckbox_2x = pn.widgets.Checkbox(name='Force to replicate 2x in C direction')
        self.ckbox_relabel_cab = pn.widgets.Checkbox(name='Relabel cell vectors abc to cab')
        self.ckbox_relabel_bca = pn.widgets.Checkbox(name='Relabel cell vectors abc to bca')

        from structure import structure_jsmol
        import bokeh.models as bmd
        self.jsmol_script_source = bmd.ColumnDataSource()
        self.applet = structure_jsmol(self.jsmol_script_source)

        self.inp_source = pn.widgets.Select(name='CIF source', 
            options={'SI': 'SI', 
                     'SI (CIF)': 'SI (CIF)', 
                     'CSD': 'CSD',
                     'Private Communication': "Priv. Comm."})
        self.inp_csd = pn.widgets.TextInput(name='CSD Number', placeholder='1846139')
        self.inp_name = pn.widgets.TextInput(name='CIF name', placeholder='As used in publication')
        self.inp_dimensionality = pn.widgets.TextInput(name='CIF dimensionality', placeholder='Detected by ASE')
        self.inp_elements = pn.widgets.TextInput(name='CIF elements', placeholder='C,H,...')
        self.inp_modifications = pn.widgets.AutocompleteInput(
            name='CIF modifications', value='none', 
            options=list(set(get_frameworks_df()['Modifications'])), restrict=False)
        self.inp_charge = pn.widgets.Select(name='CIF charge', options={ 'Neutral': 'N', 'Charged': 'C' })
        self.inp_cof_id = pn.widgets.TextInput(name='COF ID', value='none')
        self.btn_mint_id = pn.widgets.Button(name='Mint', button_type='primary')
        self.btn_mint_id.on_click(self.mint_framework_id)

        self.btn_add_cif = pn.widgets.Button(name='Add CIF', button_type='primary')
        self.btn_add_cif.on_click(self.on_click_add)
Ejemplo n.º 16
0
def plotAVO(tools, model):
    '''
    Creates an AVO Intercept and Gradient Plot from a model.
    '''
    #AVO PLOT TYPES
    bkplot = bkp.figure(tools=tools,
                        title='AVO Intercept vs Gradient',
                        y_range=[-0.5, 0.5],
                        x_range=[-0.5, 0.5],
                        x_axis_label='Intercept',
                        y_axis_label='Gradient')
    # iterate over each interface in the model
    for intf in model:
        source = bkm.ColumnDataSource(
            data=dict(A=intf.AVOMod[:, 6], B=intf.AVOMod[:, 7]))
        bkplot.circle('A',
                      'B',
                      color=intf.colour,
                      legend=intf.name,
                      source=source,
                      size=5)
        bkplot.legend.location = 'top_right'
    plotOpt(bkplot)

    return bkplot
Ejemplo n.º 17
0
    def __init__(self, readers, rule):
        [self.reader] = readers
        self.rule = rule

        aligned = self.aligned()
        self.source = bom.ColumnDataSource(aligned)

        f = bop.figure(x_range=bom.DataRange1d(start=0,
                                               follow='end',
                                               range_padding=0),
                       y_range=bom.DataRange1d(start=0),
                       tooltips=[('', '$data_y')])

        p = registry.parse_prefix(self.reader.prefix)
        n_bands = aligned.shape[1] - 1
        assert n_bands % 2 == 1
        for i in range(n_bands):
            color = Viridis256[255 - 256 * i // n_bands]
            lower = aligned.columns[i + 1]
            f.line(x='_time', y=f'{lower}', color=color, source=self.source)

        default_tools(f)
        styling(f)
        p = registry.parse_prefix(readers[0].prefix)
        f.title = bom.Title(text=p.group)

        self.figure = f
    def get_edges_source(network, layout, scale=1.0, normalize=False):

        _, _, weights, xs, ys = NetworkUtility.get_edge_layout_data(network, layout)
        norm = max(weights) if normalize else 1.0
        weights = [ scale * x / norm for x in  weights ]
        lines_source = bm.ColumnDataSource(dict(xs=xs, ys=ys, weights=weights))
        return lines_source
Ejemplo n.º 19
0
    def __init__(self, readers, **kwargs):

        self.readers = readers
        self.source = bom.ColumnDataSource(self.combined())

        f = bop.figure(tooltips=[('', '$data_y')])

        for reader, color in zip(readers, cycle(Category10_10)):
            p = registry.parse_prefix(reader.prefix)
            label = dict(legend_label=p.label) if p.label else dict()
            f.line(x=f'{reader.prefix}.x',
                   y=f'{reader.prefix}.y',
                   color=color,
                   source=self.source,
                   **label)
            f.circle(x=f'{reader.prefix}.x',
                     y=f'{reader.prefix}.y',
                     color=color,
                     source=self.source,
                     **label)

        f.title = bom.Title(text=p.group)
        default_tools(f)

        self.figure = f
Ejemplo n.º 20
0
 def total_pt(self):
     df_temp = self.df
     df_new = df_temp.filter([
         'avg_autoOuterPoints', 'avg_autoInnerPoints',
         'avg_teleInnerPoints', 'avg_teleLowerPoints',
         'avg_teleOuterPoints', 'avg_climbpoints', 'avg_parkpoints'
     ],
                             axis=1)
     points_cds = bmodels.ColumnDataSource(df_new)
     tm_col_name = points_cds.column_names[0]
     task = points_cds.column_names[1:]
     tooltips = [("", "team: @team"), ("", "$name: @$name")]
     p = plt.figure(title='Points Chart',
                    x_range=points_cds.data[tm_col_name],
                    plot_width=1100,
                    plot_height=350,
                    tooltips=tooltips,
                    toolbar_location="above")
     hr = p.vbar_stack(task,
                       x=tm_col_name,
                       width=0.5,
                       source=points_cds,
                       color=bpalettes.Category10[7])
     legend = bokeh.models.Legend(items=[(x, [hr[task.index(x)]])
                                         for x in task],
                                  location=(0, 0))
     p.add_layout(legend, 'right')
     p.xaxis.major_label_orientation = 3.14 / 4
     self.chart = p
     return self.chart
Ejemplo n.º 21
0
def structure_jsmol(cif_node):

    script_source = bmd.ColumnDataSource()
    cif_str = cif_node.get_content()

    info = dict(
        height="100%",
        width="100%",
        use="HTML5",
        #serverURL="https://chemapps.stolaf.edu/jmol/jsmol/php/jsmol.php",
        #j2sPath="https://chemapps.stolaf.edu/jmol/jsmol/j2s",
        serverURL="detail_pyrenemofs/static/jsmol/php/jsmol.php",
        j2sPath="detail_pyrenemofs/static/jsmol/j2s",
        script="""
set antialiasDisplay ON;
load data "cifstring"

{}

end "cifstring"
""".format(cif_str))

    applet = JSMol(
        width=600,
        height=600,
        script_source=script_source,
        info=info,
        js_url="detail_pyrenemofs/static/jsmol/JSmol.min.js",
    )

    return applet
Ejemplo n.º 22
0
    def __init__(self, run_name=-1, prefix=''):
        super().__init__()

        self._reader = stats.Reader(run_name, prefix)

        self._source = bom.ColumnDataSource({'time': np.array([0])})
        self._handle = None
Ejemplo n.º 23
0
def create_edges_layout_data_source(
    network: nx.Graph,
    layout: NodesLayout,
    scale: float = 1.0,
    normalize: bool = False,
    weight: str = 'weight',
    project_range: Tuple[float, float] = None,
    discrete_divisor=None,
) -> bm.ColumnDataSource:

    _, _, weights, xs, ys = layout_edges(network, layout, weight=weight)
    if isinstance(discrete_divisor, int):
        weights = [max(1, x // discrete_divisor) for x in weights]
    # elif project_range is not None:
    #     # same as _project_series_to_range
    #     w_max = max(weights)
    #     low, high = project_range
    #     weights = [ low + (high - low) * (x / w_max) for x in  weights ]
    elif project_range is not None:
        # same as _project_series_to_range
        w_max = max(weights)
        low, high = project_range
        weights = [int(round(max(low, high * (x / w_max)))) for x in weights]
    else:
        norm = max(weights) if normalize else 1.0
        weights = [scale * x / norm for x in weights]

    lines_source = bm.ColumnDataSource(dict(xs=xs, ys=ys, weights=weights))
    return lines_source
Ejemplo n.º 24
0
def plot_steps(out_dict, units):
    """ Plot convergence steps in Bokeh """
    from bokeh.models import BoxAnnotation
    from bokeh.plotting import figure, show, output_notebook
    import bokeh.models as bmd

    tooltips = [("Step (total)", "@index"), ("Step (stage)", "@step"),
                ("Energy", "@energy eV/atom"),
                ("Energy (dispersion)", "@dispersion_energy_au Ha"),
                ("SCF converged", "@scf_converged"),
                ("Cell A", "@cell_a_angs Angs"),
                ("Cell Vol", "@cell_vol_angs3 Angs^3"),
                ("MAX Step", "@max_step_au Bohr"),
                ("Pressure", "@pressure_bar bar")]
    hover = bmd.HoverTool(tooltips=tooltips)
    TOOLS = ["pan", "wheel_zoom", "box_zoom", "reset", "save", hover]

    natoms = out_dict['natoms']
    values = [
        x / natoms * ha2u[units] for x in out_dict['step_info']['energy_au']
    ]
    values = [x - min(values) for x in values]

    data = bmd.ColumnDataSource(data=dict(
        index=range(len(values)),
        step=out_dict['step_info']['step'],
        energy=values,
        dispersion_energy_au=out_dict['step_info']['dispersion_energy_au'],
        scf_converged=out_dict['step_info']['scf_converged'],
        cell_a_angs=out_dict['step_info']['cell_a_angs'],
        cell_vol_angs3=out_dict['step_info']['cell_vol_angs3'],
        max_step_au=out_dict['step_info']['max_step_au'],
        pressure_bar=out_dict['step_info']['pressure_bar'],
    ))

    p = figure(tools=TOOLS,
               title='Energy profile of the DFT minimization',
               height=350,
               width=550)

    p.xgrid.grid_line_color = None
    p.xaxis.axis_label = 'Steps'
    p.yaxis.axis_label = 'Energy ({}/atom)'.format(units)

    # Colored background
    colors = ['red', 'orange', 'green', 'yellow', 'cyan', 'pink', 'palegreen']
    start = 0
    for i, steps in enumerate(out_dict['stage_info']['nsteps']):
        end = start + steps
        p.add_layout(
            BoxAnnotation(left=start,
                          right=end,
                          fill_alpha=0.2,
                          fill_color=colors[i]))
        start = end

    # Trace line and markers
    p.line('index', 'energy', source=data, line_color='blue')
    p.circle('index', 'energy', source=data, line_color='blue', size=3)
    return p
Ejemplo n.º 25
0
    def get_seasonal_source(dataframes: dict) -> dict:
        """
        Get the seasonal data sources

        Args:
            dataframes: the data

        Returns:
            bokeh data sources
        """

        data_sources = {}
        for label, data_table in dataframes.items():
            table_sources = {}
            for table_name, data_columns in data_table.items():
                columns_sources = {}
                for column_name, data_column in data_columns.items():
                    column_sources = {}
                    for frequency, freq_data in data_column.items():
                        freq_sources = {}
                        for name, data_source in freq_data.items():
                            freq_sources[name] = \
                                mdl.ColumnDataSource(data_source)

                        column_sources[frequency] = freq_sources
                    columns_sources[column_name] = column_sources
                table_sources[table_name] = columns_sources
            data_sources[label] = table_sources

        return data_sources
Ejemplo n.º 26
0
def draw_vectors(x,
                 y,
                 radius=10,
                 alpha=0.25,
                 color='blue',
                 width=600,
                 height=400,
                 show=True,
                 **kwargs):
    """ draws an interactive plot for data points with auxilirary info on hover """
    if isinstance(color, str):
        color = [color] * len(x)
    data_source = bm.ColumnDataSource({
        'x': x,
        'y': y,
        'color': color,
        **kwargs
    })

    fig = pl.figure(active_scroll='wheel_zoom', width=width, height=height)
    fig.scatter('x',
                'y',
                size=radius,
                color='color',
                alpha=alpha,
                source=data_source)

    fig.add_tools(
        bm.HoverTool(tooltips=[(key, "@" + key) for key in kwargs.keys()]))
    if show:
        pl.show(fig)
    return fig
Ejemplo n.º 27
0
    def make_map_source(self, df=None):
        import bokeh.models as bm

        # Test if there exists data
        if type(df) != type(None):
            # Make copy of dict
            kdic = self.kdic.copy()
            # Collect
            stemme_pct_list = []
            # Loop through dic
            for i, kommune in enumerate(kdic['kommuner']):
                #kommune_date = kdic['kommuner_dates'][i]
                #print(kommune.replace("Aa", "Å"))
                if kommune in df['Kommune'].values:
                    stemme_pct = df.loc[df['Kommune'] == kommune,
                                        'stemme_pct'].iloc[0]
                    stemme_pct_list.append(stemme_pct)
                # If s is added
                elif kommune[:-1] in df['Kommune'].values:
                    stemme_pct = df.loc[df['Kommune'] == kommune[:-1],
                                        'stemme_pct'].iloc[0]
                    stemme_pct_list.append(stemme_pct)
                elif kommune + "s" in df['Kommune'].values:
                    stemme_pct = df.loc[df['Kommune'] == kommune + "s",
                                        'stemme_pct'].iloc[0]
                    stemme_pct_list.append(stemme_pct)
                elif kommune.replace("Å", "Aa").replace("å", "aa").replace(
                        "Høje Taastrup",
                        "Høje-Taastrup") in df['Kommune'].values:
                    stemme_pct = df.loc[
                        df['Kommune'] ==
                        kommune.replace("Å", "Aa").replace("å", "aa").
                        replace("Høje Taastrup", "Høje-Taastrup"),
                        'stemme_pct'].iloc[0]
                    stemme_pct_list.append(stemme_pct)
                else:
                    #print(kommune, "Not found")
                    stemme_pct_list.append(None)
            # append
            kdic['stemme_pct'] = stemme_pct_list
            # Create data
            self.source = bm.ColumnDataSource(data=kdic)

        else:
            print("Making source from map")
            self.source = bm.ColumnDataSource(data=self.kdic)
    def create_nodes_data_source(network, layout):

        nodes, nodes_coordinates = zip(*sorted([x for x in layout.items()
                                                ]))  # if x[0] in line_nodes]))
        nodes_xs, nodes_ys = list(zip(*nodes_coordinates))
        nodes_source = bm.ColumnDataSource(
            dict(x=nodes_xs, y=nodes_ys, name=nodes, node_id=nodes))
        return nodes_source
Ejemplo n.º 29
0
def source_for_param_space(param_space):
    source = bm.ColumnDataSource(
        pd.DataFrame({
            'tstamp': [],
            'cummax_score': [],
            'mean_test_score': [],
            'params': np.array([], dtype=str),
        }))
    return source
    def get_node_subset_source(network, layout, node_list = None):

        layout_items = layout.items() if node_list is None else [ x for x in layout.items() if x[0] in node_list ]

        nodes, nodes_coordinates = zip(*sorted(layout_items))
        xs, ys = list(zip(*nodes_coordinates))

        nodes_source = bm.ColumnDataSource(dict(x=xs, y=ys, name=nodes, node_id=nodes))
        return nodes_source