예제 #1
0
def create_clusters_mean_plot(source: bm.ColumnDataSource,
                              filter_source: dict = None) -> bm.Box:

    figure_opts = dict(plot_width=600,
                       plot_height=620,
                       title="Cluster mean trends (pchip spline)")
    hover_opts = dict(tooltips=[('Cluster', '@legend')],
                      show_arrow=False,
                      line_policy='next')

    line_opts = dict(
        legend_field='legend',
        line_color='color',
        line_width=5,
        line_alpha=0.4,
        hover_line_color='color',
        hover_line_alpha=1.0,
    )

    p: bp.Figure = bp.figure(tools=[bm.HoverTool(**hover_opts),
                                    bm.TapTool()],
                             **figure_opts)

    p.xaxis.major_label_orientation = 1
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.minor_tick_line_color = None
    # p.xaxis.ticker = list(range(1945, 1990))
    p.y_range.start = 0

    _ = p.multi_line(source=source, xs='xs', ys='ys', **line_opts)

    p.legend.location = "top_left"
    p.legend.click_policy = "hide"

    if filter_source is not None:

        callback: bm.CustomJS = _create_multiline_multiselect_callback(source)

        multi_select: bm.MultiSelect = bm.MultiSelect(
            title='Show/hide',
            options=filter_source['options'],
            value=filter_source['values'],
            size=min(len(filter_source['options']), 30),
        )

        multi_select.js_on_change('value', callback)

        p: bm.Box = bokeh.layouts.row(p, multi_select)

    return p
예제 #2
0
def plot_clusters_count(source: bm.ColumnDataSource):

    figure_opts = dict(plot_width=500,
                       plot_height=600,
                       title="Cluster token count")

    hover_opts = dict(tooltips='@legend: @count words',
                      show_arrow=False,
                      line_policy='next')

    bar_opts = dict(
        legend_field='legend',
        fill_color='color',
        fill_alpha=0.4,
        hover_fill_alpha=1.0,
        hover_fill_color='color',
        line_color='color',
        hover_line_color='color',
        line_alpha=1.0,
        hover_line_alpha=1.0,
        height=0.75,
    )

    p = bp.figure(tools=[bm.HoverTool(**hover_opts),
                         bm.TapTool()],
                  **figure_opts)

    # y_range=source.data['clusters'],
    p.yaxis.major_label_orientation = 1
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.minor_tick_line_color = None
    p.x_range.start = 0

    _ = p.hbar(source=source, y='cluster', right='count', **bar_opts)

    return p
예제 #3
0
파일: main.py 프로젝트: ltalirz/CCGenome
    elif v['type'] == 'list':
        if 'labels' not in v.keys():
            v['labels'] = None
        filters_dict[k] = get_select(desc, v['values'], v['default'],
                                     v['labels'])

# plot button, output, graph
btn_plot = Button(label='Plot', button_type='primary')
info_block = PreText(text='', width=500, height=100)
plot_info = PreText(text='', width=300, height=100)

load_preset(None, None, get_preset_label_from_url())

source = bmd.ColumnDataSource(data=data_empty)
hover = bmd.HoverTool(tooltips=[])
tap = bmd.TapTool()

colorscale = [
    '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC',
    '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC', '#CCFFCC',
    '#CCFFCC', '#CCFFCC', '#CCFFCC', '#80FF66', '#80FF66', '#80FF66',
    '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66',
    '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66',
    '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#80FF66',
    '#80FF66', '#80FF66', '#80FF66', '#80FF66', '#19FF19', '#19FF19',
    '#19FF19', '#19FF19', '#19FF19', '#19FF19', '#19FF19', '#19FF19',
    '#19FF19', '#19FF19', '#19FF19', '#19FF19', '#19FF19', '#009900',
    '#009900', '#009900', '#009900', '#009900', '#009900', '#009900',
    '#009900', '#009900', '#009900', '#009900', '#009900', '#009900',
    '#009900', '#009900', '#009900', '#009900', '#009900', '#009900',
    '#009900', '#009900', '#009900', '#009900', '#009900', '#009900',
예제 #4
0
def get_plot(inp_x, inp_y, inp_clr):
    """Returns a Bokeh plot of the input values, and a message with the number of COFs found."""
    q_list = [quantities[label] for label in [inp_x, inp_y, inp_clr]]
    db_nodes_dict = get_db_nodes_dict(
    )  # TODO: try to move outside, to load it once!
    results = get_figure_values(
        db_nodes_dict,
        q_list)  #returns [inp_x_value, inp_y_value, inp_clr_value, cif.label]

    # prepare data for plotting
    nresults = len(results)
    msg = "{} MOFs found.<br> <b>Click on any point for details!</b>".format(
        nresults)

    label, x, y, clrs = zip(*results)
    x = list(map(float, x))
    y = list(map(float, y))
    clrs = list(map(float, clrs))
    mat_id = label

    data = {'x': x, 'y': y, 'color': clrs, 'mat_id': mat_id}

    # create bokeh plot
    source = bmd.ColumnDataSource(data=data)

    hover = bmd.HoverTool(tooltips=[])
    tap = bmd.TapTool()
    p_new = bpl.figure(
        plot_height=600,
        plot_width=600,
        toolbar_location='above',
        tools=[
            'pan',
            'wheel_zoom',
            'box_zoom',
            'save',
            'reset',
            hover,
            tap,
        ],
        active_drag='box_zoom',
        output_backend='webgl',
        title='',  # trick: title is used as the colorbar label
        title_location='right',
        x_axis_type=q_list[0]['scale'],
        y_axis_type=q_list[1]['scale'],
    )
    p_new.title.align = 'center'
    p_new.title.text_font_size = '10pt'
    p_new.title.text_font_style = 'italic'
    update_legends(p_new, q_list, hover)
    tap.callback = bmd.OpenURL(url="detail_pyrenemofs?mat_id=@mat_id")

    cmap = bmd.LinearColorMapper(palette=Plasma256,
                                 low=min(clrs),
                                 high=max(clrs))
    fill_color = {'field': 'color', 'transform': cmap}
    p_new.circle('x', 'y', size=10, source=source, fill_color=fill_color)
    cbar = bmd.ColorBar(color_mapper=cmap, location=(0, 0))
    p_new.add_layout(cbar, 'right')

    return p_new, msg
예제 #5
0
def get_plot(appl):  #pylint: disable=too-many-locals
    """Make the bokeh plot for a given application.

    1. read important metrics from applications.yml
    2. read metadata for thes metricy in quantities.yml
    3. query the AiiDA database for values
    4. rank materials according to their performance
    5. generate the plot and return a message stating the number of found materials
    """

    # Query for results
    q_list = tuple([quantities[label] for label in [appl['x'], appl['y']]])
    results_wnone = get_data_aiida(
        q_list)  #[[id_material, name_material, class_material, xval, yval]]

    # Clean the query from None values projections
    results = []
    for l in results_wnone:
        if None not in l:
            results.append(l)

    # Prepare data for plotting
    nresults = len(results)
    if not results:
        results = [['none', 'none', 'none', 0, 0]]
        msg = "No materials found"
    else:
        msg = "{} materials shown".format(nresults)

    mat_id, name, class_mat, x, y = zip(*results)

    x = list(map(float, x))
    y = list(map(float, y))
    rank = rank_materials(x, y, appl['wx'], appl['wy'])

    # Setup plot
    hover = bmd.HoverTool()
    hover.tooltips = [
        ("name", "@name"),
        ("MAT_ID", "@mat_id"),
        (q_list[0]["label"], "@x {}".format(q_list[0]["unit"])),
        (q_list[1]["label"], "@y {}".format(q_list[1]["unit"])),
        ('ranking', '@color'),
    ]

    tap = bmd.TapTool()
    p = bpl.figure(
        plot_height=600,
        plot_width=600,
        toolbar_location="right",  # choose: above, below, right, left
        tools=[
            'pan',
            'wheel_zoom',
            'box_zoom',
            'save',
            'reset',
            hover,
            tap,
        ],
        active_drag='box_zoom',
        output_backend='webgl',
        x_axis_type=q_list[0]['scale'],
        y_axis_type=q_list[1]['scale'],
        x_axis_label="{} [{}]".format(q_list[0]["label"], q_list[0]["unit"]),
        y_axis_label="{} [{}]".format(q_list[1]["label"], q_list[1]["unit"]),
    )

    tap.callback = bmd.OpenURL(url="details?mat_id=@mat_id")

    cmap = bmd.LinearColorMapper(palette=myRdYlGn)
    fill_color = {'field': 'color', 'transform': cmap}

    source = bmd.ColumnDataSource(
        data={
            'mat_id': mat_id,
            'name': name,
            'class_mat': class_mat,
            'x': x,
            'y': y,
            'color': rank,
        })
    p.circle(x='x',
             y='y',
             size=10,
             source=source,
             fill_color=fill_color,
             muted_alpha=0.2)

    #cbar = bmd.ColorBar(color_mapper=cmap, location=(0, 0))
    #p.add_layout(cbar, 'right') #show colorbar

    return p, msg
예제 #6
0
def plot_isotherms(mat_id):  #pylint: disable=too-many-locals
    """Plot figure with all isotherms."""

    nodes_dict = get_isotherm_nodes(mat_id)

    tooltips = [
        ("Molecule", "@legend_label"),
        ("Uptake (mol/kg)", "@q_avg"),
    ]
    hover = bmd.HoverTool(tooltips=tooltips)
    tap = bmd.TapTool()
    tap.callback = bmd.OpenURL(url=get_provenance_url(uuid="@uuid"))
    TOOLS = ["pan", "wheel_zoom", "box_zoom", "reset", "save", hover, tap]

    p1 = figure(tools=TOOLS, height=350, width=450)
    p1.xaxis.axis_label = 'Pressure (bar)'
    p1.yaxis.axis_label = 'Uptake (mol/kg)'

    for gas, gas_dict in gasses.items():
        if gas not in nodes_dict:
            continue

        for node in nodes_dict[gas]:
            try:  # avoid to fail if there are problems with one dict
                isot_out = node.get_dict()

                if isot_out['is_porous']:
                    p = isot_out['isotherm']["pressure"]  #(bar)
                    q_avg = isot_out['isotherm']["loading_absolute_average"]  #(mol/kg)
                    q_dev = isot_out['isotherm']["loading_absolute_dev"]  #(mol/kg)
                    q_upper = np.array(q_avg) + np.array(q_dev)
                    q_lower = np.array(q_avg) - np.array(q_dev)
                    h_avg = isot_out['isotherm']["enthalpy_of_adsorption_average"]  #(kJ/mol)
                    h_dev = isot_out['isotherm']["enthalpy_of_adsorption_dev"]  #(kJ/mol)
                    # TRICK: use the enthalpy from widom (energy-RT) which is more accurate that the one at 0.001 bar
                    # (and which also is NaN for weakly interacting systems)
                    h_avg[0] = isot_out['adsorption_energy_widom_average'] - isot_out['temperature'] / 120.027
                    h_dev[0] = isot_out['adsorption_energy_widom_dev']
                    h_upper = np.array(h_avg) + np.array(h_dev)
                    h_lower = np.array(h_avg) - np.array(h_dev)
                else:
                    p = [0, 100]
                    q_avg = q_upper = q_lower = h_avg = h_upper = h_lower = [0, 0]

                legend_label = "{} ({}K)".format(gas_dict['legend'], int(isot_out['temperature']))

                data = dict(p=p,
                            q_avg=q_avg,
                            q_upper=q_upper,
                            q_lower=q_lower,
                            h_avg=h_avg,
                            h_upper=h_upper,
                            h_lower=h_lower,
                            uuid=[str(node.uuid) for _ in q_avg],
                            legend_label=[legend_label] * len(p))
                source = bmd.ColumnDataSource(data=data)

                p1.line(x='p',
                        y='q_avg',
                        source=source,
                        line_color=gas_dict['color'],
                        line_width=2,
                        legend_label=legend_label)
                p1.circle(x='p', y='q_avg', source=source, color=gas_dict['color'], size=5, legend_label=legend_label)
                p1.add_layout(bmd.Whisker(source=source, base="p", upper="q_upper", lower="q_lower"))
            except (KeyError, TypeError):
                continue

    p1.legend.location = "bottom_right"

    fig = p1

    return fig
예제 #7
0
def get_plot(inp_x, inp_y, inp_clr):
    """Returns a Bokeh plot of the input values, and a message with the number of COFs found."""
    q_list = [config.quantities[label] for label in [inp_x, inp_y, inp_clr]]
    results_wnone = get_data_aiida(q_list)  #returns ***

    # dump None lists that make bokeh crash
    results = []
    for l in results_wnone:
        if None not in l:
            results.append(l)

    # prepare data for plotting
    nresults = len(results)
    if not results:
        results = [['x', 'x', 'x', 0, 0, 0]]
        msg = "No matching COFs found."
    else:
        msg = "{} COFs found.<br> <b>Click on any point for details!</b>".format(nresults)

    mat_id, mat_name, mat_class, x, y, clrs = zip(*results)  # returned ***
    x = list(map(float, x))
    y = list(map(float, y))
    clrs = list(map(float, clrs))

    data = {'x': x, 'y': y, 'color': clrs, 'mat_id': mat_id, 'mat_name': mat_name, 'mat_class': mat_class}

    # create bokeh plot
    source = bmd.ColumnDataSource(data=data)

    hover = bmd.HoverTool(tooltips=[])
    tap = bmd.TapTool()
    p_new = bpl.figure(
        plot_height=600,
        plot_width=600,
        toolbar_location='above',
        tools=[
            'pan',
            'wheel_zoom',
            'box_zoom',
            'save',
            'reset',
            hover,
            tap,
        ],
        active_drag='box_zoom',
        output_backend='webgl',
        title='',  # trick: title is used as the colorbar label
        title_location='right',
        x_axis_type=q_list[0]['scale'],
        y_axis_type=q_list[1]['scale'],
    )
    p_new.title.align = 'center'
    p_new.title.text_font_size = '10pt'
    p_new.title.text_font_style = 'italic'
    update_legends(p_new, q_list, hover)
    tap.callback = bmd.OpenURL(url="detail?mat_id=@mat_id")

    # Plot vertical line for comparison with amine-based technology (PE=1MJ/kg)
    if inp_y == 'CO2 parasitic energy (coal)':
        hline = bmd.Span(location=1, dimension='width', line_dash='dashed', line_color='grey', line_width=3)
        p_new.add_layout(hline)
        hline_descr = bmd.Label(x=30, y=1, x_units='screen', text_color='grey', text='amine-based sep.')
        p_new.add_layout(hline_descr)

    cmap = bmd.LinearColorMapper(palette=Plasma256, low=min(clrs), high=max(clrs))
    fill_color = {'field': 'color', 'transform': cmap}
    p_new.circle('x', 'y', size=10, source=source, fill_color=fill_color)
    cbar = bmd.ColorBar(color_mapper=cmap, location=(0, 0))
    p_new.add_layout(cbar, 'right')

    return p_new, msg
예제 #8
0
def get_plot(inp_x, inp_y, inp_clr):
    """Creates holoviews plot"""
    data, msg = prepare_data(inp_x, inp_y, inp_clr)
    source = bmd.ColumnDataSource(data=data)

    # hovering
    hover = get_hover(inp_x, inp_y, inp_clr)

    # tap
    tap = bmd.TapTool()
    tap.callback = bmd.OpenURL(url=explore_url + "/details/@uuid")

    # plot
    points = hv.Points(
        source.data,
        kdims=['x', 'y'],
        vdims=['color', 'name', 'uuid'],
    )
    filtered = points.apply(filter_points,
                            streams=[hv.streams.RangeXY(source=points)])

    p_shaded = datashade(
        filtered,
        width=plot_px,
        height=plot_px,
        cmap=Plasma256,
        aggregator=ds.mean('color')  # we want color of mean value under pixel
    )
    p_hover = filtered.apply(hover_points)

    update_fn = functools.partial(update_legends,
                                  inp_x=inp_x,
                                  inp_y=inp_y,
                                  inp_clr=inp_clr)
    hv_plot = (dynspread(p_shaded) * p_hover).opts(
        hv.opts.Points(
            tools=[
                tap,
                'pan',
                'box_zoom',
                'save',
                'reset',
                hover,
            ],
            active_tools=['wheel_zoom'],
            #active_scroll='box_zoom',
            #active_drag='box_zoom',
            alpha=0.2,
            hover_alpha=0.5,
            size=10,
            width=plot_px,
            height=plot_px,
            color='color',
            cmap=Plasma256,
            colorbar=True,
            show_grid=True,
        ),
        hv.opts(toolbar='above', finalize_hooks=[update_fn]),
    )
    #     output_backend='webgl',

    p_new = hv_renderer.get_plot(hv_plot).state

    return p_new, msg