def test_stream_cleanup(self): stream = Stream.define(str('Test'), test=1)() dmap = DynamicMap(lambda test: Curve([]), streams=[stream]) plot = mpl_renderer.get_plot(dmap) self.assertTrue(bool(stream._subscribers)) plot.cleanup() self.assertFalse(bool(stream._subscribers))
def test_server_dynamicmap_with_stream_dims(self): stream = Stream.define('Custom', y=2)() dmap = DynamicMap(lambda x, y: Curve([x, 1, y]), kdims=['x', 'y'], streams=[stream]).redim.values(x=[1, 2, 3]) obj, _ = bokeh_renderer._validate(dmap, None) session = self._threaded_launcher(obj) [(doc, _)] = obj.layout._documents.items() orig_cds = session.document.roots[0].select_one( {'type': ColumnDataSource}) self.assertEqual(orig_cds.data['y'][2], 2) def run(): stream.event(y=3) doc.add_next_tick_callback(run) time.sleep(1) cds = self.session.document.roots[0].select_one( {'type': ColumnDataSource}) self.assertEqual(cds.data['y'][2], 3) self.assertEqual(orig_cds.data['y'][0], 1) slider = obj.layout.select(DiscreteSlider)[0] def run(): slider.value = 3 doc.add_next_tick_callback(run) time.sleep(1) cds = self.session.document.roots[0].select_one( {'type': ColumnDataSource}) self.assertEqual(cds.data['y'][0], 3)
def test_deep_map_apply_element_function_with_stream_kwarg(self): stream = Stream.define('Test', label='New label')() fn = lambda i: Curve(np.arange(i)) dmap = DynamicMap(fn, kdims=[Dimension('Test', range=(10, 20))]) mapped = dmap.apply(lambda x, label: x.relabel(label), streams=[stream]) self.assertEqual(mapped[10], fn(10).relabel('New label'))
def test_stream_cleanup(self): stream = Stream.define(str('Test'), test=1)() dmap = DynamicMap(lambda test: Curve([]), streams=[stream]) plot = bokeh_renderer.get_plot(dmap) self.assertTrue(bool(stream._subscribers)) plot.cleanup() self.assertFalse(bool(stream._subscribers))
def test_periodic_param_fn_blocking(self): def callback(x): return Curve([1,2,3]) xval = Stream.define('x',x=0)() dmap = DynamicMap(callback, streams=[xval]) # Add stream subscriber mocking plot xval.add_subscriber(lambda **kwargs: dmap[()]) dmap.periodic(0.01, 100, param_fn=lambda i: {'x':i}) self.assertEqual(xval.x, 100)
def test_points_update_selected(self): stream = Stream.define('Selected', selected=[])() points = Points([(0, 0), (1, 1), (2, 2)]).apply.opts(selected=stream.param.selected) plot = bokeh_renderer.get_plot(points) cds = plot.handles['cds'] self.assertEqual(cds.selected.indices, []) stream.event(selected=[0, 2]) self.assertEqual(cds.selected.indices, [0, 2])
def test_dynamic_operation_init_stream_params(self): img = Image(sine_array(0, 5)) stream = Stream.define('TestStream', bin_range=None)() dmap_with_fn = histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.bin_range, (0, 1))
def __init__(self, groups, **params): super(AttributeAnnotator, self).__init__(**params) self.param.group.objects = groups self.param.group.default = groups[0] # self.point_sel_stream = Selection1D(source=self.points) self.poly_sel_stream = Selection1D(source=self.polys) self._group_data = {g: [] for g in groups} self.table_stream = Stream.define('TableUpdate')(transient=True)
def test_table_update_selected(self): stream = Stream.define('Selected', selected=[])() table = Table([(0, 0), (1, 1), (2, 2)], ['x', 'y']).apply.opts(selected=stream.param.selected) plot = bokeh_renderer.get_plot(table) cds = plot.handles['cds'] self.assertEqual(cds.selected.indices, []) stream.event(selected=[0, 2]) self.assertEqual(cds.selected.indices, [0, 2])
def __init__(self, groups, **params): super(PointWidgetAnnotator, self).__init__(**params) group_param = self.params('group') group_param.objects = groups group_param.default = groups[0] self.point_sel_stream = Selection1D(source=self.points) self._group_data = {g: [] for g in groups} self.table_stream = Stream.define('TableUpdate')(transient=True)
def test_dynamicmap_ndoverlay_shrink_number_of_items(self): selected = Stream.define('selected', items=3)() def callback(items): return NdOverlay({j: Overlay([Curve([1, 2, j])]) for j in range(items)}) dmap = DynamicMap(callback, streams=[selected]) plot = bokeh_renderer.get_plot(dmap) selected.event(items=2) self.assertEqual(len([r for r in plot.state.renderers if r.visible]), 2)
def test_layout_dimensioned_stream_title_update(self): stream = Stream.define('Test', test=0)() dmap = DynamicMap(lambda test: Curve([]), kdims=['test'], streams=[stream]) layout = dmap + Curve([]) plot = mpl_renderer.get_plot(layout) self.assertIn('test: 0', plot.handles['title'].get_text()) stream.event(test=1) self.assertIn('test: 1', plot.handles['title'].get_text()) plot.cleanup() self.assertEqual(stream._subscribers, [])
def test_grid_dimensioned_stream_title_update(self): stream = Stream.define('Test', test=0)() dmap = DynamicMap(lambda test: Curve([]), kdims=['test'], streams=[stream]) grid = GridMatrix({0: dmap, 1: Curve([])}, 'X') plot = bokeh_renderer.get_plot(grid) self.assertIn('test: 0', plot.handles['title'].text) stream.event(test=1) self.assertIn('test: 1', plot.handles['title'].text) plot.cleanup() self.assertEqual(stream._subscribers, [])
def test_periodic_param_fn_blocking_timeout(self): def callback(x): return Curve([1,2,3]) xval = Stream.define('x',x=0)() dmap = DynamicMap(callback, streams=[xval]) # Add stream subscriber mocking plot xval.add_subscriber(lambda **kwargs: dmap[()]) start = time.time() dmap.periodic(0.5, 100, param_fn=lambda i: {'x':i}, timeout=3) end = time.time() self.assertEqual((end - start) < 5, True)
def test_dimensioned_streams_with_dynamic_map_overlay_clone(self): time = Stream.define('Time', time=-3.0)() def crosshair(time): return VLine(time) * HLine(time) crosshair = DynamicMap(crosshair, kdims='time', streams=[time]) path = Path([]) t = crosshair * path html, _ = bokeh_renderer(t) self.assertIn('Bokeh Application', html)
def test_render_dynamicmap_with_stream(self): stream = Stream.define(str('Custom'), y=2)() dmap = DynamicMap(lambda y: Curve([1, 2, y]), kdims=['y'], streams=[stream]) obj, _ = self.renderer._validate(dmap, None) self.renderer.components(obj) [(plot, pane)] = obj._plots.values() y = plot.handles['fig']['data'][0]['y'] self.assertEqual(y[2], 2) stream.event(y=3) y = plot.handles['fig']['data'][0]['y'] self.assertEqual(y[2], 3)
def boxes_exploration_interactive(data_path): '''Returns an interactive plot with the agonia boxes with a confidence value above a Score selected by the user with a slider. The user can select a box by clicking on it and mean box Fluorescence and the Caiman DF/F of such box will be ploted.''' data_name, median_projection, fnames, fname_new, results_caiman_path, boxes_path = get_files_names( data_path) cnm = cnmf.load_CNMF(results_caiman_path) img = hv.Image(median_projection, bounds=(0, 0, median_projection.shape[1], median_projection.shape[0])).options(cmap='gray') with open(boxes_path, 'rb') as f: boxes = pickle.load(f) f.close() centers = np.empty((cnm.estimates.A.shape[1], 2)) for i, factor in enumerate(cnm.estimates.A.T): centers[i] = center_of_mass(factor.toarray().reshape( cnm.estimates.dims, order='F')) #scatter = hv.Scatter((centers[:,1], median_projection.shape[0] - centers[:,0])) kdims = [hv.Dimension('Score', values=np.arange(0.05, 1, 0.05))] tap = streams.SingleTap(transient=True, source=img) Experiment = Stream.define('Experiment', data_path=data_path) Centers = Stream.define('Centers', centers=centers) CaImAn_detection = Stream.define('CaImAn_detection', cnm=cnm) dmap = hv.DynamicMap(plot_AGonia_boxes_interactive, kdims=kdims, streams=[Experiment(), tap]) dmap1 = hv.DynamicMap(plot_boxes_traces, kdims=kdims, streams=[Experiment(), tap]) dmap2 = hv.DynamicMap( plot_seeded_traces, kdims=kdims, streams=[CaImAn_detection(), Experiment(), tap, Centers()]) return ((img * dmap).opts(width=500, height=500) + dmap1.opts(width=500, height=250) + dmap2.opts(width=500, height=250)).opts( opts.Curve(framewise=True)).cols(1)
def test_periodic_param_fn_non_blocking(self): def callback(x): return Curve([1,2,3]) xval = Stream.define('x',x=0)() dmap = DynamicMap(callback, streams=[xval]) # Add stream subscriber mocking plot xval.add_subscriber(lambda **kwargs: dmap[()]) self.assertNotEqual(xval.x, 100) dmap.periodic(0.0001, 100, param_fn=lambda i: {'x': i}, block=False) time.sleep(2) if not dmap.periodic.instance.completed: raise RuntimeError('Periodic callback timed out.') dmap.periodic.stop() self.assertEqual(xval.x, 100)
def test_periodic_param_fn_non_blocking(self): def callback(x): return Curve([1,2,3]) xval = Stream.define('x',x=0)() dmap = DynamicMap(callback, streams=[xval]) # Add stream subscriber mocking plot xval.add_subscriber(lambda **kwargs: dmap[()]) dmap.periodic(0.0001, 1000, param_fn=lambda i: {'x':i}, block=False) self.assertNotEqual(xval.x, 1000) for i in range(1000): time.sleep(0.01) if dmap.periodic.instance.completed: break dmap.periodic.stop() self.assertEqual(xval.x, 1000)
def test_dimensioned_streams_with_dynamic_callback_returns_layout(self): stream = Stream.define('aname', aname='a')() def cb(aname): x = np.linspace(0, 1, 10) y = np.random.randn(10) curve = Curve((x, y), group=aname) hist = Histogram(y) return (curve + hist).opts(shared_axes=False) m = DynamicMap(cb, kdims=['aname'], streams=[stream]) p = bokeh_renderer.get_plot(m) T = 'XYZT' stream.event(aname=T) self.assertIn('aname: ' + T, p.handles['title'].text, p.handles['title'].text) p.cleanup() self.assertEqual(stream._subscribers, [])
def test_periodic_counter_blocking(self): class Counter(object): def __init__(self): self.count = 0 def __call__(self): self.count += 1 return Curve([1,2,3]) next_stream = Stream.define('Next')() counter = Counter() dmap = DynamicMap(counter, streams=[next_stream]) # Add stream subscriber mocking plot next_stream.add_subscriber(lambda **kwargs: dmap[()]) dmap.periodic(0.01, 100) self.assertEqual(counter.count, 100)
def test_update_dynamic_map_with_stream(self): ys = np.arange(10) # Build stream Scale = Stream.define('Scale', scale=1.0) scale_stream = Scale() # Build DynamicMap def build_scatter(scale): return hv.Scatter(ys * scale) dmap = hv.DynamicMap(build_scatter, streams=[scale_stream]) # Create HoloViews Pane using panel so that we can access the plotly pane # used to display the plotly figure dmap_pane = pn.pane.HoloViews(dmap, backend='plotly') # Call get_root to force instantiation of internal plots/models doc = Document() comm = Comm() dmap_pane.get_root(doc, comm) # Get reference to the plotly pane _, plotly_pane = next(iter(dmap_pane._plots.values())) # Check initial data data = plotly_pane.object['data'] self.assertEqual(len(data), 1) self.assertEqual(data[0]['type'], 'scatter') np.testing.assert_equal(data[0]['y'], ys) # Watch object for changes fn = Mock() plotly_pane.param.watch(fn, 'object') # Update stream scale_stream.event(scale=2.0) # Check that figure object was updated data = plotly_pane.object['data'] np.testing.assert_equal(data[0]['y'], ys * 2.0) # Check that object callback was triggered fn.assert_called_once() args, kwargs = fn.call_args_list[0] event = args[0] self.assertIs(event.obj, plotly_pane) self.assertIs(event.new, plotly_pane.object)
def test_static_source_optimization(self): global data data = np.ones((5, 5)) img = Image(data) def get_img(test): global data data *= test return img stream = Stream.define(str('Test'), test=1)() dmap = DynamicMap(get_img, streams=[stream]) plot = bokeh_renderer.get_plot(dmap, doc=Document()) source = plot.handles['source'] self.assertEqual(source.data['image'][0].mean(), 1) stream.event(test=2) self.assertTrue(plot.static_source) self.assertEqual(source.data['image'][0].mean(), 2) self.assertNotIn(source, plot.current_handles)
def test_render_dynamicmap_with_stream_dims(self): stream = Stream.define(str('Custom'), y=2)() dmap = DynamicMap(lambda x, y: Curve([x, 1, y]), kdims=['x', 'y'], streams=[stream]).redim.values(x=[1, 2, 3]) obj, _ = self.renderer._validate(dmap, None) self.renderer.components(obj) [(plot, pane)] = obj._plots.values() cds = plot.handles['cds'] self.assertEqual(cds.data['y'][2], 2) stream.event(y=3) self.assertEqual(cds.data['y'][2], 3) self.assertEqual(cds.data['y'][0], 1) slider = obj.layout.select(DiscreteSlider)[0] slider.value = 3 self.assertEqual(cds.data['y'][0], 3)
def boxes_exploration(data_path): '''Returns an interactive plot with the agonia boxes with a confidence value above a Score selected by the user with a slider. The user can see the mean-trace of a specific box and scroll through the boxes with a slider''' data_name, median_projection, boxes_path = get_files_names(data_path) with open(boxes_path, 'rb') as f: boxes = pickle.load(f) f.close() kdims = [ hv.Dimension('Score', values=np.arange(0.05, 1, 0.05)), hv.Dimension('box_idx', values=np.arange(0, len(boxes), 1)) ] Experiment = Stream.define('Experiment', data_path=data_path) dmap = hv.DynamicMap(plot_AGonia_boxes, kdims=kdims, streams=[Experiment()]) return dmap
def test_server_dynamicmap_with_stream(self): stream = Stream.define('Custom', y=2)() dmap = DynamicMap(lambda y: Curve([1, 2, y]), kdims=['y'], streams=[stream]) obj, _ = bokeh_renderer._validate(dmap, None) server, session = self._launcher(obj, port=6005) [(doc, _)] = obj._documents.items() cds = session.document.roots[0].select_one({'type': ColumnDataSource}) self.assertEqual(cds.data['y'][2], 2) def run(): stream.event(y=3) doc.add_next_tick_callback(run) time.sleep(1) cds = self.session.document.roots[0].select_one( {'type': ColumnDataSource}) self.assertEqual(cds.data['y'][2], 3) server.stop()
def test_layout_framewise_nonmatching_norm_update(self): img1 = Image(np.mgrid[0:5, 0:5][0], vdims='z').opts(framewise=True) stream = Stream.define('zscale', value=1)() transform = dim('z2') * stream.param.value img2 = Image( np.mgrid[0:5, 0:5][0], vdims='z2').apply.transform(z2=transform).opts(framewise=True) plot = bokeh_renderer.get_plot(img1 + img2) img1_plot = plot.subplots[(0, 0)].subplots['main'] img2_plot = plot.subplots[(0, 1)].subplots['main'] img1_cmapper = img1_plot.handles['color_mapper'] img2_cmapper = img2_plot.handles['color_mapper'] self.assertEqual(img1_cmapper.low, 0) self.assertEqual(img2_cmapper.low, 0) self.assertEqual(img1_cmapper.high, 4) self.assertEqual(img2_cmapper.high, 4) stream.update(value=10) self.assertEqual(img1_cmapper.high, 4) self.assertEqual(img2_cmapper.high, 40) stream.update(value=2) self.assertEqual(img1_cmapper.high, 4) self.assertEqual(img2_cmapper.high, 8)
import param import numpy as np from holoviews import Dimension, NdLayout, GridSpace, Layout, NdOverlay from holoviews.core.spaces import DynamicMap, HoloMap, Callable from holoviews.core.options import Store from holoviews.element import Image, Scatter, Curve, Text, Points from holoviews.operation import histogram from holoviews.plotting.util import initialize_dynamic from holoviews.streams import Stream, LinkedStream, PointerXY, PointerX, PointerY, RangeX, Buffer from holoviews.util import Dynamic from holoviews.element.comparison import ComparisonTestCase from ..utils import LoggingComparisonTestCase from .testdimensioned import CustomBackendTestCase, TestObj XY = Stream.define('XY', x=0, y=0) X = Stream.define('X', x=0) Y = Stream.define('Y', y=0) frequencies = np.linspace(0.5, 2.0, 5) phases = np.linspace(0, np.pi * 2, 5) x, y = np.mgrid[-5:6, -5:6] * 0.1 def sine_array(phase, freq): return np.sin(phase + (freq * x**2 + freq * y**2)) class TestParameters(param.Parameterized): example = param.Number(default=1)
import param import numpy as np from holoviews import Dimension, NdLayout, GridSpace, Layout, NdOverlay from holoviews.core.spaces import DynamicMap, HoloMap, Callable from holoviews.core.options import Store from holoviews.element import Image, Scatter, Curve, Text, Points from holoviews.operation import histogram from holoviews.plotting.util import initialize_dynamic from holoviews.streams import Stream, LinkedStream, PointerXY, PointerX, PointerY, RangeX, Buffer from holoviews.util import Dynamic from holoviews.element.comparison import ComparisonTestCase from .testdimensioned import CustomBackendTestCase, TestObj XY = Stream.define('XY', x=0,y=0) frequencies = np.linspace(0.5,2.0,5) phases = np.linspace(0, np.pi*2, 5) x,y = np.mgrid[-5:6, -5:6] * 0.1 def sine_array(phase, freq): return np.sin(phase + (freq*x**2+freq*y**2)) class DynamicMapConstructor(ComparisonTestCase): def test_simple_constructor_kdims(self): DynamicMap(lambda x: x, kdims=['test'])
def test_dynamic_operation_init_stream_params(self): img = Image(sine_array(0,5)) stream = Stream.define('TestStream', bin_range=None)() histogram(img, bin_range=(0, 1), streams=[stream], dynamic=True) self.assertEqual(stream.bin_range, (0, 1))
import uuid from collections import deque import time import numpy as np from holoviews import Dimension, NdLayout, GridSpace, Layout from holoviews.core.spaces import DynamicMap, HoloMap, Callable from holoviews.element import Image, Scatter, Curve, Text, Points from holoviews.operation import histogram from holoviews.streams import Stream, PointerXY, PointerX, PointerY, RangeX from holoviews.util import Dynamic from holoviews.element.comparison import ComparisonTestCase XY = Stream.define('XY', x=0, y=0) frequencies = np.linspace(0.5, 2.0, 5) phases = np.linspace(0, np.pi * 2, 5) x, y = np.mgrid[-5:6, -5:6] * 0.1 def sine_array(phase, freq): return np.sin(phase + (freq * x**2 + freq * y**2)) class DynamicMapConstructor(ComparisonTestCase): def test_simple_constructor_kdims(self): DynamicMap(lambda x: x, kdims=['test']) def test_simple_constructor_invalid_no_kdims(self): regexp = ( "Callable '<lambda>' accepts more positional arguments than there are "
from holoviews.streams import Stream, PlotSize, RangeXY try: from holoviews.operation.datashader import spread, datashade except: spread = datashade = None datashade_skip = skipIf(datashade is None, "datashade is not available") class XY(Stream): x = param.Number(constant=True) y = param.Number(constant=True) Z = Stream.define("Z", z=0.0) PX = Stream.define("PX", px=1) class TestDecollation(ComparisonTestCase): def setUp(self): from holoviews.tests.teststreams import Sum, Val # kdims: a and b self.dmap_ab = DynamicMap(lambda a, b: Points([a, b]), kdims=['a', 'b']).redim.range(a=(0.0, 10.0), b=(0.0, 10.0)) # kdims: b self.dmap_b = DynamicMap(lambda b: Points([b, b]),
hv.extension('bokeh') renderer = hv.renderer('bokeh') aapl_df = pd.DataFrame(AAPL['close'], columns=['close'], index=pd.to_datetime(AAPL['date'])) goog_df = pd.DataFrame(GOOG['close'], columns=['close'], index=pd.to_datetime(GOOG['date'])) aapl_df.index.name = 'Date' goog_df.index.name = 'Date' aapl_curve = hv.Curve(aapl_df, 'Date', ('close', 'Price ($)')) goog_curve = hv.Curve(goog_df, 'Date', ('close', 'Price ($)')) chosen_stocks_stream = Stream.define('Toggle Stocks', active=[0, 1])() stock_symbols = [('aapl', aapl_curve), ('goog', goog_curve)] def stocks_callback(active): print(f"Callback {active}") return hv.Overlay([(crv if i in active else hv.Curve([])) for (i, (sym, crv)) in enumerate(stock_symbols)]) def change_active_stocks(attr, old, new): chosen_stocks_stream.event(active=new) dmap = hv.DynamicMap(stocks_callback, streams=[chosen_stocks_stream]) olayed = dmap