def show(sample_size): global session global scatter_plot global source global pie_chart_source global line_chart_source global slider DB.__init__(sample_size) min_time = DB.min_time() max_time = DB.max_time() print min_time print min_time xs, ys, color, time = DB.get_current() xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time] ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time] color = [color[i] for i,v in enumerate(time) if time[i] == min_time] time_dict = Counter(time) pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color)) line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict])) source = ColumnDataSource(data=dict(x=xs, y=ys, color=color)) scatter_plot = Figure(plot_height=800, plot_width=1200, title="Plot of Voters", tools="pan, reset, resize, save, wheel_zoom", ) scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15) scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1) scatter_plot.x_range.on_change('end', update_coordinates) line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350) line_chart.line(x='x', y='y', source=line_chart_source) pie_chart_plot = Figure(plot_height=350, plot_width=350, title="Voter Distribution", x_range=(-1, 1), y_range=(-1, 1)) pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color") slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time") slider.on_change('value', update_coordinates) h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart)) vplot(slider, h, width=1600, height=1800) session = push_session(curdoc()) session.show() #script = autoload_server(scatter_plot, session_id=session.id) session.loop_until_closed()
def test_server_examples(server_example, example, report, bokeh_server): if example.is_skip: pytest.skip("skipping %s" % example.relpath) app = build_single_handler_application(example.path) doc = app.create_document() # remove all periodic and timeout callbacks for session_callback in list(doc._session_callbacks.keys()): doc._remove_session_callback(session_callback) session_id = "session_id" push_session(doc, session_id=session_id) if example.no_js: if not pytest.config.option.no_js: warn("skipping bokehjs for %s" % example.relpath) else: _assert_snapshot(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, 'server') if example.no_diff: warn("skipping image diff for %s" % example.relpath) else: _get_pdiff(example)
def test_server_examples(server_example, example, report, bokeh_server): if example.is_skip: pytest.skip("skipping %s" % example.relpath) app = build_single_handler_application(example.path) doc = app.create_document() # remove all next-tick, periodic, and timeout callbacks for session_callback in doc.session_callbacks: if isinstance(session_callback, NextTickCallback): doc.remove_next_tick_callback(session_callback) elif isinstance(session_callback, PeriodicCallback): doc.remove_periodic_callback(session_callback) elif isinstance(session_callback, TimeoutCallback): doc.remove_timeout_callback(session_callback) else: raise RuntimeError('Unhandled callback type', type(session_callback)) session_id = basename(example.path) push_session(doc, session_id=session_id) if example.no_js: if not pytest.config.option.no_js: warn("skipping bokehjs for %s" % example.relpath) else: _assert_snapshot(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, 'server') if example.no_diff: warn("skipping image diff for %s" % example.relpath) else: _get_pdiff(example)
def test_server_examples(server_example, example, config, report, bokeh_server): # mitigate some weird interaction isolated to simple ids, py2.7, # "push_session" server usage, and TravisCI if six.PY2: os.environ['BOKEH_SIMPLE_IDS'] = 'no' app = build_single_handler_application(example.path) doc = app.create_document() if six.PY2: del os.environ['BOKEH_SIMPLE_IDS'] # remove all next-tick, periodic, and timeout callbacks for session_callback in doc.session_callbacks: if isinstance(session_callback, NextTickCallback): doc.remove_next_tick_callback(session_callback) elif isinstance(session_callback, PeriodicCallback): doc.remove_periodic_callback(session_callback) elif isinstance(session_callback, TimeoutCallback): doc.remove_timeout_callback(session_callback) else: raise RuntimeError('Unhandled callback type', type(session_callback)) session_id = basename(example.path) push_session(doc, session_id=session_id) if example.no_js: if not config.option.no_js: warn("skipping bokehjs for %s" % example.relpath) else: _run_in_browser(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id, config.option.verbose)
def render_plot(): build_plot() session = push_session(curdoc()) curdoc().add_periodic_callback(callback, 60000) session.show() # open the document in a browser session.loop_until_closed() # run forever return ""
def test_client_session_next_tick_async_added_before_push(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() result = DictModel() doc.add_root(result) @gen.coroutine def cb(): result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) cb_id = doc.add_next_tick_callback(cb) client_session = push_session(doc, session_id='test_client_session_next_tick_async', url=url(server), io_loop=server.io_loop) client_session.loop_until_closed(suppress_warning=True) with pytest.raises(ValueError) as exc: doc.remove_next_tick_callback(cb_id) assert 'already removed' in repr(exc.value) assert dict(a=0, b=1, c=2, d=3, e=4) == result.values
def render_table(sym): df = get_data(sym) text_input = TextInput(value=sym.upper(), title="Label:") mids = (df['open'] + df['close'])/2 spans = abs(df['open'] - df['close']) inc = df['close'] > df['open'] dec = df['close'] < df['open'] w = 12*60*60*1000 # half day in ms TOOLS = "pan,wheel_zoom,box_zoom,reset,save" global p p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=750, plot_height=300, toolbar_location="left") p.title = sym.upper() + " Candlestick" p.xaxis.major_label_orientation = pi/4 p.grid.grid_line_alpha=0.3 p.segment(df.date, df.high, df.date, df.low, color="black") p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black") p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black") session = push_session(curdoc()) curdoc().add_periodic_callback(update, 1000) session.show() # open the document in a browser session.loop_until_closed() # run forever output_file("candlestick.html", title="candlestick.py example")
def bokeh_local(self): p = figure() x, y = read_log() # print x, y self.r = p.line(x, y, color='navy', line_width=3) session = push_session(curdoc()) session.show()
def test_server_session_periodic_async(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() doc.add_root(DictModel()) client_session = push_session(doc, session_id='test_server_session_periodic_async', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) result = next(iter(server_session.document.roots)) @gen.coroutine def cb(): # we're testing that we can modify the doc and be # "inside" the document lock result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) callback = server_session.document.add_periodic_callback(cb, 10) client_session.loop_until_closed() server_session.document.remove_periodic_callback(cb) self.assertDictEqual(dict(a=0, b=1, c=2, d=3, e=4), result.values)
def main(): session = push_session(curdoc(), session_id='labeler') document = session.document print document do_step(document) session.show() session.loop_until_closed()
def test_client_session_periodic_async_added_before_push(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() result = DictModel() doc.add_root(result) @gen.coroutine def cb(): result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) callback = doc.add_periodic_callback(cb, 10) client_session = push_session(doc, session_id='test_client_session_periodic_async', url=url(server), io_loop=server.io_loop) client_session.loop_until_closed() doc.remove_periodic_callback(cb) self.assertDictEqual(dict(a=0, b=1, c=2, d=3, e=4), result.values)
def notebook_plot(x_key, y_key, **kwargs): r"""Live plot log entries in the current notebook. Parameters ---------- x_key : str The key in the serialized JSON object that contains the x-axis value. y_key : str See `x_key`. \*\*kwargs Connection parameters passed to the `connect` function. """ subscriber, sequence, x, y = connect(x_key, y_key, **kwargs) session = push_session(curdoc()) output_notebook() fig = figure() plot = fig.line(x, y) show(fig) def notebook_update(): update(x_key, y_key, sequence, subscriber, plot) push_notebook() curdoc().add_periodic_callback(notebook_update, 50) session.loop_until_closed()
def test_client_session_next_tick_async(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_session = push_session(doc, session_id='test_client_session_next_tick_async', url=url(server), io_loop=server.io_loop) result = DictModel() doc.add_root(result) @gen.coroutine def cb(): result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) callback = doc.add_next_tick_callback(cb) client_session.loop_until_closed() with (self.assertRaises(ValueError)) as manager: doc.remove_next_tick_callback(cb) self.assertTrue('already removed' in repr(manager.exception)) self.assertDictEqual(dict(a=0, b=1, c=2, d=3, e=4), result.values)
def test_push_document(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() doc.add_root(AnotherModelInTestClientServer(bar=43)) doc.add_root(SomeModelInTestClientServer(foo=42)) client_session = push_session(doc, session_id='test_push_document', url=server.ws_url, io_loop=server.io_loop) assert client_session.document == doc assert len(client_session.document.roots) == 2 server_session = server.get_session('/', client_session.id) assert len(server_session.document.roots) == 2 results = {} for r in server_session.document.roots: if hasattr(r, 'foo'): results['foo'] = r.foo if hasattr(r, 'bar'): results['bar'] = r.bar assert results['foo'] == 42 assert results['bar'] == 43 client_session.close() client_session.loop_until_closed() assert not client_session.connected
def test(): p = figure(x_range=(-20, 20), y_range=(-20, 20), toolbar_location=None, webgl=False, plot_width=750, plot_height=750) p.border_fill_color = '#eeeeee' p.background_fill_color = 'white' p.outline_line_color = None p.grid.grid_line_color = None session = push_session(curdoc()) curdoc().add_root(p) session.show() car = Car([1.0, 2.0], angle_to_vector(math.pi/2), wheels_angle=0.4, speed=1.0, width=1.0, length=2.0, fig=p, nrays=36) border = geom.Figure([[-10.0, -10.0], [-10.0, 10.0], [10.0, 10.0], [10.0, -10.0]], close=True, fig=p) obstacle = geom.Figure([[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]], close=True, fig=p) #obstacle = geom.Figure(close=True, fig=p) #print border.points #obstacle.set_points([[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]]) env = geom.CompoundFigure([border, obstacle]) env.draw() for i in xrange(10000): car.turn_wheels(random.random() - 0.5) car.save_pos() car.move(0.1) if car.path().intersect(env) != None: car.restore_pos() car.speed = -car.speed car.draw(env) time.sleep(0.01)
def serve(host='localhost', port=5006, session_id='test'): url = 'http://' + host + ':' + str(port) + '/' session = push_session(curdoc(), session_id=session_id, url=url) session.show() return session
def test_server_session_next_tick_async(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() doc.add_root(DictModel()) client_session = push_session(doc, session_id='test_server_session_next_tick_async', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) result = next(iter(server_session.document.roots)) @gen.coroutine def cb(): # we're testing that we can modify the doc and be # "inside" the document lock result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) cb_id = server_session.document.add_next_tick_callback(cb) client_session.loop_until_closed(suppress_warning=True) with pytest.raises(ValueError) as exc: server_session.document.remove_next_tick_callback(cb_id) assert 'already removed' in repr(exc.value) assert dict(a=0, b=1, c=2, d=3, e=4) == result.values
def __init__(self, document): if BokehSession._session == None: BokehSession._session = push_session(document) else: pass self.session_id = BokehSession._session.id print('Click here to open Live Trending Web Page') print('http://localhost:5006/?bokeh-session-id=%s' % self.session_id)
def main(): # example input: # bokeh serve # python3 waggle_dash/main.py --date 2016-07-29 --id ub_3 ub_4 parser = argparse.ArgumentParser(description='Plot Beehive data using Bokeh') parser.add_argument('-dates', metavar='dates', type=str, nargs='+', help='The dates for which the data will be retrieved') parser.add_argument('-id', metavar='id', type=str, nargs='+', help='The node IDs') parser.add_argument('-row_first', metavar='row_first', type=int, nargs='?', default = 0, help='maximum number of rows of data to load') parser.add_argument('-row_last', metavar='row_last', type=int, nargs='?', default = -1, help='maximum number of rows of data to load') parser.add_argument('-csv_out', type=str, nargs='?', help='the csv file to which the data is saved.') args = parser.parse_args() # node_ids = {'ub_1': '0000001e06107d6b', # 'ub_2': '0000001e06107e4c', # 'ub_3': '0000001e06107d7f', # 'ub_4': '0000001e06107cc5' # # 'ub_5':'0000001e06107cdc' # } print(args) #nodes = {'ub_3': '0000001e06107d7f', 'ub_4': '0000001e06107cc5'} dates = args.dates # '2016-07-29' node_ids = args.id print(dates) print('row_first = ', args.row_first) print('row_last = ', args.row_last) data = load_data(node_ids, dates, row0 = args.row_first, row1 = args.row_last) if bDebug: print('data: ', data) if (args.csv_out): store_csv(data, args.csv_out) else: sensor_names, data_types = compute_params(data) if False: sensor_names = {'Temperature': ['TSYS01', 'TMP112', 'BMP180', 'TMP421', 'HIH6130', 'HTU21D'], 'Humidity': ['HTU21D', 'HIH6130'], 'Concentration': ['Nitrogen Di-oxide (NO2)', 'Carbon Monoxide (C0)','Hydrogen Sulphide (H2S)', 'Sulfur Dioxide (SO2)']} data_types = ['Temperature', 'Humidity', 'Concentration'] # sensor_names = {'Temperature': ['TSYS01']} # data_types = ['Temperature'] panels = init_panels(data, sensor_names, data_types, dates, node_ids[0]) tabs = Tabs(tabs=[panels[dtype] for dtype in data_types]) #panels4 = init_panels(data, sensor_names, data_types, dates, node_ids['ub_4']) #tabs4 = Tabs(tabs=[panels4[dtype] for dtype in data_types]) # lo = layout([[tabs4]], sizing_mode='stretch_both') #lo = layout(tabs, sizing_mode='stretch_both') session = push_session(curdoc()) curdoc().add_root(tabs) session.show(tabs) session.loop_until_closed()
def index(): plot = figure() plot.circle([1,2], [3,4]) document = Document() document.add_root(plot) session = push_session(document) script = autoload_server(None, session_id=session.id) return render_template('index.html', bokeh_script=script)
def apply(self,target_df): self.init_func(target_df, *self.args, **self.kwargs) self.session = push_session(curdoc()) tag = autoload_server(self.p,session_id=self.session.id) target_df._top_df._plots.append(tag) thread = Thread(target = self._continuous_wrapper, args=(target_df,)) thread.start() return thread
def test_unit_spec_changes_do_not_boomerang(monkeypatch): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_root = UnitsSpecModel() doc.add_root(client_root) client_session = push_session(doc, session_id='test_unit_spec_changes_do_not_boomerang', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(server_session.document.roots) == 1 server_root = next(iter(server_session.document.roots)) assert client_root.distance == 42 assert server_root.angle == 0 def change_to(new_distance, new_angle): got_angry = {} got_angry['result'] = None # trap any boomerang def get_angry(message): got_angry['result'] = message monkeypatch.setattr(client_session, '_handle_patch', get_angry) server_previous_distance = server_root.distance server_previous_angle = server_root.angle # Now modify the client document client_root.distance = new_distance client_root.angle = new_angle # wait until server side change made ... but we may not have the # boomerang yet def server_change_made(): return server_root.distance != server_previous_distance and \ server_root.angle != server_previous_angle client_session._connection._loop_until(server_change_made) # force a round trip to be sure we get the boomerang if we're going to client_session.force_roundtrip() assert got_angry['result'] is None change_to(57, 1) change_to({ 'value' : 58 }, { 'value' : 2 }) change_to({ 'field' : 'foo' }, { 'field' : 'bar' }) change_to({ 'value' : 59, 'units' : 'screen' }, { 'value' : 30, 'units' : 'deg' }) client_session.close() client_session.loop_until_closed() assert not client_session.connected server.unlisten() # clean up so next test can run
def __init__(self): from bokeh.document import Document from bokeh.client import push_session from bokeh.models import ColumnDataSource from bokeh.sampledata.population import load_population self.document = Document() self.session = push_session(self.document) self.df = load_population() self.source_pyramid = ColumnDataSource(data=dict())
def go(self): """Displays the application""" document = Document() document.title = "UT330 UI" document.add_root(self.tabs) session = push_session(document) session.show() session.loop_until_closed()
def exg(source): if source.endswith('.bin'): data_dir, data_list = get_mock_data_list() source = os.path.join(data_dir, source) print('Loading data...', end='', flush=True) with open(source, 'rb') as fd: buff = bytearray(fd.read()) serial_obj = FakeSerialByteArray(buff) print('Done.', flush=True) else: serial_obj = serial.Serial(source, baudrate=DEFAULT_BAUDRATE) reader = PacketStreamReader(serial_obj) new_data_gen = get_new_data_points(reader) p = figure( x_range=(0, 1024), y_range=(0, 1024), plot_width=1024, plot_height=400, tools='save', toolbar_location='below', ) p.axis.visible = False p.xgrid.visible = False line = p.line( x=tuple(range(1024)), y=tuple(512 for _ in range(1024)) ) ds = line.data_source def update(): data = next(new_data_gen) new_y = tuple(ds.data['y']) + tuple(data) new_y = new_y[-1024:] new_x = tuple(range(len(new_y))) ds.data.update(x=new_x, y=new_y) curdoc().add_periodic_callback(update, 30) # open a session to keep our local document in sync with server session = push_session(curdoc()) session.show(p) # open the document in a browser try: session.loop_until_closed() # run forever finally: serial_obj.close()
def __init__(self, N=200): self.document = Document() self.params = {'amplitude': 1, 'frequency': 1, 'phase': 0, 'offset': 0 } self.param_limits = {'amplitude': [-5.0, 5.0, 0.2], 'frequency': [0.1, 5.1, 0.1], 'phase': [0, 2*np.pi, 2*np.pi/50], 'offset': [-5.0, 5.0, 0.1] } keys = self.params.keys() self.selectors = {n: Select(title="Parameter %i" % (n+1), value=keys[n], options=keys) for n in range(2) } self.sliders = {n: Slider(value=self.params[keys[n]], start=self.param_limits[keys[n]][0], end=self.param_limits[keys[n]][1], step=self.param_limits[keys[n]][2] ) for n in range(2) } selection_layout = VBoxForm(children=[VBoxForm(children=[self.selectors[n], self.sliders[n] ] ) for n in range(2) ] ) for slider in self.sliders.values(): slider.on_change('value', self.update_sliders) self.selector_values = {} for num, selector in self.selectors.items(): selector.on_change('value', self.update_selectors) self.selector_values[num] = selector.value self.resetting_selectors = False # keeps from updating plot when we update selection self.N = N self.source = ColumnDataSource() self.update_data() plot = Figure(plot_height=400, plot_width=400, title="my sine wave", tools="crosshair,pan,reset,resize,save,wheel_zoom", x_range=[0, 4*np.pi], y_range=[-2.5, 2.5] ) plot.line('x', 'y', source=self.source, line_width=3, line_alpha=0.6) self.document.add_root(HBox(selection_layout, plot)) self.session = push_session(self.document)
def pages_timeseries(response): parse_datetime = lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%f") parsed_dates = [parse_datetime(x[1]) for x in response] dates = sorted(parsed_dates) plot = figure(plot_width=584, x_axis_type="datetime", x_axis_label="Dates", y_axis_label="Number Fetched") plot.line(x=dates, y=range(len(dates))) button = Button(label="Press Me") session = push_session(curdoc()) script = autoload_server(vplot(plot, button), session_id=session.id) return script
def __init__(self): self.document = Document() self.manufacturer_filter = None self.model_filter = None self.transmission_filter = None self.drive_filter = None self.class_filter = None self.source = ColumnDataSource() self.update_data() self.document.add_root((self.create())) self.session = push_session(self.document)
def test_server_changes_go_to_client(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_session = push_session(doc, session_id='test_server_changes_go_to_client', url=server.ws_url, io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(client_session.document.roots) == 0 server_root = SomeModelInTestClientServer(foo=42) server_session.document.add_root(server_root) def client_has_root(): return len(doc.roots) > 0 client_session._connection._loop_until(client_has_root) client_root = next(iter(client_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 # Now try setting title on server side server_session.document.title = "Server Title" def client_title_set(): return client_session.document.title != document.DEFAULT_TITLE client_session._connection._loop_until(client_title_set) assert client_session.document.title == "Server Title" # Now modify a model within the server document server_root.foo = 57 # there is no great way to block until the server # has applied changes, since patches are sent # asynchronously. We use internal _loop_until API. def client_change_made(): return client_root.foo == 57 client_session._connection._loop_until(client_change_made) assert client_root.foo == 57 server_session.document.remove_root(server_root) def client_lacks_root(): return len(doc.roots) == 0 client_session._connection._loop_until(client_lacks_root) assert len(client_session.document.roots) == 0 client_session.close() client_session.loop_until_closed() assert not client_session.connected
def get_bokeh_script(user, plot, suffix): from .models import UserSession document = Document() document.add_root(plot) document.title = suffix with closing(push_session(document)) as session: # Save the session id to a UserSession UserSession.objects.create(user=user, bokeh_session_id=session.id) # Get the script to pass into the template script = autoload_server(None, session_id=session.id) return script
def test_client_changes_do_not_boomerang(monkeypatch): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_root = SomeModelInTestClientServer(foo=42) doc.add_root(client_root) client_session = push_session( doc, session_id='test_client_changes_do_not_boomerang', url=server.ws_url, io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(server_session.document.roots) == 1 server_root = next(iter(server_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 got_angry = {} got_angry['result'] = None # trap any boomerang def get_angry(message): got_angry['result'] = message monkeypatch.setattr(client_session, '_handle_patch', get_angry) # Now modify the client document client_root.foo = 57 # wait until server side change made ... but we may not have the # boomerang yet def server_change_made(): return server_root.foo == 57 client_session._connection._loop_until(server_change_made) assert server_root.foo == 57 # force a round trip to be sure we get the boomerang if we're going to client_session.force_roundtrip() assert got_angry['result'] is None client_session.close() client_session.loop_until_closed() assert not client_session.connected server.unlisten() # clean up so next test can run
def test_server_examples(server_example, example, report, bokeh_server): if example.is_skip: pytest.skip("skipping %s" % example.relpath) # mitigate some weird interaction isolated to simple ids, py2.7, # "push_session" server usage, and TravisCI if six.PY2: os.environ['BOKEH_SIMPLE_IDS'] = 'no' app = build_single_handler_application(example.path) doc = app.create_document() if six.PY2: del os.environ['BOKEH_SIMPLE_IDS'] # remove all next-tick, periodic, and timeout callbacks for session_callback in doc.session_callbacks: if isinstance(session_callback, NextTickCallback): doc.remove_next_tick_callback(session_callback) elif isinstance(session_callback, PeriodicCallback): doc.remove_periodic_callback(session_callback) elif isinstance(session_callback, TimeoutCallback): doc.remove_timeout_callback(session_callback) else: raise RuntimeError('Unhandled callback type', type(session_callback)) session_id = basename(example.path) push_session(doc, session_id=session_id) if example.no_js: if not pytest.config.option.no_js: warn("skipping bokehjs for %s" % example.relpath) else: _run_in_browser(example, "http://localhost:5006/?bokeh-session-id=%s" % session_id) if example.no_diff: warn("skipping image diff for %s" % example.relpath) else: _get_pdiff(example)
def test_server_changes_go_to_client(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_session = push_session( doc, session_id='test_server_changes_go_to_client', url=server.ws_url, io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(client_session.document.roots) == 0 server_root = SomeModelInTestClientServer(foo=42) server_session.document.add_root(server_root) def client_has_root(): return len(doc.roots) > 0 client_session._connection._loop_until(client_has_root) client_root = next(iter(client_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 # Now modify the server document server_root.foo = 57 # there is no great way to block until the server # has applied changes, since patches are sent # asynchronously. We use internal _loop_until API. def client_change_made(): return client_root.foo == 57 client_session._connection._loop_until(client_change_made) assert client_root.foo == 57 server_session.document.remove_root(server_root) def client_lacks_root(): return len(doc.roots) == 0 client_session._connection._loop_until(client_lacks_root) assert len(client_session.document.roots) == 0 client_session.close() client_session.loop_until_closed() assert not client_session.connected
def test_client_changes_go_to_server(self, ManagedServerLoop) -> None: application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_root = SomeModelInTestClientServer(foo=42) client_session = push_session(doc, session_id='test_client_changes_go_to_server', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(server_session.document.roots) == 0 doc.add_root(client_root) client_session.force_roundtrip() # be sure events have been handled on server assert len(server_session.document.roots) == 1 server_root = next(iter(server_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 # Now try setting title assert server_session.document.title == document.DEFAULT_TITLE doc.title = "Client Title" client_session.force_roundtrip() # be sure events have been handled on server assert server_session.document.title == "Client Title" # Now modify an attribute on a client model client_root.foo = 57 # there is no great way to block until the server # has applied changes, since patches are sent # asynchronously. We use internal _loop_until API. def server_change_made(): return server_root.foo == 57 client_session._connection._loop_until(server_change_made) assert server_root.foo == 57 doc.remove_root(client_root) client_session.force_roundtrip() # be sure events have been handled on server assert len(server_session.document.roots) == 0 client_session.close() client_session._loop_until_closed() assert not client_session.connected
def test_server_changes_do_not_boomerang(monkeypatch, ManagedServerLoop) -> None: application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_root = SomeModelInTestClientServer(foo=42) doc.add_root(client_root) client_session = push_session(doc, session_id='test_server_changes_do_not_boomerang', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(server_session.document.roots) == 1 server_root = next(iter(server_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 got_angry = {} got_angry['result'] = None # trap any boomerang def get_angry(message, connection): got_angry['result'] = message monkeypatch.setattr(server_session, '_handle_patch', get_angry) # Now modify the server document def do_set_foo_property(): server_root.foo = 57 server.io_loop.spawn_callback(server_session.with_document_locked, do_set_foo_property) # there is no great way to block until the server # has applied changes, since patches are sent # asynchronously. We use internal _loop_until API. def client_change_made(): return client_root.foo == 57 client_session._connection._loop_until(client_change_made) assert client_root.foo == 57 # force a round trip to be sure we get the boomerang if we're going to client_session.force_roundtrip() assert got_angry['result'] is None client_session.close() client_session._loop_until_closed() assert not client_session.connected
def test(): p = figure(x_range=(-20, 20), y_range=(-20, 20), toolbar_location=None, webgl=False, plot_width=750, plot_height=750) p.border_fill_color = '#eeeeee' p.background_fill_color = 'white' p.outline_line_color = None p.grid.grid_line_color = None session = push_session(curdoc()) curdoc().add_root(p) session.show() car = Car([1.0, 2.0], angle_to_vector(math.pi / 2), wheels_angle=0.4, speed=1.0, width=1.0, length=2.0, fig=p, nrays=36) border = geom.Figure( [[-10.0, -10.0], [-10.0, 10.0], [10.0, 10.0], [10.0, -10.0]], close=True, fig=p) obstacle = geom.Figure( [[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]], close=True, fig=p) #obstacle = geom.Figure(close=True, fig=p) #print border.points #obstacle.set_points([[-5.0, 0.0], [0.0, 0.0], [0.0, -5.0], [-5.0, -5.0]]) env = geom.CompoundFigure([border, obstacle]) env.draw() for i in xrange(10000): car.turn_wheels(random.random() - 0.5) car.save_pos() car.move(0.1) if car.path().intersect(env) != None: car.restore_pos() car.speed = -car.speed car.draw(env) time.sleep(0.01)
def __init__(self, box): self.doc = curdoc() self.box = box # open a session to keep local doc in sync with server self.session = push_session(self.doc) self.particle_source = ColumnDataSource(data=dict(x=[0], y=[0])) self.agent_source = ColumnDataSource(data=dict(x=[0], y=[0])) # @gen.coroutine # setup plot self.p = figure(plot_width=600, plot_height=600, x_range=(0, 10), y_range=(0, 10)) self.particle_source = ColumnDataSource(data=box.particles) self.agent_source = ColumnDataSource(data=box.agents) self.particles = self.p.circle('x', 'y', source=self.particle_source, radius=box.size[1]) self.agents = self.p.circle('x', 'y', source=self.agent_source, radius=box.size[0], color="red") # put the button and plot in a layout and add to the document self.doc.add_root(row(self.p)) # self.thread2 = Thread(target=self.animate) # self.thread2.daemon = True # self.thread2.start() # self.animate() self.doc.add_periodic_callback(self.update, 50) # session.show(doc) # open the document in a browser # self.animate() self.session.show() thread = Thread(target=self.session.loop_until_closed) thread.daemon = True thread.start()
def __init__(self, url: str, session_id: str = None, display: bool = True) -> object: """ Create a BokehServerSession object. We will link this server session with a document, self.document, which allows changes to be pushed to the server. :param url: url for server :param session_id: unique session id for server session :param display: a bool variable to indicate if output is to be displayed immediately. """ self.document = Document() self.server_session = push_session(self.document, url=url, session_id=session_id) if display: self.server_session.show()
def build_plots(self ): self.BokehDoc = curdoc() plot_toml_path = os.path.join(self.settings["Project Path"], 'Settings', 'plotting_settings.toml') plot_info = self.read_settings(plot_toml_path) _plots = {} _layouts = [] for plot_type, plot_dict in plot_info.items(): for plot_name, plot_data in plot_dict.items(): _plots[plot_name] = create_plot(plot_type, plot_data, self.network_graph) _layouts.append(_plots[plot_name].GetLayout()) final_layout = self.configure_layouts(_layouts) Layout = column(final_layout) self.BokehDoc.add_root(Layout) self.BokehDoc.title = "PyDSS" self.session = push_session(self.BokehDoc) self.session.show() return _plots
def __init__(self, n_x, x_axis_label, names, show=True, title='Monitor neural network training'): """ Parameters ---------- n_x : int total number of expected samples in x-direction x_axis_label : string names : list of strings names of the quantities to be monitored show : bool (True by default) if True, browser window is automatically opened and dynamically updated title : str (default: 'Monitor neural network training') Notes ----- The plot is served under: http://localhost:port/?bokeh-session-id=disease-detection """ self.n_x = n_x self.seen_so_far = 0 self.p = bp.figure(title=title, x_axis_label=x_axis_label, x_range=[0, n_x]) self.y = {k: np.zeros(n_x) for k in names} self.x = np.arange(n_x) # Add one line for each tracked quantity: self.l = {} colors = sns.color_palette(n_colors=len(names)).as_hex() for i, k in enumerate(names): self.l[k] = self.p.line(x=[], y=[], line_color=colors[i], legend=k, line_width=2) self.curdoc = bp.curdoc() # This line is crucial as it adds the necessary on change callbacks: self.curdoc.add_root(self.p) self.session = bc.push_session(self.curdoc, session_id='disease-detection') if show: self.session.show() self.show = show
def _CreatePlots(self, PlotsDict): self.BokehDoc = curdoc() Figures = [] for PlotType, PlotNames in PlotsDict.items(): newPlotNames = list(PlotNames) PlotType1 = ['Topology', 'GISplot', 'NetworkGraph'] PlotType2 = ['SagPlot', 'Histogram'] PlotType3 = ['XY', 'TimeSeries', 'FrequencySweep'] for Name in newPlotNames: PlotSettings = PlotNames[Name] PlotSettings['FileName'] = Name if PlotType in PlotType1: self._pyPlotObjects[PlotType] = pyPlots.pyPlots.Create( PlotType, PlotSettings, self._dssBuses, self._dssObjectsByClass, self._dssCircuit, self._dssSolver) Figures.append(self._pyPlotObjects[PlotType].GetFigure()) #self.BokehDoc.add_root(self._pyPlotObjects[PlotType].GetFigure()) self._Logger.info('Created pyPlot -> ' + PlotType) elif PlotType in PlotType2: self._pyPlotObjects[PlotType + Name] = pyPlots.pyPlots.Create( PlotType, PlotSettings, self._dssBuses, self._dssObjectsByClass, self._dssCircuit, self._dssSolver) self._Logger.info('Created pyPlot -> ' + PlotType) elif PlotType in PlotType3: self._pyPlotObjects[PlotType + Name] = pyPlots.pyPlots.Create( PlotType, PlotSettings, self._dssBuses, self._dssObjects, self._dssCircuit, self._dssSolver) self._Logger.info('Created pyPlot -> ' + PlotType) Layout = row(*Figures) self.BokehDoc.add_root(Layout) self.BokehDoc.title = "PyDSS" self.session = push_session(self.BokehDoc) self.session.show() return
def __init__(self,PlotProperties, dssBuses, dssObjectsbyClass, dssCircuit, dssSolver): super(VoltageDistance).__init__() self.__dssBuses = dssBuses self.__PlotProperties = PlotProperties self.__dssObjectsByClass = dssObjectsbyClass self.VoltagePhase = PlotProperties['Phase'] #for BusName in dssBuses: # print(dssBuses[BusName].Distance) self.BusData = self.GetBusData() self.LineData = self.GetLineData() self.busDataSource = ColumnDataSource(self.BusData) Vlb = PlotProperties['Vlb'] Vub = PlotProperties['Vub'] ########################## TOOL TIP DATA ################################ hoverBus = HoverTool(tooltips=[ ("Name", "@Name"), ("Distance", "@Distance"), ("Voltage", "@puVoltage"), ]) output_file(PlotProperties['FileName']) self.__Figure = figure(plot_width=int(self.__PlotProperties['Width']), plot_height=int(self.__PlotProperties['Height']), tools=[ResetTool(), hoverBus, BoxSelectTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), PanTool()]) # tools=[hover] a = self.BusData['Distance'].max() self.BusPlot = self.__Figure.circle(x='Distance', y='puVoltage', source=self.busDataSource, legend='Nodes') self.lineLB = self.__Figure.line([0, PlotProperties['Dmax']], [Vlb, Vlb], line_width=2) self.lineUB = self.__Figure.line([0, PlotProperties['Dmax']], [Vub, Vub], line_width=2) self.Lineplot = self.__Figure.multi_line(self.LineX, self.LineY, legend='Lines', color='green') self.Lineplot1 = self.__Figure.multi_line(self.trX, self.trY, legend='XFMRs', color='red') self.__Figure.legend.location = "top_right" self.__Figure.legend.click_policy = "hide" curdoc().add_root(self.__Figure) curdoc().title = "PyDSS" session = push_session(curdoc()) session.show(self.__Figure) return
def init_func(self, target_df, f, title, legend=None, interval=1, colors=None, **kwargs): # self.connect_to_server() self.p = figure(plot_width=400, plot_height=400, title=title) (y0, x0) = f(**kwargs) target_df["x/", "val/"].set_matrix(np.array(x0).reshape(1, len(x0))) target_df["y/", "val/"].set_matrix(np.array(y0).reshape(1, len(y0))) if len(legend) == 0: for i in range(len(y0)): legend.append(str(i)) if len(colors) == 0: for i in range(len(y0)): color = "#%06x" % randint(0, 0xFFFFFF) colors.append(color) if len(y0) != len(x0): raise ValueError("f must return two lists of equal length, equal\ to the number of lines to be plotted.") if len(y0) != len(legend): raise ValueError("length of legend must match number of\ lines plotted") if len(y0) != len(colors): raise ValueError("length of list of colors must much number of\ lines plotted") for i in range(len(legend)): self.p.line([], [], name=legend[i], legend=legend[i], color=colors[i]) self.session = push_session(curdoc()) tag = autoload_server(self.p, session_id=self.session.id) target_df._top_df._plots.append(tag)
def __init__(self, map_size, team_size): # start bokeh server if it doesn't exist # note: there should be only one process to update the session, otherwise chaos # TODO: this process will not be closed when main process quit, but it doesn't matter # must wait this serve process to run up then we can draw try: requests.get("http://localhost:5006") except Exception as e: subprocess.Popen(['bokeh', 'serve'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) print(">> waiting for bokeh server starting, 5 seconds...") time.sleep(5) print(">> here we go!") self.draw_init_plot(map_size, team_size) # curdoc().add_root(plt_combo) # open a session to keep our local document in sync with server session = push_session(curdoc()) session.show(self.plt_combo) # open the document in a browser
def __init__(self, PlotProperties, dssBuses, dssObjects, dssCircuit, dssSolver): super(FrequencySweep).__init__() self.__dssSolver = dssSolver self.__dssBuses = dssBuses self.__dssObjs = dssObjects self.__dssCircuit = dssCircuit self.__PlotProperties = PlotProperties self.plotted_object = self.getObject(PlotProperties['Object Name'], PlotProperties['Object Type']) output_file(PlotProperties['FileName']) freq = dssSolver.getFrequency() yVal = self.getObjectValue(self.plotted_object, PlotProperties['Property'], PlotProperties['Indices']) self.data = {'frequency': [0]} self.data[PlotProperties['Property']] = [0] self.data_source = ColumnDataSource(self.data) self.__Figure = figure(plot_width=self.__PlotProperties['Width'], plot_height=self.__PlotProperties['Height'], title='Frequency sweep plot: ' + PlotProperties['Object Name']) self.ScatterPlot = self.__Figure.line(x='frequency', y=PlotProperties['Property'], color='green', source=self.data_source) self.__Figure.yaxis.axis_label = PlotProperties[ 'Property'] + ' - ' + PlotProperties['Indices'] self.__Figure.xaxis.axis_label = 'frequency [Hz]' self.doc = curdoc() self.doc.add_root(self.__Figure) self.doc.title = "PyDSS" self.session = push_session(self.doc) self.session.show(self.__Figure) # open the document in a browser self.__time = dssSolver.GetDateTime() return
def test_server(): session = push_session(curdoc()) session.show() # create the figure fig = figure(title='testing', x_axis_label='iterations', y_axis_label='value', logo=None, toolbar_location='right') # create a new line l = fig.line([], [], legend='test_line', name='test_line', line_color='#1f77b4') for i in range(100): if i == 0: l.data_source.stream({'x': [i], 'y': [10]}) else: l.data_source.stream({'x': [i], 'y': [i]}) time.sleep(0.05) print 'done!'
def run(self): print("In thread.run") self.p = figure(plot_height=500, tools=TOOLS, y_axis_location='left', title=self.title) self.p.x_range.follow = "end" self.p.xaxis.axis_label = "Timestamp" self.p.x_range.follow_interval = 100 self.p.x_range.range_padding = 0 self.p.line(x="timestamp", y="value", color="blue", source=self.source) self.p.circle(x="timestamp", y="value", color="red", source=self.source) self.session = push_session(curdoc()) curdoc().add_periodic_callback(self.update, 100) #period in ms self.session.show(column(self.p)) curdoc().title = 'Sensor' self.session.loop_until_closed()
def _initialize(self, figsize, **kwargs): map_options = GMapOptions(**kwargs) self.map = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=figsize[0], plot_height=figsize[1]) self.map.api_key = self.key self.source = ColumnDataSource(dict( lat=[], lon=[], index=[], )) self.text = ColumnDataSource(dict( x=[], y=[], text=[], )) mapper = LinearColorMapper(palette=Magma[256]) circle = Circle(x="lon", y="lat", size=15, fill_color={ "field": "index", "transform": mapper }) text = Text(x="x", y="y", text="text") self.map.add_glyph(self.source, circle) self.map.add_glyph(self.text, text) self.map.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool()) session = push_session(curdoc()) curdoc().add_root(self.map) session.show()
def serve_plot(x_key, y_key, **kwargs): r"""Live plot log entries on the current Bokeh server. Parameters ---------- x_key : str The key in the serialized JSON object that contains the x-axis value. y_key : str See `x_key`. \*\*kwargs Connection parameters passed to the `connect` function. """ subscriber, sequence, x, y = connect(x_key, y_key, **kwargs) session = push_session(curdoc()) fig = figure() plot = fig.line(x, y) serve_update = partial(update, x_key, y_key, sequence, subscriber, plot) curdoc().add_periodic_callback(serve_update, 50) return session
def test_server_session_next_tick_async(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() doc.add_root(DictModel()) client_session = push_session( doc, session_id='test_server_session_next_tick_async', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) result = next(iter(server_session.document.roots)) @gen.coroutine def cb(): # we're testing that we can modify the doc and be # "inside" the document lock result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) cb_id = server_session.document.add_next_tick_callback(cb) client_session.loop_until_closed(suppress_warning=True) with pytest.raises(ValueError) as exc: server_session.document.remove_next_tick_callback(cb_id) assert 'already removed' in repr(exc.value) assert dict(a=0, b=1, c=2, d=3, e=4) == result.values
def input(): hover = HoverTool( tooltips=[('Agency', '<font color="#000000"> @agency, @city, @state</font>')]) plot = format( figure(title="Hit Rate vs Search Rate Split by Race", plot_width=800, plot_height=400, tools=[hover, "pan", "wheel_zoom", "box_zoom", "reset"])) plot.circle('black_search_rate', 'black_hit_rate', color="#dd3439", size=10, source=source_rates, legend="Black Drivers", alpha=0.7) plot.circle('white_search_rate', 'white_hit_rate', color="#257bf8", size=10, source=source_rates, legend="White Drivers", alpha=0.7) plot.xaxis.axis_label = "Searches / Stops" plot.yaxis.axis_label = "Hits / Searches" curdoc().add_root(plot) session = push_session(curdoc()) bokeh_script = autoload_server(plot, session_id=session.id, url=url) bokeh_id = bokeh_script.split()[2].split('"')[1] print "script:" print bokeh_script print "id:" print bokeh_id return render_template("input.html", bokeh_script=bokeh_script)
def test_server_session_timeout_async(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() doc.add_root(DictModel()) client_session = push_session( doc, session_id='test_server_session_timeout_async', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) result = next(iter(server_session.document.roots)) @gen.coroutine def cb(): # we're testing that we can modify the doc and be # "inside" the document lock result.values['a'] = 0 result.values['b'] = yield self.async_value(1) result.values['c'] = yield self.async_value(2) result.values['d'] = yield self.async_value(3) result.values['e'] = yield self.async_value(4) client_session.close() raise gen.Return(5) server_session.document.add_timeout_callback(cb, 10) client_session.loop_until_closed() with (self.assertRaises(ValueError)) as manager: server_session.document.remove_timeout_callback(cb) self.assertTrue('already removed' in repr(manager.exception)) self.assertDictEqual(dict(a=0, b=1, c=2, d=3, e=4), result.values)
def animated_plot(xydata): """ I haven't been able to generate a working code for an animated plot function and I haven't been able to find out why. Whenever I try, I get an error message saying that index cannot be defined. """ b = xydata xlist = b[:, 1] ylist = b[:, 2] # create a plot and style its properties p = figure(x_range=(min(xlist), max(xlist)), y_range=(min(ylist), max(ylist)), toolbar_location=None) # add a text renderer to out plot (no data yet) r = p.line(x=[], y=[], line_width=3, color='navy') session = push_session(curdoc()) index = 0 ds = r.data_source # create a callback that will add the next point of the trajectory data def callback(): global index ds.data['x'].append(xlist[index]) ds.data['y'].append(ylist[index]) ds.trigger('data', ds.data, ds.data) index = index + 1 curdoc().add_periodic_callback(callback, 67) # open the document in a browser session.show() # run forever session.loop_until_closed()
def test_server_session_next_tick_async(self, ManagedServerLoop: MSL) -> None: application = Application() with ManagedServerLoop(application) as server: # XXX io_loop=IOLoop() doc = document.Document() doc.add_root(DictModel()) client_session = push_session( doc, session_id=ID("test_server_session_next_tick_async"), url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) result = next(iter(server_session.document.roots)) async def cb(): # we're testing that we can modify the doc and be # "inside" the document lock result.values['a'] = 0 result.values['b'] = await self.async_value(1) result.values['c'] = await self.async_value(2) result.values['d'] = await self.async_value(3) result.values['e'] = await self.async_value(4) client_session.close() return 5 cb_id = server_session.document.add_next_tick_callback(cb) client_session._loop_until_closed() with pytest.raises(ValueError) as exc: server_session.document.remove_next_tick_callback(cb_id) assert 'already removed' in repr(exc.value) assert dict(a=0, b=1, c=2, d=3, e=4) == result.values
def loop(): if self.context.config.instrument.interactive >= 1: self.context.bokeh_session = push_session(curdoc()) p = figure() c = column(children=[p]) curdoc().add_root(c) self.context.bokeh_session.show(c) else: self.context.bokeh_session = None while self.keep_going: try: action = '' event = '' event = self.get_event() if event is None: self.logger.info("No new events - do nothing") if self.event_queue.qsize() == 0 and \ self.event_queue_hi.qsize() == 0: self.logger.info( f"No pending events or actions, terminating") self.keep_going = False else: action = self.event_to_action(event, self.context) self.execute(action, self.context) if self.context.state == 'stop': break except Exception as e: self.logger.error( f"Exception while processing action {action}, {e}") if self.config.print_trace: traceback.print_exc() break self.keep_going = False
def _draw_plots(self, scaffolder): '''Setup all plots.''' self.contig_read_src = ColumnDataSource( dict(reads=[scaffolder.nrReads], contigs=[scaffolder.nrContigs], n50=[scaffolder.N50])) # Calculate data for contig circle plot circle = self._calculate_circle(scaffolder) self.contig_dist_src = ColumnDataSource( dict(start=circle[0], stop=circle[1], colors=circle[2], contigs=circle[3])) self.read_src = ColumnDataSource( dict(nrReads=[], nrPassReads=[], nrFailReads=[], readTime=[])) self.read_hist_src = ColumnDataSource( dict(readLength=[], left=[], right=[])) # Draw plots contigNrPlot = self._draw_contigNrPlot(scaffolder) n50Plot = self._draw_n50Plot() contigCirclePlot = self._draw_contigCirclePlot() readPlot = self._draw_readCountPlot() #readHist = self._draw_readLenHistPlot() # Position plots layout = gridplot([[n50Plot, contigNrPlot], [contigCirclePlot, readPlot]]) try: session = push_session(curdoc()) session.show(layout) except IOError: sys.exit("No bokeh server is running on this host")
from __future__ import print_function import time from numpy import pi, sin, cos, linspace from bokeh.util.browser import view from bokeh.document import Document from bokeh.models.glyphs import Line from bokeh.models import (Plot, DataRange1d, LinearAxis, Range1d, ColumnDataSource, PanTool, WheelZoomTool) from bokeh.client import push_session document = Document() session = push_session(document) x = linspace(-6 * pi, 6 * pi, 1000) y = sin(x) z = cos(x) source = ColumnDataSource(data=dict(x=x, y=y, z=z)) plot = Plot(x_range=Range1d(-2 * pi, 2 * pi), y_range=DataRange1d(), min_border=50) line_glyph = Line(x="x", y="y", line_color="blue") plot.add_glyph(source, line_glyph) line_glyph2 = Line(x="x", y="z", line_color="red") plot.add_glyph(source, line_glyph2)
def test_server_changes_go_to_client(self): application = Application() with ManagedServerLoop(application) as server: doc = document.Document() client_session = push_session( doc, session_id='test_server_changes_go_to_client', url=url(server), io_loop=server.io_loop) server_session = server.get_session('/', client_session.id) assert len(client_session.document.roots) == 0 server_root = SomeModelInTestClientServer(foo=42) def do_add_server_root(): server_session.document.add_root(server_root) server_session.with_document_locked(do_add_server_root) def client_has_root(): return len(doc.roots) > 0 client_session._connection._loop_until(client_has_root) client_root = next(iter(client_session.document.roots)) assert client_root.foo == 42 assert server_root.foo == 42 # Now try setting title on server side def do_set_server_title(): server_session.document.title = "Server Title" server_session.with_document_locked(do_set_server_title) def client_title_set(): return client_session.document.title != document.DEFAULT_TITLE client_session._connection._loop_until(client_title_set) assert client_session.document.title == "Server Title" # Now modify a model within the server document def do_set_property_on_server(): server_root.foo = 57 server_session.with_document_locked(do_set_property_on_server) # there is no great way to block until the server # has applied changes, since patches are sent # asynchronously. We use internal _loop_until API. def client_change_made(): return client_root.foo == 57 client_session._connection._loop_until(client_change_made) assert client_root.foo == 57 def do_remove_server_root(): server_session.document.remove_root(server_root) server_session.with_document_locked(do_remove_server_root) def client_lacks_root(): return len(doc.roots) == 0 client_session._connection._loop_until(client_lacks_root) assert len(client_session.document.roots) == 0 client_session.close() client_session.loop_until_closed(suppress_warning=True) assert not client_session.connected
a=cmap((df[str(Year)][itr])) rgb = a[:3] b=matplotlib.colors.rgb2hex(rgb) p.patch(x, y, fill_color=b,line_color="black") colors=['#fff7ec', '#feebd0', '#fddcaf', '#fdca94', '#fdb27b', '#fc8c59','#f26d4b', '#e0442f', '#c91d13', '#a80000'] mapper = LinearColorMapper(palette=colors, low=0, high=1) color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="5pt", label_standoff=6, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') listOfSubLayouts.append(p) #menu select = Select(options=["2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"],title="Year") select.on_change('value',update_plot) # show results mainLayout = row(row(p,name='mainLayout'),widgetbox(select)) curdoc().add_root(mainLayout) # #create a session session = push_session(curdoc()) session.loop_until_closed()
def serve(self, host='localhost', port=5006, session_id='test'): url = 'http://' + host + ':' + str(port) + '/' self.session = push_session(curdoc(), session_id=session_id, url=url)