Example #1
0
def render(pkg):
    global current_rpm, level, hover, source
    current_rpm = pkg
    hist.append([pkg, level])
    newG = Graph()
    nrn, nre = graphe(pkg, newG)
    if nrn == 0:
        return Div(text="This package is unknown")
    newgraph = from_networkx(newG, spring_layout, scale=4, center=(0, 0))
    newplot = figure(title="RPM network",
                     sizing_mode="scale_width",
                     aspect_ratio=2,
                     x_range=(-2.2, 2.2),
                     y_range=(-2.1, 2.1),
                     tools="tap",
                     toolbar_location=None)
    newplot.axis.visible = False
    newplot.grid.visible = False
    newgraph.node_renderer.glyph = Rect(height=0.07,
                                        width=0.1,
                                        fill_color="color",
                                        fill_alpha=0.0,
                                        line_alpha=0.0)
    if nre != 0:
        newgraph.edge_renderer.glyph = MultiLine(line_color="color",
                                                 line_alpha=0.8)
    newplot.renderers.append(newgraph)
    source = newgraph.node_renderer.data_source
    xcoord = CustomJSTransform(v_func=code % "0",
                               args=dict(provider=newgraph.layout_provider))
    ycoord = CustomJSTransform(v_func=code % "1",
                               args=dict(provider=newgraph.layout_provider))
    source.selected.on_change('indices', selected)
    labels = LabelSet(x=transform('index', xcoord),
                      y=transform('index', ycoord),
                      text='name',
                      text_font_size="12px",
                      y_offset=-6,
                      x_offset="offset",
                      background_fill_color='color',
                      background_fill_alpha=0.85,
                      border_line_color='color',
                      border_line_alpha=1.0,
                      source=source,
                      render_mode='canvas')
    newplot.add_tools(hover)
    newplot.add_layout(labels)
    return newplot
Example #2
0
def general_mapper(column, mapped_to, to_map):
    m = dict(zip(to_map, mapped_to))
    v_func = """
    const first = xs[0]
    const norm = new Float64Array(xs.length)
    for (let i = 0; i < xs.length; i++) {
        norm[i] = m[xs[i]];
    }
    return norm
    """
    t = CustomJSTransform(args={"m": m}, v_func=v_func)

    return transform(column, t)
# add the labels to the edge renderer data source
source = r.edge_renderer.data_source

#source.data['names'] = ["{x}-{y}".format(x=x, y=y) for (x,y) in zip(source.data['start'], source.data['end'])]
source.data['names'] = df['weight'].values
# create a transform that can extract and average the actual x,y positions
code = """
    var result = new Float64Array(xs.length)
    coords = provider.get_edge_coordinates(source)[%s]
    for (var i = 0; i < xs.length; i++) {
        result[i] = (coords[i][0] + coords[i][1])/2
    }
    return result
"""
xcoord = CustomJSTransform(v_func=code % "0",
                           args=dict(provider=r.layout_provider,
                                     source=source))
ycoord = CustomJSTransform(v_func=code % "1",
                           args=dict(provider=r.layout_provider,
                                     source=source))

# Use the transforms to supply coords to a LabelSet
labels = LabelSet(x=transform('start', xcoord),
                  y=transform('start', ycoord),
                  text='names',
                  text_font_size="10px",
                  x_offset=5,
                  y_offset=5,
                  source=source,
                  render_mode='canvas',
                  text_color='#ff0000')
Example #4
0
from bokeh.transform import factor_cmap, transform

years = [str(x) for x in sorted(df.Year.unique())]
locations = sorted(df.Location.unique())
groups = list(df.AgeGrp.unique())

# pyramid plot of age groups by gender

ages = ColumnDataSource(data=dict(AgeGrp=[], Sex=[], Value=[]))

gender_transform = CustomJSTransform(args=dict(source=ages),
                                     func="",
                                     v_func="""
    const val = new Float64Array(xs.length)
    for (let i = 0; i < xs.length; i++) {
        if (source.data['Sex'][i] == 'Male')
            val[i] = -xs[i]
        else
            val[i] = xs[i]
    }
    return val
""")

pyramid = figure(width=600,
                 height=500,
                 toolbar_location=None,
                 y_range=groups,
                 title="Population Breakdown by Age Group and Gender",
                 x_axis_label="Population (Millions)",
                 y_axis_label="Age Group")
pyramid.hbar(y="AgeGrp",
             height=1,
))

goog_source = ColumnDataSource(data=dict(
    goog_date=datetime(GOOG['date']),
    goog_close=GOOG['adj_close'],
))

v_func = """
    const first = xs[0]
    const norm = new Float64Array(xs.length)
    for (let i = 0; i < xs.length; i++) {
        norm[i] = xs[i] / first
    }
    return norm
"""
normalize = CustomJSTransform(v_func=v_func)

plot.line(x='aapl_date',
          y=transform('aapl_close', normalize),
          line_width=2,
          color='#cf3c4d',
          alpha=0.6,
          legend_label="Apple",
          source=aapl_source)
plot.line(x='goog_date',
          y=transform('goog_close', normalize),
          line_width=2,
          color='#2f7bce',
          alpha=0.6,
          legend_label="Google",
          source=goog_source)
plot.yaxis.axis_label = 'Normalized Price'

aapl_source = ColumnDataSource(data=dict(
    aapl_date=datetime(AAPL['date']),
    aapl_close=AAPL['adj_close'],
))

goog_source = ColumnDataSource(data=dict(
    goog_date=datetime(GOOG['date']),
    goog_close=GOOG['adj_close'],
))

v_func = """\
    var first = xs[0]
    var norm = new Float64Array(xs.length)
    for (i = 0; i < xs.length; i++) {
        norm[i] = xs[i] / first
    }
    return norm
"""
normalize = CustomJSTransform(func="", v_func=v_func)

plot.line(x='aapl_date', y={'field': 'aapl_close', 'transform': normalize},
        color='red', legend="Apple", source=aapl_source)
plot.line(x='goog_date', y={'field': 'goog_close', 'transform': normalize},
        color='blue', legend="Google", source=goog_source)
plot.legend.location='top_left'

output_file("customjs_transform.html")
show(plot)
def test_CustomJSTransform() -> None:
    custom_js_transform = CustomJSTransform()
    assert custom_js_transform.func == ""
    assert custom_js_transform.v_func == ""
Example #8
0
    def __init__(self, default_dir):
        # MD directory and files selection
        self.md_dir = TextInput(title="Path to MD directory containing mdin and mdout files", value=default_dir, width=750)
        self.anim_button = Toggle(label="▶ Load", button_type="warning", width=80, height=50, active=False)
        # container for the buttons that are created while the user types in the textinput
        self.autocomp_results = column(children=[])
        # file used to display temperature, pressure...etc. plots
        self.mdout_sel = Select(
            title="MDout file", width=230,
            value=None, options=[],
        )
        # button to load content
        self.mdout_button = Button(width=80, height=50, label="Plot", button_type="primary")
        self.mdout_files = [None]
        self.md_mdout_files = []

        # mdinfo figures
        progressbar_tooltip = """
        <span style="color:#428df5">@completed{0,0}</span> out of <span style="color:#428df5">@total{0,0}</span> steps (<span style="color:#428df5">@remaining{0,0}</span> remaining)
        """
        self.progressbar = figure(
            title="Current progress", x_range=Range1d(0, 10),
            tooltips=progressbar_tooltip,
            height=70, width=350, tools="hover", toolbar_location=None)
        self.progressbar.xgrid.grid_line_color = None
        self.progressbar.ygrid.grid_line_color = None
        self.progressbar.axis.visible = False
        self.progressbar.outline_line_color = "#444444"
        self.steps_CDS = ColumnDataSource({
            "total":     [np.nan],
            "completed": [np.nan],
            "remaining": [np.nan],
            "color": ['#428df5'],
        })
        self.progressbar.hbar(
            y=0, left=0, right="completed",
            source=self.steps_CDS, height=0.5, color="color",
        )
        self.progressbar.hover[0].mode = "hline"

        self.calc_speed = Div(
            width=150, height=50, text="Calculation speed:",
            style={"font-weight": "bold", "color": "#444444", "margin-top": "5px"}
        )

        self.eta = Div(
            width=100, height=50, text="ETA:",
            style={"font-weight": "bold", "color": "#444444", "margin-top": "5px"}
        )

        self.last_update = Div(
            width=280, height=50, text="Last update:",
            style={"font-weight": "bold", "color": "#444444", "margin-top": "5px"}
        )

        # number of mdout files displayed on the dashboard at max
        self.slider = Slider(start=1, end=10, value=2, step=1, callback_policy="mouseup", title="Number of simulations displayed")
        self.dashboard_CDS = ColumnDataSource({
            "y_coords": [0, 1],
            "mdout": ["heat.out", "prod.out"],
            "time":  [42, 200],
            "angle": [1.09, 5.193],
            "color": ["#f54b42", "#4287f5"],
        })
        dashboard_tooltip = """
        <span style="color:@color">@mdout</span>: @time{0,0.00} ns
        """
        # pie plot
        self.pie = figure(
            plot_height=300, width=500, title="Simulations length", toolbar_location=None,
            tools="hover", tooltips=dashboard_tooltip, x_range=Range1d(-0.5, 1.0))

        self.rpie = self.pie.wedge(
            x=0, y=1, radius=0.4, source=self.dashboard_CDS,
            start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
            line_color="white", fill_color='color', legend="mdout" )
        self.pie.axis.axis_label=None
        self.pie.axis.visible=False
        self.pie.grid.grid_line_color = None
        self.pie.legend.label_text_font_size = '9pt'
        self.pie.legend.border_line_width = 0
        self.pie.legend.border_line_alpha = 0
        self.pie.legend.spacing = 0
        self.pie.legend.margin = 0
        # hbar plot
        self.bar = figure(
            width=850, plot_height=300, toolbar_location=None,
            tools="hover", tooltips=dashboard_tooltip)
        self.rbar = self.bar.hbar(
            y="y_coords", left=0, right="time", source=self.dashboard_CDS,
            height=0.8, color="color")
        self.bar.x_range.set_from_json("start", 0)
        self.bar.xaxis.axis_label="Time (ns)"
        self.bar.yaxis.axis_label=None
        self.bar.yaxis.visible=False
        self.bar.hover[0].mode = "hline"

        ## Mdout figures
        self.mdinfo_CDS = ColumnDataSource(copy.deepcopy(empty_mddata_dic))
        self.moving_avg_trans = CustomJSTransform(v_func=moving_avg_func)
        ticker = PrintfTickFormatter(format="%4.0e")
        # Temperature
        self.temperature_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        self.temperature_fig.toolbar.autohide = True
        self.temperature_fig.xaxis.axis_label = "Number of steps"
        self.temperature_fig.yaxis.axis_label = "Temperature (K)"
        self.temperature_fig.xaxis.formatter = ticker
        r = self.temperature_fig.line(
            "Nsteps","Temperature", color=palette[0], source=self.mdinfo_CDS, _width=1, alpha=0.15)
        self.temperature_fig.line(transform("Nsteps", self.moving_avg_trans), transform("Temperature", self.moving_avg_trans),
                 color=colorscale(palette[0],0.85), source=self.mdinfo_CDS, line_width=3)
        self.temperature_fig.add_tools(make_hover([r]))

        # Pressure
        self.pressure_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        self.pressure_fig.toolbar.autohide = True
        self.pressure_fig.xaxis.axis_label = "Number of steps"
        self.pressure_fig.yaxis.axis_label = "Pressure"
        self.pressure_fig.xaxis.formatter = ticker
        r = self.pressure_fig.line("Nsteps","Pressure", color=palette[1], source=self.mdinfo_CDS, line_width=1, alpha=0.15)
        self.pressure_fig.line(transform("Nsteps", self.moving_avg_trans), transform("Pressure", self.moving_avg_trans),
                 color=colorscale(palette[1],0.85), source=self.mdinfo_CDS, line_width=3)
        self.pressure_fig.add_tools(make_hover([r]))

        # Energy
        self.energy_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        etot  = self.energy_fig.line("Nsteps","Etot",  color=palette[2], source=self.mdinfo_CDS, line_width=1)
        ektot = self.energy_fig.line("Nsteps","EKtot", color=palette[3], source=self.mdinfo_CDS, line_width=1)
        eptot = self.energy_fig.line("Nsteps","EPtot", color=palette[4], source=self.mdinfo_CDS, line_width=1)
        legend = Legend(items=[
            ("Total"   , [etot]),
            ("Kinetic" , [ektot]),
            ("Potential" , [eptot]),
        ], location="top_right")
        self.energy_fig.add_layout(legend, 'right')
        self.energy_fig.add_tools(make_hover([etot]))
        self.energy_fig.legend.location = "top_left"
        self.energy_fig.legend.click_policy="hide"
        self.energy_fig.toolbar.autohide = True
        self.energy_fig.xaxis.axis_label = "Number of steps"
        self.energy_fig.yaxis.axis_label = "Energy"
        self.energy_fig.xaxis.formatter = ticker

        # Volume
        self.vol_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        self.vol_fig.toolbar.autohide = True
        self.vol_fig.xaxis.axis_label = "Number of steps"
        self.vol_fig.yaxis.axis_label = "Volume"
        self.vol_fig.xaxis.formatter = ticker
        r = self.vol_fig.line("Nsteps","Volume", color=palette[6], source=self.mdinfo_CDS, line_width=1, alpha=0.15)
        self.vol_fig.line(transform("Nsteps", self.moving_avg_trans), transform("Volume", self.moving_avg_trans),
                 color=colorscale(palette[6],0.85), source=self.mdinfo_CDS, line_width=3)
        self.vol_fig.add_tools(make_hover([r]))

        # Density
        self.density_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        self.density_fig.toolbar.autohide = True
        self.density_fig.xaxis.axis_label = "Number of steps"
        self.density_fig.yaxis.axis_label = "Density"
        self.density_fig.xaxis.formatter = ticker
        r = self.density_fig.line("Nsteps","Density", color=palette[7], source=self.mdinfo_CDS, line_width=1, alpha=0.15)
        self.density_fig.line(transform("Nsteps", self.moving_avg_trans), transform("Density", self.moving_avg_trans),
                 color=colorscale(palette[7],0.85), source=self.mdinfo_CDS, line_width=3)
        self.density_fig.add_tools(make_hover([r]))

        ## RMSD figure
        self.empty_rmsd_dic = {k:[] for k in ["Time","RMSD"]}
        self.rmsd_CDS = ColumnDataSource(self.empty_rmsd_dic)
        self.rmsd_fig = figure(plot_height=size[1], plot_width=size[0],
            active_scroll="wheel_zoom",
        )
        self.rmsd_fig.toolbar.autohide = True
        self.rmsd_fig.xaxis.axis_label = "Time (ps)"
        self.rmsd_fig.yaxis.axis_label = "RMSD (Å)"
        self.rmsd_fig.xaxis.formatter = ticker
        r = self.rmsd_fig.line(
            "Time","RMSD", color=palette[8], source=self.rmsd_CDS, line_width=2)
        self.rmsd_fig.add_tools(make_hover([r], tooltips=[
            ("Time (ps)", "@Time{0,0}"),
            ("RMSD (Å)", "@RMSD")
        ]))
        self.rmsd_button = Button(width=100, label="Calculate RMSD", button_type="primary")
        self.trajectory = MultiSelect(
            title="Trajectory file(s)", width=400,
            value=None, options=[],
        )
        self.topology = Select(
            title="Topology file", width=200,
            value=None, options=[],
        )
        # NGLview
        self.view_button = Button(width=80, label="Visualize")
        self.view_canvas = Div(width=size[0], height=size[1], css_classes=["ngldiv"], text="")
        # others
        self.mdout_min = {}
        self.mdout_dt = {}
        self.add_callbacks()
Example #9
0
source = graph_renderer.node_renderer.data_source
# print(source.data)

source.data['name'] = [x for x in source.data['index']]
# print(source.date['name'])

# create a transform that can extract the acutal x,y positions
code = """
    var result = new Float64Array(xs.length)
    for (var i = 0; i < xs.length; i++) {
        result[i] = provider.graph_layout[xs[i]][%s]
    }
    return result
"""

xcoord = CustomJSTransform(v_func=code % "0", args=dict(provider=graph_renderer.layout_provider))
ycoord = CustomJSTransform(v_func=code % "1", args=dict(provider=graph_renderer.layout_provider))

# Use the transforms to supply coords to a LabelSet
labels = LabelSet(x=transform('index', xcoord),
                  y=transform('index', ycoord),
                  text='name', text_font_size="12px",
                  x_offset=-10, y_offset=-5,
                  source=source, render_mode='canvas')

plot.add_layout(labels)

graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()

plot.renderers.append(graph_renderer)
Example #10
0
def plot_tree(tree):
    line_len = 7
    width = 2
    sep = line_len + width
    mg = 0

    get_rect_tree_params(tree.root, 0, 0, 1, mg, sep)
    get_level(tree.root, 0)
    get_cond_prob(tree.root, 1)

    rects = pd.DataFrame.from_records(
        map(
            lambda x: {
                'x': x.cx,
                'y': x.cy,
                'width': width,
                'height': x.l,
                'color': pal.Spectral11[x.lv],
                'level': x.lv,
                'weight': round(x.weight, 2),
                'cond_Prob': x.cond_prob,
                'index': x.index,
                'value': x.value,
                'html': '<it>good</it>'
            }, tree.node_list))
    rects = ColumnDataSource(rects)

    lines_x = list(
        map(lambda x: [x.cx - line_len - width / 2, x.cx - width / 2],
            tree.node_list[1:]))
    lines_y = list(map(lambda x: [x.cy, x.cy], tree.node_list[1:]))
    x_tick_pos = list(set(rects.data['x']))
    x_tick = list(set(rects.data['level']))
    x_tick_pos.sort()
    x_tick.sort()

    p = figure(plot_width=600,
               plot_height=400,
               y_range=(-0.55, 0.55),
               tools="save")
    # title='Box Visualisation of A Scenario Tree')
    p.toolbar.logo = None
    p.xgrid.visible = False
    p.ygrid.visible = False
    p.xaxis.axis_label = 'Time Step'
    p.yaxis.visible = False
    p.outline_line_color = None
    p.xaxis.ticker = x_tick_pos
    p.xaxis.major_label_overrides = {
        int(p): str(t)
        for p, t in zip(x_tick_pos, x_tick)
    }

    g_rect = p.rect(x='x',
                    y='y',
                    height='height',
                    width='width',
                    alpha=0.3,
                    color='color',
                    line_color='black',
                    line_width=1,
                    source=rects)

    trans = CustomJSTransform(v_func='''
            const norm = new Array(xs.length)
            for (let i = 0; i < xs.length; i++) {
                norm[i] = xs[i].toString()
            }
            return norm
        ''')

    labels = LabelSet(x='x',
                      y='y',
                      text=transform('value', trans),
                      level='glyph',
                      x_offset=-10,
                      y_offset=-4,
                      source=rects,
                      render_mode='canvas',
                      text_font_size="10pt")

    rect_hover = HoverTool(renderers=[g_rect],
                           tooltips=[("Time", "@level"),
                                     (
                                         "Prob",
                                         "@weight{1.11}",
                                     ), ("cond.Prob", "@cond_Prob{1.11}")])

    p.add_tools(rect_hover)
    p.multi_line(xs=lines_x, ys=lines_y, line_width=0.5, color='black')
    p.add_layout(labels)

    return p