Here are the examples of the python api bokeh.models.BoxSelectTool taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
8 Examples
0
Source : draw.py
with Apache License 2.0
from aws
with Apache License 2.0
from aws
def circuit_from(bqm):
G = bqm.to_networkx_graph()
plot = Plot(
plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)
)
plot.title.text = "Multiplication as a BQM"
plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
graph_renderer = from_networkx(G, circuit_layout)
circle_size = 25
graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB")
graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E")
graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C")
edge_size = 2
graph_renderer.edge_renderer.glyph = MultiLine(
line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size
)
graph_renderer.edge_renderer.selection_glyph = MultiLine(
line_color="#EEA64E", line_width=edge_size
)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = NodesAndLinkedEdges()
plot.renderers.append(graph_renderer)
plot.background_fill_color = "#202239"
add_labels(plot)
show(Row(plot))
def frequency_of(results):
0
Source : plotting.py
with BSD 3-Clause "New" or "Revised" License
from BuildACell
with BSD 3-Clause "New" or "Revised" License
from BuildACell
def graphPlot(DG,DGspecies,DGreactions,plot,layout="force",positions=None,plot_species = True, plot_reactions = True, plot_edges = True, plot_arrows = True,\
species_glyph_size = 12, reaction_glyph_size = 8, posscale = 1.0,layoutfunc=None,iterations=2000,rseed=30,show_species_images=False):
"""given a directed graph, plot it!
Inputs:
DG: a directed graph of type DiGraph
DGspecies: a directed graph which only contains the species nodes
DGreactions: a directed graph which only contains the reaction nodes
plot: a bokeh plot object
layout: graph layout function.
'force' uses fa2 to push nodes apart
'circle' plots the nodes and reactions in two overlapping circles, with the reactions on the inside of the circle
'custom' allows user input "layoutfunc". Internally, layoutfunc is passed the three inputs (DG, DGspecies, DGreactions)
and should output a position dictionary with node { < node number>:(x,y)}
positions: a dictionary of node names and x,y positions. this gets passed into the layout function
posscale: multiply the scaling of the plot. This only affects the arrows because the arrows are a hack :("""
random.seed(rseed)
if(not PLOT_NETWORK):
warn("network plotting disabled because some libraries are not found")
return
if(layout == "force"):
# below are parameters for the force directed graph visualization
forceatlas2 = ForceAtlas2(
# Behavior alternatives
outboundAttractionDistribution=True, # Dissuade hubs
linLogMode=False, # NOT IMPLEMENTED
# Prevent overlap (NOT IMPLEMENTED)
adjustSizes=False,
edgeWeightInfluence=1.0,
# Performance
jitterTolerance=1.0, # Tolerance
barnesHutOptimize=True,
barnesHutTheta=1.2,
multiThreaded=False, # NOT IMPLEMENTED
# Tuning
scalingRatio=2.4*posscale,
strongGravityMode=False,
gravity=1.0,
# Log
verbose=False)
positions = forceatlas2.forceatlas2_networkx_layout(
DG, pos=positions, iterations=iterations)
elif(layout == "circle"):
positions = nx.circular_layout(DGspecies, scale=50*posscale)
positions.update(nx.circular_layout(DGreactions, scale=35*posscale))
elif(layout == "custom"):
positions = layoutfunc(DG, DGspecies, DGreactions)
reaction_renderer = from_networkx(DGreactions, positions, center=(0, 0))
species_renderer = from_networkx(DGspecies, positions, center=(0, 0))
edges_renderer = from_networkx(DG, positions, center=(0, 0))
#Set xbounds and ybounds:
xbounds = [0, 0]
ybounds = [0, 0]
for n in positions:
xbounds[0] = min([xbounds[0], positions[n][0]])
xbounds[1] = max([xbounds[1], positions[n][0]])
ybounds[0] = min([ybounds[0], positions[n][1]])
ybounds[1] = max([ybounds[1], positions[n][1]])
max_glyph = max([reaction_glyph_size, species_glyph_size])
xbounds[0] -= max_glyph
xbounds[1] += max_glyph
ybounds[0] -= max_glyph
ybounds[1] += max_glyph
# edges
edges_renderer.node_renderer.glyph = Circle(
size=species_glyph_size, line_alpha=0, fill_alpha=0, fill_color="color")
edges_renderer.edge_renderer.glyph = MultiLine(
line_alpha=0.2, line_width=4, line_join="round", line_color="color")
edges_renderer.edge_renderer.selection_glyph = MultiLine(
line_color=Spectral4[2], line_width=5, line_join="round")
edges_renderer.edge_renderer.hover_glyph = MultiLine(
line_color=Spectral4[1], line_width=5, line_join="round")
if plot_arrows:
xbounds_a, ybounds_a = makeArrows2(
edges_renderer, DG, positions, headsize=5) # make the arrows!
xbounds[0] = min([xbounds[0], xbounds_a[0]])
xbounds[1] = max([xbounds[1], xbounds_a[1]])
ybounds[0] = min([ybounds[0], ybounds_a[0]])
ybounds[1] = max([ybounds[1], ybounds_a[1]])
# we want to find the middle of the graph and plot a square that is 1:1 aspect ratio
# find the midpoint of the graph
xmid = statistics.mean(xbounds)
ymid = statistics.mean(ybounds)
# now, subtract the middle from the edges
xmiddlized = [a-xmid for a in xbounds]
ymiddlized = [a-ymid for a in ybounds]
# now, find the biggest dimension
absdim = max([abs(a) for a in xmiddlized+ymiddlized])
xlim = [xmid-absdim*1.05, xmid + absdim*1.05]
ylim = [ymid-absdim*1.05, ymid + absdim*1.05]
# now set it on the plot!
plot.x_range = Range1d(xlim[0], xlim[1])
plot.y_range = Range1d(ylim[0], ylim[1])
# reactions
reaction_renderer.node_renderer.glyph = Square(
size=reaction_glyph_size, fill_color="color")
reaction_renderer.node_renderer.selection_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[2])
reaction_renderer.node_renderer.hover_glyph = Square(
size=reaction_glyph_size, fill_color=Spectral4[1])
# nodes
species_renderer.node_renderer.glyph = Circle(size=12, fill_color="color")
species_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
species_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
#this part adds the interactive elements that make it so that the lines are highlighted
#when you mouse over and click
edge_hover_tool = HoverTool(tooltips= None,renderers=[edges_renderer])
if( not show_species_images):
species_hover_tool = HoverTool(tooltips=[("name", "@species"), ("type", "@type")],\
renderers=[species_renderer],attachment="right")
else:
species_hover_tool = HoverTool(tooltips=' < div> < div> < img src="data:image/png;base64,@image" style="float: left; margin: 0px 0px 0px 0px;"> < /img> < /div> < /div>',\
renderers=[species_renderer],attachment="right")
rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
renderers=[reaction_renderer],attachment="right")
plot.add_tools(edge_hover_tool,species_hover_tool,rxn_hover_tool, TapTool(), BoxSelectTool(),PanTool(),WheelZoomTool())
edges_renderer.selection_policy = NodesAndLinkedEdges()
edges_renderer.inspection_policy = EdgesAndLinkedNodes()
if plot_edges:
plot.renderers.append(edges_renderer)
if plot_reactions:
plot.renderers.append(reaction_renderer)
if plot_species:
plot.renderers.append(species_renderer)
def generate_networkx_graph(CRN,useweights=False,use_pretty_print=False,pp_show_material=True,
0
Source : cell_continuous_handler.py
with MIT License
from evdoxiataka
with MIT License
from evdoxiataka
def initialize_glyphs_interactive(variableCell, space):
hover_renderer = []
so = variableCell.plot[space].line('x', 'y', line_color = COLORS[0], line_width = 2, source = variableCell.source[space])
re = variableCell.plot[space].line('x', 'y', line_color = COLORS[1], line_width = 2, source = variableCell.reconstructed[space])
variableCell.plot[space].line('x', 'y', line_color = COLORS[2], line_width = 2, source = variableCell.selection[space])
variableCell.plot[space].dash('x', 'y', size='size', angle = 90.0, angle_units = 'deg', line_color = COLORS[0], source = variableCell.non_sel_samples[space])
variableCell.plot[space].dash('x', 'y', size='size', angle = 90.0, angle_units = 'deg', line_color = COLORS[1], source = variableCell.sel_samples[space])
hover_renderer.append(so)
hover_renderer.append(re)
## Add observations as yellow asterisks
if space in variableCell.data:
dat = variableCell.plot[space].asterisk('x', 'y', size = DATA_SIZE, line_color = COLORS[3], source = variableCell.data[space])
hover_renderer.append(dat)
##Add BoxSelectTool
variableCell.plot[space].add_tools(BoxSelectTool(dimensions = 'width', renderers = [so]))
##Tooltips
TOOLTIPS = [("x", "@x"), ("y","@y"),]
hover = HoverTool( tooltips = TOOLTIPS, renderers = hover_renderer, mode = 'mouse')
variableCell.plot[space].tools.append(hover)
@staticmethod
0
Source : cell_discrete_handler.py
with MIT License
from evdoxiataka
with MIT License
from evdoxiataka
def initialize_glyphs_interactive(variableCell, space):
hover_renderer = []
so_seg = variableCell.plot[space].segment(x0 = 'x', y0 ='y0', x1 = 'x', y1 = 'y', source = variableCell.source[space], line_alpha = 1.0, color = COLORS[0], line_width = 1, selection_color = COLORS[0], \
nonselection_color = COLORS[0], nonselection_line_alpha = 1.0)
variableCell.plot[space].scatter('x', 'y', source = variableCell.source[space], size = 4, fill_color = COLORS[0], fill_alpha = 1.0, line_color = COLORS[0], selection_fill_color = COLORS[0], \
nonselection_fill_color = COLORS[0], nonselection_fill_alpha = 1.0, nonselection_line_color = COLORS[0])
variableCell.plot[space].segment(x0 = 'x', y0 ='y0', x1 = 'x', y1 = 'y', source = variableCell.selection[space], line_alpha = 0.7, color = COLORS[2], line_width = 1)
variableCell.plot[space].scatter('x', 'y', source = variableCell.selection[space], size = 4, fill_color = COLORS[2], fill_alpha = 0.7, line_color = COLORS[2])
rec = variableCell.plot[space].segment(x0 = 'x', y0 ='y0', x1 = 'x', y1 = 'y', source = variableCell.reconstructed[space], line_alpha = 0.5, color = COLORS[1], line_width = 1)
variableCell.plot[space].scatter('x', 'y', source = variableCell.reconstructed[space], size = 4, fill_color = COLORS[1], fill_alpha = 0.5, line_color = COLORS[1])
hover_renderer.append(so_seg)
hover_renderer.append(rec)
## Add observations as yellow asterisks
if space in variableCell.data:
dat = variableCell.plot[space].asterisk('x', 'y', size = DATA_SIZE, line_color = COLORS[3], source = variableCell.data[space])
hover_renderer.append(dat)
##Add BoxSelectTool
variableCell.plot[space].add_tools(BoxSelectTool(dimensions = 'width', renderers = [so_seg]))
##Tooltips
TOOLTIPS = [("x", "@x"), ("y","@y"),]
hover = HoverTool( tooltips = TOOLTIPS, renderers = hover_renderer, mode = 'mouse')
variableCell.plot[space].tools.append(hover)
@staticmethod
0
Source : wm_reader.py
with BSD 3-Clause "New" or "Revised" License
from NREL
with BSD 3-Clause "New" or "Revised" License
from NREL
def create_plot(self, updateCoordinates):
load_x = []
load_y = []
load_lines_xs = []
load_lines_ys = []
if updateCoordinates:
edges = [list(x) for x in self.nxGraph.edges()]
self.plotdata = {
'Xs': [],
'Ys': [],
}
for edge in edges:
node1, node2 = edge
if 'x' in self.nxGraph.node[node1] and 'x' in self.nxGraph.node[node2]:
x1 = self.nxGraph.node[node1]['x']
y1 = self.nxGraph.node[node1]['y']
x2 = self.nxGraph.node[node2]['x']
y2 = self.nxGraph.node[node2]['y']
if None not in [x1, x2, y1, y2]:
self.plotdata['Xs'].append([x1, x2])
self.plotdata['Ys'].append([y1, y2])
for node in [node1, node2]:
if 'loads' in self.nxGraph.node[node]:
for load_name, load_properties in self.nxGraph.node[node]['loads'].items():
if 'x' in self.nxGraph.node[node] and self.nxGraph.node[node]:
x1 = self.nxGraph.node[node]['x']
y1 = self.nxGraph.node[node]['y']
x2 = load_properties['x']
y2 = load_properties['y']
dist = np.sqrt((x1 - x2)**2 + (y1 - y2)**2)
if 0 not in [x1, x2, y1, y2] and dist < 500:
load_x.append(x2)
load_y.append(y2)
load_lines_xs.append([x1, x2])
load_lines_ys.append([y1, y2])
Linesource = ColumnDataSource(self.plotdata)
plot = figure(title=None, plot_width=900, plot_height=900,
tools=[ResetTool(), BoxSelectTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(),
PanTool()])
# plot edges (lines, fuses, switches, transformers, regulators)
plot.multi_line(xs="Xs", ys="Ys", source=Linesource, line_width=2, legend='Edges', line_color='#00008B') # , line_color=ColorBy
# plot loads
plot.triangle(x=load_x, y=load_y, legend='Loads', color='orange')
# plot substation
Xs, Ys = self.get_class_type_locations('substation')
plot.circle_x(x=Xs, y=Ys, size=14, legend='Substation', fill_color='red', line_color='black')
Xs, Ys = self.get_class_type_locations('regulator')
plot.hex(x=Xs, y=Ys, size=14, legend='Regulators', fill_color='lightgreen', line_color='black')
plot.multi_line(xs=load_lines_xs, ys=load_lines_ys, line_width=2, legend='Drop lines', line_color='black')
plot.legend.location = "top_left"
plot.legend.click_policy = "hide"
curdoc().add_root(plot)
show(plot)
return
def get_graph_metrics(self):
0
Source : visualize_utils.py
with MIT License
from ratsgo
with MIT License
from ratsgo
def visualize_self_attention_scores(tokens, scores, filename="/notebooks/embedding/self-attention.png",
use_notebook=False):
mean_prob = np.mean(scores)
weighted_edges = []
for idx_1, token_prob_dist_1 in enumerate(scores):
for idx_2, el in enumerate(token_prob_dist_1):
if idx_1 == idx_2 or el < mean_prob:
weighted_edges.append((tokens[idx_1], tokens[idx_2], 0))
else:
weighted_edges.append((tokens[idx_1], tokens[idx_2], el))
max_prob = np.max([el[2] for el in weighted_edges])
weighted_edges = [(el[0], el[1], (el[2] - mean_prob) / (max_prob - mean_prob)) for el in weighted_edges]
G = nx.Graph()
G.add_nodes_from([el for el in tokens])
G.add_weighted_edges_from(weighted_edges)
plot = Plot(plot_width=500, plot_height=500,
x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
graph_renderer.node_renderer.data_source.data['colors'] = Spectral8[:len(tokens)]
graph_renderer.node_renderer.glyph = Circle(size=15, line_color=None, fill_color="colors")
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="colors")
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="grey")
graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a, b)['weight'] * 3 for a, b in
G.edges()]
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_width={'field': 'line_width'})
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="grey", line_width=5)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="grey", line_width=5)
graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()
plot.renderers.append(graph_renderer)
x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
data = {'x': list(x), 'y': list(y), 'connectionNames': tokens}
source = ColumnDataSource(data)
labels = LabelSet(x='x', y='y', text='connectionNames', source=source, text_align='center')
plot.renderers.append(labels)
plot.add_tools(SaveTool())
if use_notebook:
output_notebook()
show(plot)
else:
export_png(plot, filename)
print("save @ " + filename)
def visualize_words(words, vecs, palette="Viridis256", filename="/notebooks/embedding/words.png",
0
Source : test_objects.py
with MIT License
from rthorst
with MIT License
from rthorst
def large_plot(n):
from bokeh.models import (
Plot, LinearAxis, Grid, GlyphRenderer,
ColumnDataSource, DataRange1d, PanTool, ZoomInTool, ZoomOutTool, WheelZoomTool, BoxZoomTool,
BoxSelectTool, SaveTool, ResetTool
)
from bokeh.models.layouts import Column
from bokeh.models.glyphs import Line
col = Column()
objects = set([col])
for i in xrange(n):
source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
xdr = DataRange1d()
ydr = DataRange1d()
plot = Plot(x_range=xdr, y_range=ydr)
xaxis = LinearAxis()
plot.add_layout(xaxis, "below")
yaxis = LinearAxis()
plot.add_layout(yaxis, "left")
xgrid = Grid(dimension=0)
plot.add_layout(xgrid, "center")
ygrid = Grid(dimension=1)
plot.add_layout(ygrid, "center")
tickers = [xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter]
glyph = Line(x='x', y='y')
renderer = GlyphRenderer(data_source=source, glyph=glyph)
plot.renderers.append(renderer)
pan = PanTool()
zoom_in = ZoomInTool()
zoom_out = ZoomOutTool()
wheel_zoom = WheelZoomTool()
box_zoom = BoxZoomTool()
box_select = BoxSelectTool()
save = SaveTool()
reset = ResetTool()
tools = [pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, save, reset]
plot.add_tools(*tools)
col.children.append(plot)
objects |= set([
xdr, ydr,
xaxis, yaxis,
xgrid, ygrid,
renderer, renderer.view, glyph,
source, source.selected, source.selection_policy,
plot, plot.x_scale, plot.y_scale, plot.toolbar, plot.title,
box_zoom.overlay, box_select.overlay,
] + tickers + tools)
return col, objects
class TestMetaModel(object):
0
Source : widgets.py
with MIT License
from smartyal
with MIT License
from smartyal
def __init_figure(self):
"""
initialize the time series widget, plot the lines, create controls like buttons and menues
also hook the callbacks
"""
self.hoverCounter = 0
self.newHover = None
self.hoverTool = None # forget the old hovers
self.showBackgrounds = False
self.showThresholds = False
self.showMotifs = False
self.showScores = False
self.buttonWidth = 70
#layoutControls = []# this will later be applied to layout() function
settings = self.server.get_settings()
mirror = self.server.get_mirror()
if "width" in settings:
self.width = settings["width"]
if "height" in settings:
self.height = settings["height"]
"""
#set the theme
if settings["theme"] == "dark":
self.curdoc().theme = Theme(json=themes.darkTheme)
self.lineColors = themes.darkLineColors
self.plot.xaxis.major_label_text_color = themes.darkTickColor
else:
self.curdoc().theme = Theme(json=themes.whiteTheme)
self.lineColors = themes.whiteLineColors
self.plot.xaxis.major_label_text_color = themes.whiteTickColor
"""
#self.cssClasses = {"button":"button_21","groupButton":"group_button_21","multiSelect":"multi_select_21"}
#self.cssClasses = {"button": "button_21_sm", "groupButton": "group_button_21_sm", "multiSelect": "multi_select_21_sm"}
#self.layoutSettings = {"controlPosition":"bottom"} #support right and bottom, the location of the buttons and tools
#initial values
try:
self.rangeStart = date2secs(settings["startTime"])*1000
self.rangeEnd = date2secs(settings["endTime"])*1000
except:
self.rangeStart = None
self.rangeEnd = None
self.logger.error("range start, end error, use default full")
#create figure
"""
the creation of the figure was reworked as this is a work around for a well known bug (in 1.04), see here
https://github.com/bokeh/bokeh/issues/7497
it's a bokeh problem with internal sync problems of frontend and backend, so what we do now is:
1) use toolbar_location = None to avoid auto-creation of toolbar
2) create tools by hand
3) assign them to the figure with add_tools()
4) create a toolbar and add it to the layout by hand
"""
if self.server.get_mirror()["panOnlyX"][".properties"]["value"]==True:
self.wheelZoomTool = WheelZoomTool(dimensions="width")
self.panTool = PanTool(dimensions="width")
else:
self.wheelZoomTool = WheelZoomTool()#dimensions="width")
self.panTool = PanTool()#dimensions="width")
tools = [self.wheelZoomTool, self.panTool]
"""
self.wheelZoomTool = WheelZoomTool()
self.wheelZoomToolX = WheelZoomTool(dimensions = "width")
self.panTool = PanTool()
tools = [self.wheelZoomTool,self.wheelZoomToolX,self.panTool]
"""
if settings["hasAnnotation"] == True:
self.boxSelectTool = BoxSelectTool(dimensions="width")
tools.append(self.boxSelectTool)
elif settings["hasThreshold"] == True:
self.boxSelectTool = BoxSelectTool(dimensions="height")
tools.append(self.boxSelectTool)
tools.append(ResetTool())
self.freeZoomTool = BoxZoomTool()
tools.append(self.freeZoomTool)
if "yAxisType" in mirror and mirror ["yAxisType"][".properties"]["value"]=="log":
yAxisType = "log"
else:
yAxisType = "linear"
if "xAxisType" in mirror and mirror ["xAxisType"][".properties"]["value"]=="number":
if yAxisType == "log":
fig = figure(toolbar_location=None, plot_height=self.height,
plot_width=self.width,
sizing_mode="scale_width",
x_range=(0,1),y_axis_type=yAxisType)
else:
fig = figure(toolbar_location=None, plot_height=self.height,
plot_width=self.width,
sizing_mode="scale_width",
x_range=(0,1),y_axis_type=yAxisType,y_range=Range1d())
else:
if yAxisType == "log":
fig = figure(toolbar_location=None, plot_height=self.height,
plot_width=self.width,
sizing_mode="scale_width",
x_axis_type='datetime',x_range=(0,1),y_axis_type=yAxisType)
else:
fig = figure(toolbar_location=None, plot_height=self.height,
plot_width=self.width,
sizing_mode="scale_width",
x_axis_type='datetime',x_range=(0,1),y_axis_type=yAxisType,y_range=Range1d())
self.plot = fig
# set the theme
if settings["theme"] == "dark":
self.curdoc().theme = Theme(json=themes.darkTheme)
self.lineColors = themes.darkLineColors
self.plot.xaxis.major_label_text_color = themes.darkTickColor
self.plot.yaxis.major_label_text_color = themes.darkTickColor
else:
self.curdoc().theme = Theme(json=themes.whiteTheme)
self.lineColors = themes.whiteLineColors
self.plot.xaxis.major_label_text_color = themes.whiteTickColor
self.plot.yaxis.major_label_text_color = themes.whiteTickColor
#b1 = date2secs(datetime.datetime(2015,2,13,3,tzinfo=pytz.UTC))*1000
#b2 = date2secs(datetime.datetime(2015,2,13,4,tzinfo=pytz.UTC))*1000
#wid = 20*60*1000 # 20 min
#self.boxData = ColumnDataSource({'x': [b1,b2], 'y':[0,0],'width': [5, 5],'height':[300,300],"alpha":[1,1,0.2]})
#self.boxRect = self.plot.rect(x="x", y="y", width="width", height="height",source=self.boxData)
#self.boxRect = self.plot.rect('x', 'y', 'width', 'height', source=self.boxData,width_units="screen")#, height_units="screen")#, height_units="screen")
self.boxModifierTool=BoxEditTool( renderers=[],num_objects=0,empty_value=0.1)#,dimensions="width")
self.box_modifier_init()
#self.box_modifier_show()
# possible attribures to boxedittool:
# custom_icon, custom_tooltip, dimensions, empty_value, js_event_callbacks, js_property_callbacks, name, num_objects, renderers, subscribed_events
#self.plot.add_layout(self.boxRect)
#self.boxModifierRect.data_source.on_change("selected",self.box_cb)
#self.boxRect.data_source.on_change("active", self.box_cb_2)
tools.append(self.boxModifierTool)
for tool in tools:
fig.add_tools(tool) # must assign them to the layout to have the actual use hooked
toolBarBox = ToolbarBox() #we need the strange creation of the tools to avoid the toolbar to disappear after
# reload of widget, then drawing an annotations (bokeh bug?)
toolBarBox.toolbar = Toolbar(tools=tools,active_inspect=None,active_scroll=self.wheelZoomTool,active_drag = None)
#active_inspect = [crosshair],
# active_drag = # here you can assign the defaults
# active_scroll = # wheel_zoom sometimes is not working if it is set here
# active_tap
toolBarBox.toolbar_location = "right"
toolBarBox.toolbar.logo = None # no bokeh logo
self.tools = toolBarBox
self.toolBarBox = toolBarBox
if "xAxisType" in mirror and mirror["xAxisType"][".properties"]["value"]=="number":
if "xAxisUnit" in mirror:
self.plot.xaxis.formatter = FuncTickFormatter(code = """
let x=tick.toString();
return x + " %s";
"""%mirror['xAxisUnit']['.properties']['value'])
else:
#no formatter
pass
else:
self.plot.xaxis.formatter = FuncTickFormatter(code = """
let local = moment(tick).tz('%s');
let datestring = local.format();
return datestring.slice(0,-6);
"""%settings["timeZone"])
self.plot.xaxis.ticker = DatetimeTicker(desired_num_ticks=5)# give more room for the date time string (default was 6)
self.plot.xgrid.ticker = self.plot.xaxis.ticker
self.build_second_y_axis()
self.show_hide_scroll_label() #it must be created at startup and then visible=True/False, the later add_layout did not work
self.refresh_plot()
#hook in the callback of the figure
self.plot.x_range.on_change('start', self.range_cb)
self.plot.x_range.on_change('end', self.range_cb)
self.plot.on_event(events.Pan, self.event_cb)
self.plot.on_event(events.PanStart, self.event_cb)
self.plot.on_event(events.PanEnd, self.event_cb)
self.plot.on_event(events.LODEnd, self.event_cb)
self.plot.on_event(events.Reset, self.event_cb)
self.plot.on_event(events.SelectionGeometry, self.event_cb)
self.plot.on_event(events.Tap,self.event_cb)
#self.plot.on_event(events.MouseWheel, self.mouse_cb)
#make the controls
layoutControls =[]
#Annotation drop down
if 0: #no drop down for now
labels=[]
if settings["hasAnnotation"] == True:
labels = settings["tags"]
labels.append("-erase-")
if settings["hasThreshold"] == True:
labels.extend(["threshold","-erase threshold-"])
if labels:
menu = [(label,label) for label in labels]
self.annotationDropDown = Dropdown(label="Annotate: "+str(labels[0]), menu=menu,width=self.buttonWidth,css_classes = ['dropdown_21'])
self.currentAnnotationTag = labels[0]
self.annotationDropDown.on_change('value', self.annotation_drop_down_on_change_cb)
#self.annotation_drop_down_on_change_cb() #call it to set the box select tool right and the label
layoutControls.append(self.annotationDropDown)
"""
currently disabled
# show Buttons
# initially everything is disabled
# check background, threshold, annotation, streaming
self.showGroupLabels = []
self.showGroupLabelsDisplay=[]
if self.server.get_settings()["hasAnnotation"] == True:
self.showGroupLabels.append("Annotation")
self.showGroupLabelsDisplay.append("Anno")
if self.server.get_settings()["background"]["hasBackground"]:
self.showGroupLabels.append("Background")
self.showGroupLabelsDisplay.append("Back")
self.showBackgrounds = False # initially off
if self.server.get_settings()["hasThreshold"] == True:
self.showGroupLabels.append("Threshold")
self.showGroupLabelsDisplay.append("Thre")
self.showThresholds = False # initially off
if self.server.get_settings()["hasStreaming"] == True:
self.showGroupLabels.append("Streaming")
self.showGroupLabelsDisplay.append("Stream")
self.streamingMode = False # initially off
self.showGroup = CheckboxButtonGroup(labels=self.showGroupLabelsDisplay)
self.showGroup.on_change("active",self.show_group_on_click_cb)
layoutControls.append(row(self.showGroup))
"""
#make the custom buttons
buttonControls = []
self.customButtonsInstances = []
if "buttons" in settings:
self.logger.debug("create user buttons")
#create the buttons
for entry in settings["buttons"]:
button = Button(label=entry["name"],width=self.buttonWidth)#,css_classes=['button_21'])
instance = self.ButtonCb(self,entry["targets"])
button.on_click(instance.cb)
buttonControls.append(button)
self.customButtonsInstances.append(instance)
#make the debug button
if "hasReloadButton" in self.server.get_settings():
if self.server.get_settings()["hasReloadButton"] == True:
#we must create a reload button
button = Button(label="reload",width=self.buttonWidth)#, css_classes=['button_21'])
button.on_click(self.reset_all)
buttonControls.append(button)
if 0: # turn this helper button on to put some debug code
self.debugButton= Button(label="debug")
self.debugButton.on_click(self.debug_button_cb)
self.debugButton2 = Button(label="debug2")
self.debugButton2.on_click(self.debug_button_2_cb)
buttonControls.append(self.debugButton)
buttonControls.append(self.debugButton2)
layoutControls.extend(buttonControls)
#build the layout
self.layout = layout([row(children=[self.plot, self.tools], sizing_mode="fixed")], row(layoutControls, width=int(self.width*0.6),sizing_mode="scale_width"))
#self.layout = layout([row(children=[self.plot, self.tools], sizing_mode="fixed")])
if self.server.get_settings()["hasAnnotation"] == True:
self.init_annotations() # we create all annotations that we have into self.annotations
if "hasEvents" in self.server.get_settings() and self.server.get_settings()["hasEvents"] == True:
self.init_events()
def init_additional_elements(self):