def test_tidy_chart_index_by(self, kind, element): plot = self.df.hvplot(x='index', y='y', by='x', kind=kind) obj = NdOverlay( { 1: element(self.df[self.df.x == 1], 'index', 'y'), 3: element(self.df[self.df.x == 3], 'index', 'y'), 5: element(self.df[self.df.x == 5], 'index', 'y') }, 'x') self.assertEqual(plot, obj)
def _sample(self, obj, data): """ Rasterizes the supplied object in the current region and samples it with the drawn paths returning an NdOverlay of Curves. Note: Because the function returns an NdOverlay containing a variable number of elements batching must be enabled and the legend_limit must be set to 0. """ if self.path_stream.data is None: path = self.path else: path = self.path_stream.element if isinstance(obj, TriMesh): vdim = obj.nodes.vdims[0] else: vdim = obj.vdims[0] if len(path) > 2: x_range = path.range(0) y_range = path.range(1) else: return NdOverlay({0: Curve([], 'Distance', vdim)}) (x0, x1), (y0, y1) = x_range, y_range width, height = (max([min([(x1 - x0) / self.resolution, 500]), 10]), max([min([(y1 - y0) / self.resolution, 500]), 10])) raster = rasterize(obj, x_range=x_range, y_range=y_range, aggregator=self.aggregator, width=int(width), height=int(height), dynamic=False) x, y = raster.kdims sections = [] for g in path.geom(): xs, ys, distance = self._gen_samples(g) indexes = {x.name: xs, y.name: ys} points = raster.data.sel_points(method='nearest', **indexes).to_dataframe() points['Distance'] = distance sections.append(Curve(points, 'Distance', vdims=[vdim, x, y])) return NdOverlay(dict(enumerate(sections)))
def test_wide_chart_labels(self, kind, element): plot = self.df.hvplot(kind=kind, value_label='Test', group_label='Category') obj = NdOverlay( { 'x': element(self.df, 'index', 'x').redim(x='Test'), 'y': element(self.df, 'index', 'y').redim(y='Test') }, 'Category') self.assertEqual(plot, obj)
def _pos_indicator(self, obj, x): """ Returns an NdOverlay of Points indicating the current mouse position along the cross-sections. Note: Because the function returns an NdOverlay containing a variable number of elements batching must be enabled and the legend_limit must be set to 0. """ points = [] elements = obj or [] for el in elements: if len(el) < 1: continue p = Points(el[x], ['x', 'y'], crs=ccrs.GOOGLE_MERCATOR) points.append(p) if not points: return NdOverlay({0: Points([], ['x', 'y'])}) return NdOverlay(enumerate(points))
def test_image_contours(self): img = Image(np.array([[0, 1, 0], [3, 4, 5.], [6, 7, 8]])) op_contours = contours(img) ndoverlay = NdOverlay(None, kdims=['Levels']) ndoverlay[0.5] = Contours([[(-0.5, 0.416667), (-0.25, 0.5)], [(0.25, 0.5), (0.5, 0.45)]], group='Level', level=0.5, vdims=img.vdims) self.assertEqual(op_contours, img * ndoverlay)
def test_aggregate_points_categorical(self): points = Points([(0.2, 0.3, 'A'), (0.4, 0.7, 'B'), (0, 0.99, 'C')], vdims='z') img = aggregate(points, dynamic=False, x_range=(0, 1), y_range=(0, 1), width=2, height=2, aggregator=ds.count_cat('z')) xs, ys = [0.25, 0.75], [0.25, 0.75] expected = NdOverlay({'A': Image((xs, ys, [[1, 0], [0, 0]]), vdims='z Count'), 'B': Image((xs, ys, [[0, 0], [1, 0]]), vdims='z Count'), 'C': Image((xs, ys, [[0, 0], [1, 0]]), vdims='z Count')}, kdims=['z']) self.assertEqual(img, expected)
def test_overlay_integer_indexing(self): overlay = NdOverlay( list(enumerate([self.view1, self.view2, self.view3]))) self.assertEqual(overlay[0], self.view1) self.assertEqual(overlay[1], self.view2) self.assertEqual(overlay[2], self.view3) try: overlay[3] raise AssertionError("Index should be out of range.") except KeyError: pass
def test_aggregate_points_categorical_zero_range(self): points = Points([(0.2, 0.3, 'A'), (0.4, 0.7, 'B'), (0, 0.99, 'C')], vdims='z') img = aggregate(points, dynamic=False, x_range=(0, 0), y_range=(0, 1), aggregator=ds.count_cat('z')) xs, ys = [], [0.25, 0.75] params = dict(bounds=(0, 0, 0, 1), xdensity=1) expected = NdOverlay({'A': Image((xs, ys, np.zeros((2, 0))), vdims='z Count', **params), 'B': Image((xs, ys, np.zeros((2, 0))), vdims='z Count', **params), 'C': Image((xs, ys, np.zeros((2, 0))), vdims='z Count', **params)}, kdims=['z']) self.assertEqual(img, expected)
def test_image_contours_filled(self): img = Image(np.array([[0, 1, 0], [3, 4, 5.], [6, 7, 8]])) op_contours = contours(img, filled=True, levels=[2, 2.5]) ndoverlay = NdOverlay(None, kdims=['Levels']) data = [[(0., 0.333333), (0.5, 0.3), (0.5, 0.25), (0., 0.25), (-0.5, 0.08333333), (-0.5, 0.16666667), (0., 0.33333333)]] ndoverlay[0.5] = Polygons(data, group='Level', level=2, vdims=img.vdims) self.assertEqual(op_contours, img * ndoverlay)
def test_includes_str_if_no_num_chart(self, kind, element): plot = self.cat_only_df.hvplot(kind=kind) obj = NdOverlay( { 'upper': element(self.cat_only_df, 'index', 'upper').redim(upper='value'), 'lower': element(self.cat_only_df, 'index', 'lower').redim(lower='value'), }, 'Variable') self.assertEqual(plot, obj)
def test_curve_overlay_hover_batched(self): obj = NdOverlay({i: Curve(np.random.rand(10, 2)) for i in range(5)}, kdims=['Test']) opts = { 'Curve': { 'tools': ['hover'] }, 'NdOverlay': { 'legend_limit': 0 } } obj = obj(plot=opts) self._test_hover_info(obj, [('Test', '@Test')])
def test_points_errorbars_text_ndoverlay_categorical_xaxis(self): overlay = NdOverlay({ i: Points(([chr(65 + i)] * 10, np.random.randn(10))) for i in range(5) }) error = ErrorBars([(el['x'][0], np.mean(el['y']), np.std(el['y'])) for el in overlay]) text = Text('C', 0, 'Test') plot = bokeh_renderer.get_plot(overlay * error * text) x_range = plot.handles['x_range'] y_range = plot.handles['y_range'] self.assertIsInstance(x_range, FactorRange) self.assertEqual(x_range.factors, ['A', 'B', 'C', 'D', 'E']) self.assertIsInstance(y_range, Range1d)
def test_shade_categorical_images_grid(self): xs, ys = [0.25, 0.75], [0.25, 0.75] data = NdOverlay({'A': Image((xs, ys, [[1, 0], [0, 0]]), datatype=['grid'], vdims='z Count'), 'B': Image((xs, ys, [[0, 0], [1, 0]]), datatype=['grid'], vdims='z Count'), 'C': Image((xs, ys, [[0, 0], [1, 0]]), datatype=['grid'], vdims='z Count')}, kdims=['z']) shaded = shade(data) r = [[228, 255], [66, 255]] g = [[26, 255], [150, 255]] b = [[28, 255], [129, 255]] a = [[40, 0], [255, 0]] expected = RGB((xs, ys, r, g, b, a), datatype=['grid'], vdims=RGB.vdims+[Dimension('A', range=(0, 1))]) self.assertEqual(shaded, expected)
def test_points_overlay_hover(self): obj = NdOverlay({i: Points(np.random.rand(10, 2)) for i in range(5)}, kdims=['Test']) opts = { 'Points': { 'tools': ['hover'] }, 'NdOverlay': { 'legend_limit': 0 } } obj = obj(plot=opts) self._test_hover_info(obj, [('Test', '@Test'), ('x', '@x'), ('y', '@y')])
def test_polygons_overlay_hover(self): obj = NdOverlay( { i: Polygons([np.random.rand(10, 2)], vdims=['z'], level=0) for i in range(5) }, kdims=['Test']) opts = { 'Polygons': { 'tools': ['hover'] }, 'NdOverlay': { 'legend_limit': 0 } } obj = obj(plot=opts) self._test_hover_info(obj, [('Test', '@Test'), ('z', '@z')])
def test_aggregate_ndoverlay_count_cat_datetimes_microsecond_timebase(self): dates = pd.date_range(start="2016-01-01", end="2016-01-03", freq='1D') xstart = np.datetime64('2015-12-31T23:59:59.723518000', 'us') xend = np.datetime64('2016-01-03T00:00:00.276482000', 'us') curve = Curve((dates, [1, 2, 3])) curve2 = Curve((dates, [3, 2, 1])) ndoverlay = NdOverlay({0: curve, 1: curve2}, 'Cat') imgs = aggregate(ndoverlay, aggregator=ds.count_cat('Cat'), width=2, height=2, x_range=(xstart, xend), dynamic=False) bounds = (np.datetime64('2015-12-31T23:59:59.723518'), 1.0, np.datetime64('2016-01-03T00:00:00.276482'), 3.0) dates = [np.datetime64('2016-01-01T11:59:59.861759000',), np.datetime64('2016-01-02T12:00:00.138241000')] expected = Image((dates, [1.5, 2.5], [[1, 0], [0, 2]]), datatype=['xarray'], bounds=bounds, vdims='Count') expected2 = Image((dates, [1.5, 2.5], [[0, 1], [1, 1]]), datatype=['xarray'], bounds=bounds, vdims='Count') self.assertEqual(imgs[0], expected) self.assertEqual(imgs[1], expected2)
def test_dynamic_compute_overlayable_zorders_mixed_dynamic_and_dynamic_ndoverlay_with_streams_cloned(self): ndoverlay = DynamicMap(lambda x: NdOverlay({i: Area(range(10+i)) for i in range(2)}), kdims=[], streams=[PointerX()]) curve = DynamicMap(lambda: Curve(range(10)), kdims=[]) curve_redim = curve.redim(x='x2') combined = ndoverlay*curve_redim combined[()] sources = compute_overlayable_zorders(combined.clone()) self.assertIn(ndoverlay, sources[0]) self.assertNotIn(curve_redim, sources[0]) self.assertNotIn(curve, sources[0]) self.assertIn(ndoverlay, sources[1]) self.assertNotIn(curve_redim, sources[1]) self.assertNotIn(curve, sources[1]) self.assertIn(curve_redim, sources[2]) self.assertIn(curve, sources[2]) self.assertNotIn(ndoverlay, sources[2])
def test_dynamic_compute_overlayable_zorders_mixed_dynamic_and_non_dynamic_ndoverlays_reverse(self): ndoverlay = NdOverlay({i: Area(range(10+i)) for i in range(2)}) curve = DynamicMap(lambda: Curve(range(10)), kdims=[]) curve_redim = curve.redim(x='x2') combined = curve_redim*ndoverlay combined[()] sources = compute_overlayable_zorders(combined) self.assertIn(curve_redim, sources[0]) self.assertIn(curve, sources[0]) self.assertNotIn(ndoverlay, sources[0]) self.assertIn(ndoverlay[0], sources[1]) self.assertIn(ndoverlay, sources[1]) self.assertNotIn(curve_redim, sources[1]) self.assertNotIn(curve, sources[1]) self.assertIn(ndoverlay[1], sources[2]) self.assertIn(ndoverlay, sources[2]) self.assertNotIn(curve_redim, sources[2]) self.assertNotIn(curve, sources[2])
def test_batched_plot(self): overlay = NdOverlay({i: Points(np.arange(i)) for i in range(1, 100)}) plot = bokeh_renderer.get_plot(overlay) extents = plot.get_extents(overlay, {}) self.assertEqual(extents, (0, 0, 98, 98))
def test_overlay(self): NdOverlay(list(enumerate([self.view1, self.view2, self.view3])))
def test_stack_area_ndoverlay(self): areas = NdOverlay([(0, Area([1, 2, 3])), (1, Area([1, 2, 3]))]) stacked = Area.stack(areas) area1 = Area(([0, 1, 2], [1, 2, 3], [0, 0, 0]), vdims=['y', 'Baseline']) area2 = Area(([0, 1, 2], [2, 4, 6], [1, 2, 3]), vdims=['y', 'Baseline']) self.assertEqual(stacked, NdOverlay([(0, area1), (1, area2)]))
def test_area_stacked(self): plot = self.df.hvplot.area(stacked=True) obj = NdOverlay({'x': Area(self.df, 'index', 'x').redim(x='value'), 'y': Area(self.df, 'index', 'y').redim(y='value')}, 'Variable') self.assertEqual(plot, Area.stack(obj))
def test_wide_chart(self, kind, element): plot = self.df.hvplot(kind=kind) obj = NdOverlay({'x': element(self.df, 'index', 'x').redim(x='value'), 'y': element(self.df, 'index', 'y').redim(y='value')}, 'Variable') self.assertEqual(plot, obj)
view = paired.loc[start:end] break else: raise TypeError(f"Invalid type: {type(length).__name__}") curves = { key: Curve( (view.index, col), kdims=[Dimension(f"x_{i}", label=view.index.name)], vdims=[Dimension(f"y_{i}", label="y")], **({} if label is None else { "label": label }), ) for key, col in view.items() } plot = NdOverlay(curves).opts(show_grid=True) plots.append(plot) if isinstance(net, NeuralNet): epoch = net.history[-1]["epoch"] try: dirname = one(x for x in net.callbacks if isinstance(x, Checkpoint)).dirname except ValueError: label = f"Epoch {epoch}" else: label = f"Epoch {epoch} ({dirname})" label_kwargs = {"label": label} else: label_kwargs = {} return Layout(plots, **label_kwargs)
def test_overlay_iter(self): views = [self.view1, self.view2, self.view3] overlay = NdOverlay(list(enumerate(views))) for el, v in zip(overlay, views): self.assertEqual(el, v)
def test_only_includes_num_chart(self, kind, element): plot = self.cat_df.hvplot(kind=kind) obj = NdOverlay({'x': element(self.cat_df, 'index', 'x').redim(x='value'), 'y': element(self.cat_df, 'index', 'y').redim(y='value'), }, 'Variable') self.assertEqual(plot, obj)