def test_mpl_bokeh_offset_mpl(self): img = Image(np.random.rand(10,10)) # Use blue in matplotlib Store.current_backend = 'matplotlib' StoreOptions.set_options(img, style={'Image':{'cmap':'Blues'}}) mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap':'Blues'}) # Switch to bokeh and style a random object... Store.current_backend = 'bokeh' img2 = Image(np.random.rand(10,10)) StoreOptions.set_options(img2, style={'Image':{'cmap':'Reds'}}) img2_opts = Store.lookup_options('bokeh', img2, 'style').options self.assertEqual(img2_opts, {'cmap':'Reds'}) # Use purple in bokeh on the object... StoreOptions.set_options(img, style={'Image':{'cmap':'Purple'}}) bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap':'Purple'}) # Check it is still blue in matplotlib... Store.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap':'Blues'}) # And purple in bokeh.. Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap':'Purple'}) return img
def test_custom_magic_to_default_inheritance(self): """ Checks customs inheritance backs off to default tree correctly simulating the %%opts cell magic. """ if 'matplotlib' not in Store.renderers: raise SkipTest("Custom magic inheritance test requires matplotlib") options = self.initialize_option_tree() options.Image.A.B = Options('style', alpha=0.2) obj = Image(np.random.rand(10, 10), group='A', label='B') # Before customizing... expected_obj = {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'} obj_lookup = Store.lookup_options('matplotlib', obj, 'style') self.assertEqual(obj_lookup.kwargs, expected_obj) custom_tree = {0: OptionTree(groups=['plot', 'style', 'norm'], style={'Image' : dict(clims=(0, 0.5))})} Store._custom_options['matplotlib'] = custom_tree obj.id = 0 # Manually set the id to point to the tree above # Customize this particular object expected_custom_obj = dict(clims=(0,0.5), **expected_obj) custom_obj_lookup = Store.lookup_options('matplotlib', obj, 'style') self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)
def test_style_transfer(self): hist = self.hist.opts(style={'style1':'style_child'}) hist2 = self.hist.opts() opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs self.assertEqual(opts, {'style1': 'style1', 'style2': 'style2'}) Store.transfer_options(hist, hist2, 'matplotlib') opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs self.assertEqual(opts, {'style1': 'style_child', 'style2': 'style2'})
def setUp(self): if 'matplotlib' not in Store.renderers: raise SkipTest('Matplotlib backend not available.') self.store_copy = OptionTree(sorted(Store.options().items()), groups=Options._option_groups) self.backend = 'matplotlib' Store.set_current_backend(self.backend) super(TestOptsMethod, self).setUp()
def test_mpl_bokeh_mpl_via_dict_backend_keyword(self): curve = Curve([1,2,3]) styled_mpl = curve.opts({'Curve': dict(color='red')}, backend='matplotlib') styled = styled_mpl.opts({'Curve': dict(color='green')}, backend='bokeh') mpl_lookup = Store.lookup_options('matplotlib', styled, 'style') self.assertEqual(mpl_lookup.kwargs['color'], 'red') bokeh_lookup = Store.lookup_options('bokeh', styled, 'style') self.assertEqual(bokeh_lookup.kwargs['color'], 'green')
def test_style_inheritance_addition(self): "Adding an element" hist2 = self.hist(style={"style3": "style3"}) self.assertEqual( Store.lookup_options(hist2, "style").options, dict(style1="style1", style2="style2", style3="style3") ) # Check plot options works as expected self.assertEqual(Store.lookup_options(hist2, "plot").options, self.default_plot)
def tearDown(self): Store.options(val=self.store_mpl, backend='matplotlib') Store.options(val=self.store_bokeh, backend='bokeh') Store.current_backend = 'matplotlib' Store._custom_options = {k:{} for k in Store._custom_options.keys()} if self.plotly_options is not None: Store._options['plotly'] = self.plotly_options super(TestCrossBackendOptionSpecification, self).tearDown()
def setUp(self): if 'bokeh' not in Store.renderers: raise SkipTest("Cross background tests assumes bokeh is available.") self.store_mpl = OptionTree(sorted(Store.options(backend='matplotlib').items()), groups=['style', 'plot', 'norm']) self.store_bokeh = OptionTree(sorted(Store.options(backend='bokeh').items()), groups=['style', 'plot', 'norm']) self.clear_options() super(TestCrossBackendOptions, self).setUp()
def test_style_transfer(self): if 'matplotlib' not in Store.renderers: raise SkipTest("test_style_transfer requires matplotlib") hist = self.hist.opts(style={'style1':'style_child'}) hist2 = self.hist.opts() opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs self.assertEqual(opts, {'style1': 'style1', 'style2': 'style2'}) Store.transfer_options(hist, hist2, 'matplotlib') opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs self.assertEqual(opts, {'style1': 'style_child', 'style2': 'style2'})
def test_mpl_bokeh_mpl_via_builders_opts_method(self): img = Image(np.random.rand(10,10)) mpl_opts = opts.Image(cmap='Blues', backend='matplotlib') bokeh_opts = opts.Image(cmap='Purple', backend='bokeh') self.assertEqual(mpl_opts.kwargs['backend'], 'matplotlib') self.assertEqual(bokeh_opts.kwargs['backend'], 'bokeh') img.opts(mpl_opts, bokeh_opts) mpl_lookup = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_lookup['cmap'], 'Blues') bokeh_lookup = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_lookup['cmap'], 'Purple') self.assert_output_options_group_empty(img)
def setUp(self): if 'matplotlib' not in Store.renderers: raise SkipTest("Cross background tests assumes matplotlib is available") if 'bokeh' not in Store.renderers: raise SkipTest("Cross background tests assumes bokeh is available.") # Some tests require that plotly isn't loaded self.plotly_options = Store._options.pop('plotly', None) self.store_mpl = OptionTree(sorted(Store.options(backend='matplotlib').items()), groups=Options._option_groups) self.store_bokeh = OptionTree(sorted(Store.options(backend='bokeh').items()), groups=Options._option_groups) super(TestCrossBackendOptionSpecification, self).setUp()
def test_builder_cross_backend_validation(self): Store.options(val=self.store_mpl, backend='matplotlib') Store.options(val=self.store_bokeh, backend='bokeh') Store.set_current_backend('bokeh') opts.Curve(line_dash='dotted') # Bokeh keyword opts.Curve(linewidth=10) # MPL keyword err = ("In opts.Curve\(...\), keywords supplied are mixed across backends. " "Keyword\(s\) 'linewidth' are invalid for bokeh, " "'line_dash' are invalid for matplotlib") with self.assertRaisesRegexp(ValueError, err): opts.Curve(linewidth=10, line_dash='dotted') # Bokeh and MPL # Non-existent keyword across backends (bokeh active) err = ("In opts.Curve\(...\), unexpected option 'foobar' for Curve type " "across all extensions. Similar options for current " "extension \('bokeh'\) are: \['toolbar'\].") with self.assertRaisesRegexp(ValueError, err): opts.Curve(foobar=3) # Non-existent keyword across backends (matplotlib active) Store.set_current_backend('matplotlib') err = ("In opts.Curve\(...\), unexpected option 'foobar' for Curve " "type across all extensions. No similar options found.") with self.assertRaisesRegexp(ValueError, err): opts.Curve(foobar=3)
def clear_options(self): # Clear global options.. Store.options(val=OptionTree(groups=['plot', 'style']), backend='matplotlib') Store.options(val=OptionTree(groups=['plot', 'style']), backend='bokeh') # ... and custom options Store.custom_options({}, backend='matplotlib') Store.custom_options({}, backend='bokeh')
def test_holoviews_defined_default_opts_logx_overwritten_in_call(self): hv.opts.defaults(hv.opts.Scatter(logx=True)) plot = self.df.hvplot.scatter('x', 'y', c='category', logx=False) opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['logx'], False) self.assertEqual(opts.kwargs['logy'], False) self.assertEqual(opts.kwargs.get('logz'), None)
def test_bivariate_opts(self): plot = self.df.hvplot.bivariate('x', 'y', bandwidth=0.2, cut=1, levels=5, filled=True) opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['bandwidth'], 0.2) self.assertEqual(opts.kwargs['cut'], 1) self.assertEqual(opts.kwargs['levels'], 5) self.assertEqual(opts.kwargs['filled'], True)
def test_wide_chart_legend_position(self, kind, element): plot = self.df.hvplot(kind=kind, value_label='Test', group_label='Category', legend='left') opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['legend_position'], 'left')
def test_scatter_color_by_legend_position(self): plot = self.cat_df.hvplot.scatter('x', 'y', c='category', legend='left') opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['legend_position'], 'left')
def test_specification_general_to_specific_group_and_label(self): """ Test order of specification starting with general and moving to specific """ if 'matplotlib' not in Store.renderers: raise SkipTest("General to specific option test requires matplotlib") options = self.initialize_option_tree() obj = Image(np.random.rand(10,10), group='SomeGroup', label='SomeLabel') options.Image = Options('style', cmap='viridis') options.Image.SomeGroup.SomeLabel = Options('style', alpha=0.2) expected = {'alpha': 0.2, 'cmap': 'viridis', 'interpolation': 'nearest'} lookup = Store.lookup_options('matplotlib', obj, 'style') self.assertEqual(lookup.kwargs, expected) # Check the tree is structured as expected node1 = options.Image.groups['style'] node2 = options.Image.SomeGroup.SomeLabel.groups['style'] self.assertEqual(node1.kwargs, {'cmap': 'viridis', 'interpolation': 'nearest'}) self.assertEqual(node2.kwargs, {'alpha': 0.2})
def test_aspect_and_frame_height_with_datashade(self, opt): plot = self.df.hvplot(x='x', y='y', frame_height=150, datashade=True, **{opt: 2}) opts = Store.lookup_options('bokeh', plot[()], 'plot').kwargs self.assertEqual(opts[opt], 2) self.assertEqual(opts.get('frame_height'), 150) self.assertEqual(opts.get('height'), None) self.assertEqual(opts.get('frame_width'), None)
def test_holoviews_defined_default_opts_overwritten_in_call(self): hv.opts.defaults(hv.opts.Scatter(height=400, width=900, show_grid=True)) plot = self.df.hvplot.scatter('x', 'y', c='category', width=300, legend='left') opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['legend_position'], 'left') self.assertEqual(opts.kwargs['show_grid'], True) self.assertEqual(opts.kwargs['height'], 400) self.assertEqual(opts.kwargs['width'], 300)
def test_rasterize_set_clim(self): plot = self.df.hvplot.scatter('x', 'y', dynamic=False, rasterize=True, clim=(1, 4)) opts = Store.lookup_options('bokeh', plot, 'plot').kwargs self.assertEqual(opts.get('clim'), (1, 4))
def test_rasterize_color_dim_with_new_column_gets_default_cmap(self): plot = self.df.hvplot.scatter('x', 'y', c='y', dynamic=False, rasterize=True) opts = Store.lookup_options('bokeh', plot, 'style').kwargs self.assertEqual(opts.get('cmap'), 'kbc_r')
def test_store_render_html(self): curve = Curve([1, 2, 3]) data, metadata = Store.render(curve) mime_types = { 'text/html', 'application/javascript', 'application/vnd.holoviews_exec.v0+json' } self.assertEqual(set(data), mime_types)
def setUp(self): if 'matplotlib' not in Store.renderers: raise SkipTest('Matplotlib backend not available.') self.store_copy = OptionTree(sorted(Store.options().items()), groups=Options._option_groups) self.backend = 'matplotlib' Store.current_backend = self.backend super(TestStoreInheritanceDynamic, self).setUp()
def test_tidy_chart_index_by_legend_position(self, kind, element): plot = self.df.hvplot(x='index', y='y', by='x', kind=kind, legend='left') opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['legend_position'], 'left')
def init_notebook(mpl=True): # Enable inline plotting in the notebook if mpl: try: get_ipython().enable_matplotlib(gui='inline') except NameError: pass print('Populated the namespace with:\n' + ', '.join(init_mooc_nb) + '\nfrom code/edx_components:\n' + ', '.join(edx_components.__all__) + '\nfrom code/functions:\n' + ', '.join(functions.__all__)) holoviews.notebook_extension('matplotlib') Store.renderers['matplotlib'].fig = 'svg' holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True latex_packs = [r'\usepackage{amsmath}', r'\usepackage{amssymb}' r'\usepackage{bm}'] holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = latex_packs # Set plot style. options = Store.options(backend='matplotlib') options.Contours = Options('style', linewidth=2, color='k') options.Contours = Options('plot', aspect='square') options.HLine = Options('style', linestyle='--', color='b', linewidth=2) options.VLine = Options('style', linestyle='--', color='r', linewidth=2) options.Image = Options('style', cmap='RdBu_r') options.Image = Options('plot', title_format='{label}') options.Path = Options('style', linewidth=1.2, color='k') options.Path = Options('plot', aspect='square', title_format='{label}') options.Curve = Options('style', linewidth=2, color='k') options.Curve = Options('plot', aspect='square', title_format='{label}') options.Overlay = Options('plot', show_legend=False, title_format='{label}') options.Layout = Options('plot', title_format='{label}') options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2) options.Surface = Options('plot', azimuth=20, elevation=8) # Turn off a bogus holoviews warning. # Temporary solution to ignore the warnings warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered') module_dir = os.path.dirname(__file__) matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc")) np.set_printoptions(precision=2, suppress=True, formatter={'complexfloat': pretty_fmt_complex}) # Patch a bug in holoviews if holoviews.__version__.release <= (1, 4, 3): from patch_holoviews import patch_all patch_all()
def test_axis_set_to_false(self): plot = self.df.hvplot.scatter('x', 'y', c='category', xaxis=False, yaxis=False) opts = Store.lookup_options('bokeh', plot, 'plot') self.assertEqual(opts.kwargs['xaxis'], None) self.assertEqual(opts.kwargs['yaxis'], None)
def test_cell_opts_util_style(self): mat1 = hv.Image(np.random.rand(5, 5), name='mat1') self.assertEqual(mat1.id, None) opts("Image (cmap='hot')", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'style').options.get('cmap', None), 'hot')
def test_cell_opts_util_norm(self): mat1 = hv.Image(np.random.rand(5, 5), name='mat1') self.assertEqual(mat1.id, None) opts("Image {+axiswise}", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'norm').options.get('axiswise', True), True)
def setUp(self): if 'matplotlib' not in Store.renderers: raise SkipTest( "Cross background tests assumes matplotlib is available") if 'bokeh' not in Store.renderers: raise SkipTest( "Cross background tests assumes bokeh is available.") # Some tests require that plotly isn't loaded self.plotly_options = Store._options.pop('plotly', None) self.store_mpl = OptionTree(sorted( Store.options(backend='matplotlib').items()), groups=Options._option_groups) self.store_bokeh = OptionTree(sorted( Store.options(backend='bokeh').items()), groups=Options._option_groups) self.clear_options() super(TestCrossBackendOptions, self).setUp()
def test_scatter_size_set_to_series(self): if is_dask(self.df['y']): y = self.df['y'].compute() else: y = self.df['y'] plot = self.df.hvplot.scatter('x', 'y', s=y) opts = Store.lookup_options('bokeh', plot, 'style') assert '_size' in plot.data.columns self.assertEqual(opts.kwargs['size'], '_size')
def test_alpha_dim_overlay(self, kind): plot = self.df.hvplot('x', 'y', alpha='number', by='category', kind=kind) opts = Store.lookup_options('bokeh', plot.last, 'style') self.assertEqual(opts.kwargs['alpha'], 'number') self.assertIn('number', plot.last.vdims)
def test_custom_opts_to_default_inheritance(self): """ Checks customs inheritance backs off to default tree correctly using .opts. """ options = self.initialize_option_tree() options.Image.A.B = Options('style', alpha=0.2) obj = Image(np.random.rand(10, 10), group='A', label='B') expected_obj = {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'} obj_lookup = Store.lookup_options('matplotlib', obj, 'style') self.assertEqual(obj_lookup.kwargs, expected_obj) # Customize this particular object custom_obj = obj.opts(style=dict(clims=(0, 0.5))) expected_custom_obj = dict(clims=(0,0.5), **expected_obj) custom_obj_lookup = Store.lookup_options('matplotlib', custom_obj, 'style') self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)
def test_tidy_chart_ranges(self, kind, element): plot = self.df.hvplot(x='x', y='y', kind=kind, xlim=(0, 3), ylim=(5, 10)) opts = Store.lookup_options('bokeh', plot, 'plot').options self.assertEqual(opts['xlim'], (0, 3)) self.assertEqual(opts['ylim'], (5, 10))
def test_cell_opts_util_norm(self): mat1 = hv.Image(np.random.rand(5,5), name='mat1') self.assertEqual(mat1.id, None) opts("Image {+axiswise}", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'norm').options.get('axiswise',True), True)
def test_cell_opts_util_style(self): mat1 = hv.Image(np.random.rand(5,5), name='mat1') self.assertEqual(mat1.id, None) opts("Image (cmap='hot')", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'style').options.get('cmap',None),'hot')
def test_custom_call_to_default_inheritance(self): """ Checks customs inheritance backs off to default tree correctly using __call__. """ options = self.initialize_option_tree() options.Image.A.B = Options('style', alpha=0.2) obj = Image(np.random.rand(10, 10), group='A', label='B') expected_obj = {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'} obj_lookup = Store.lookup_options('matplotlib', obj, 'style') self.assertEqual(obj_lookup.kwargs, expected_obj) # Customize this particular object custom_obj = obj(style=dict(clims=(0, 0.5))) expected_custom_obj = dict(clims=(0,0.5), **expected_obj) custom_obj_lookup = Store.lookup_options('matplotlib', custom_obj, 'style') self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)
def setUp(self): self.store_copy = OptionTree(sorted(Store.options().items()), groups=['style', 'plot', 'norm']) self.backend = 'matplotlib' Store.current_backend = self.backend Store.options(val=OptionTree(groups=['plot', 'style'])) options = Store.options() self.default_plot = dict(plot1='plot1', plot2='plot2') options.Histogram = Options('plot', **self.default_plot) self.default_style = dict(style1='style1', style2='style2') options.Histogram = Options('style', **self.default_style) data = [np.random.normal() for i in range(10000)] frequencies, edges = np.histogram(data, 20) self.hist = Histogram(frequencies, edges) super(TestStoreInheritance, self).setUp()
def test_cell_opts_util_plot(self): mat1 = hv.Image(np.random.rand(5,5), name='mat1') self.assertEqual(mat1.id, None) opts("Image [show_title=False]", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'plot').options.get('show_title',True),False)
def test_aspect_with_datashade_and_dynamic_is_false(self, opt): plot = self.df.hvplot(x='x', y='y', datashade=True, dynamic=False, **{opt: 2}) opts = Store.lookup_options('bokeh', plot[()], 'plot').kwargs self.assertEqual(opts[opt], 2) self.assertEqual(opts.get('height'), None) self.assertEqual(opts.get('frame_height'), None)
def setUp(self): options = OptionTree(groups=['group']) self.opts1 = Options('group', kw1='value1') self.opts2 = Options('group', kw2='value2') self.opts3 = Options('group', kw3='value3') self.opts4 = Options('group', kw4='value4') self.opts5 = Options('group', kw5='value5') self.opts6 = Options('group', kw6='value6') options.MyType = self.opts1 options.XType = self.opts2 options.MyType.Foo = self.opts3 options.MyType.Bar = self.opts4 options.XType.Foo = self.opts5 options.XType.Bar = self.opts6 self.options = options self.original_options = Store.options() Store.options(val = OptionTree(groups=['group']))
def test_pickle_mpl_bokeh(self): """ Test pickle saving and loading with Store (style information preserved) """ fname = 'test_pickle_mpl_bokeh.pkl' raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl() Store.dump(raw, open(fname, 'wb')) self.clear_options() img = Store.load(open(fname, 'rb')) # Data should match self.assertEqual(raw, img) # Check it is still blue in matplotlib... Store.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap': 'Blues'}) # And purple in bokeh.. Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap': 'Purple'})
def setUp(self): options = OptionTree(groups=['group']) self.opts1 = Options('group', kw1='value1') self.opts2 = Options('group', kw2='value2') self.opts3 = Options('group', kw3='value3') self.opts4 = Options('group', kw4='value4') self.opts5 = Options('group', kw5='value5') self.opts6 = Options('group', kw6='value6') options.MyType = self.opts1 options.XType = self.opts2 options.MyType.Foo = self.opts3 options.MyType.Bar = self.opts4 options.XType.Foo = self.opts5 options.XType.Bar = self.opts6 self.options = options self.original_options = Store.options() Store.options(val=OptionTree(groups=['group']))
def test_raw_pickle(self): """ Test usual pickle saving and loading (no style information preserved) """ fname = 'test_raw_pickle.pkl' raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl() pickle.dump(raw, open(fname, 'wb')) self.clear_options() img = pickle.load(open(fname, 'rb')) # Data should match self.assertEqual(raw, img) # But the styles will be lost without using Store.load/Store.dump pickle.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {}) # ... across all backends Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {})
def test_pickle_mpl_bokeh(self): """ Test pickle saving and loading with Store (style information preserved) """ fname = 'test_pickle_mpl_bokeh.pkl' raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl() Store.dump(raw, open(fname,'wb')) self.clear_options() img = Store.load(open(fname,'rb')) # Data should match self.assertEqual(raw, img) # Check it is still blue in matplotlib... Store.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap':'Blues'}) # And purple in bokeh.. Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap':'Purple'})
def test_raw_pickle(self): """ Test usual pickle saving and loading (no style information preserved) """ fname= 'test_raw_pickle.pkl' raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl() pickle.dump(raw, open(fname,'wb')) self.clear_options() img = pickle.load(open(fname,'rb')) # Data should match self.assertEqual(raw, img) # But the styles will be lost without using Store.load/Store.dump pickle.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {}) # ... across all backends Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {})
def init_notebook(): # Enable inline plotting in the notebook try: get_ipython().enable_matplotlib(gui='inline') except NameError: pass print('Populated the namespace with:\n' + ', '.join(__all__)) holoviews.notebook_extension('matplotlib') holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True # Set plot style. options = Store.options(backend='matplotlib') options.Contours = Options('style', linewidth=2, color='k') options.Contours = Options('plot', aspect='square') options.HLine = Options('style', linestyle='--', color='b', linewidth=2) options.VLine = Options('style', linestyle='--', color='r', linewidth=2) options.Image = Options('style', cmap='RdBu_r') options.Image = Options('plot', title_format='{label}') options.Path = Options('style', linewidth=1.2, color='k') options.Path = Options('plot', aspect='square', title_format='{label}') options.Curve = Options('style', linewidth=2, color='k') options.Curve = Options('plot', aspect='square', title_format='{label}') options.Overlay = Options('plot', show_legend=False, title_format='{label}') options.Layout = Options('plot', title_format='{label}') options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2) options.Surface = Options('plot', azimuth=20, elevation=8) # Turn off a bogus holoviews warning. # Temporary solution to ignore the warnings warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered') module_dir = os.path.dirname(__file__) matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc")) np.set_printoptions(precision=2, suppress=True, formatter={'complexfloat': pretty_fmt_complex}) # In order to make the notebooks readable through nbviewer we want to hide # the code by default. However the same code is executed by the students, # and in that case we don't want to hide the code. So we check if the code # is executed by one of the mooc developers. Here we do by simply checking # for some files that belong to the internal mooc repository, but are not # published. This is a temporary solution, and should be improved in the # long run. developer = os.path.exists(os.path.join(module_dir, os.path.pardir, 'scripts')) display_html(display.HTML(nb_html_header + (hide_outside_ipython if developer else ''))) # Patch a bug in holoviews from patch_holoviews import patch_all patch_all()
def test_axis_set_to_none_in_holoviews_opts_default_overwrite_in_call( self): hv.opts.defaults(hv.opts.Scatter(xaxis=None, yaxis=None)) plot = self.df.hvplot.scatter('x', 'y', c='category', xaxis=True, yaxis=True) opts = Store.lookup_options('bokeh', plot, 'plot') assert 'xaxis' not in opts.kwargs assert 'yaxis' not in opts.kwargs
def test_cell_opts_util_style(self): mat1 = hv.Image(np.random.rand(5, 5), name='mat1') self.assertEqual(mat1.id, None) opts("Image (cmap='hot')", mat1) self.assertNotEqual(mat1.id, None) self.assertEqual( Store.lookup_options('matplotlib', mat1, 'style').options.get('cmap', None), 'hot') self.log_handler.assertContains( 'WARNING', 'Double positional argument signature of opts is deprecated')
def test_mpl_bokeh_mpl(self): img = Image(np.random.rand(10, 10)) # Use blue in matplotlib Store.current_backend = 'matplotlib' StoreOptions.set_options(img, style={'Image': {'cmap': 'Blues'}}) mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap': 'Blues'}) # Use purple in bokeh Store.current_backend = 'bokeh' StoreOptions.set_options(img, style={'Image': {'cmap': 'Purple'}}) bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap': 'Purple'}) # Check it is still blue in matplotlib... Store.current_backend = 'matplotlib' mpl_opts = Store.lookup_options('matplotlib', img, 'style').options self.assertEqual(mpl_opts, {'cmap': 'Blues'}) # And purple in bokeh.. Store.current_backend = 'bokeh' bokeh_opts = Store.lookup_options('bokeh', img, 'style').options self.assertEqual(bokeh_opts, {'cmap': 'Purple'}) return img
def test_builder_backend_switch(self): Store.options(val=self.store_mpl, backend='matplotlib') Store.options(val=self.store_bokeh, backend='bokeh') Store.set_current_backend('bokeh') self.assertEqual(opts.Curve.__doc__.startswith('Curve('), True) docline = opts.Curve.__doc__.splitlines()[0] dockeys = eval(docline.replace('Curve', 'dict')) self.assertEqual('color' in dockeys, True) self.assertEqual('line_width' in dockeys, True) Store.set_current_backend('matplotlib') self.assertEqual(opts.Curve.__doc__.startswith('Curve('), True) docline = opts.Curve.__doc__.splitlines()[0] dockeys = eval(docline.replace('Curve', 'dict')) self.assertEqual('color' in dockeys, True) self.assertEqual('linewidth' in dockeys, True)
def init_notebook(): print_information() check_versions() code_dir = os.path.dirname(os.path.realpath(__file__)) hv_css = os.path.join(code_dir, 'hv_widgets_settings.css') holoviews.plotting.widgets.SelectionWidget.css = hv_css holoviews.notebook_extension('matplotlib') # Enable inline plotting in the notebook get_ipython().enable_matplotlib(gui='inline') Store.renderers['matplotlib'].fig = 'svg' Store.renderers['matplotlib'].dpi = 100 holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True latex_packs = [r'\usepackage{amsmath}', r'\usepackage{amssymb}' r'\usepackage{bm}'] holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \ latex_packs # Set plot style. options = Store.options(backend='matplotlib') options.Contours = Options('style', linewidth=2, color='k') options.Contours = Options('plot', aspect='square') options.HLine = Options('style', linestyle='--', color='b', linewidth=2) options.VLine = Options('style', linestyle='--', color='r', linewidth=2) options.Image = Options('style', cmap='RdBu_r') options.Image = Options('plot', title_format='{label}') options.Path = Options('style', linewidth=1.2, color='k') options.Path = Options('plot', aspect='square', title_format='{label}') options.Curve = Options('style', linewidth=2, color='k') options.Curve = Options('plot', aspect='square', title_format='{label}') options.Overlay = Options('plot', show_legend=False, title_format='{label}') options.Layout = Options('plot', title_format='{label}') options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2, lw=0.2, edgecolors='k') options.Surface = Options('plot', azimuth=20, elevation=8) # Set slider label formatting for dimension_type in [float, np.float64, np.float32]: holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc")) np.set_printoptions(precision=2, suppress=True, formatter={'complexfloat': pretty_fmt_complex})
def test_mpl_bokeh_output_options_group_expandable(self): original_allowed_kws = Options._output_allowed_kws[:] Options._output_allowed_kws = ['backend', 'file_format_example'] # Re-register Store.register({Curve: plotting.mpl.CurvePlot}, 'matplotlib') Store.register({Curve: plotting.bokeh.CurvePlot}, 'bokeh') curve_bk = Options('Curve', backend='bokeh', color='blue') curve_mpl = Options('Curve', backend='matplotlib', color='red', file_format_example='SVG') c = Curve([1,2,3]) styled = c.opts(curve_bk, curve_mpl) self.assertEqual(Store.lookup_options('matplotlib', styled, 'output').kwargs, {'backend':'matplotlib', 'file_format_example':'SVG'}) self.assertEqual(Store.lookup_options('bokeh', styled, 'output').kwargs, {}) Options._output_allowed_kws = original_allowed_kws
def test_mpl_bokeh_mpl_via_builders_opts_method_flat_literal_explicit_backend(self): img = Image(np.random.rand(10,10)) curve = Curve([1,2,3]) overlay = img * curve Store.set_current_backend('matplotlib') literal = {'Curve': dict(color='orange', backend='matplotlib'), 'Image': dict(cmap='jet', backend='bokeh') } styled = overlay.opts(literal) mpl_curve_lookup = Store.lookup_options('matplotlib', styled.Curve.I, 'style') self.assertEqual(mpl_curve_lookup.kwargs['color'], 'orange') mpl_img_lookup = Store.lookup_options('matplotlib', styled.Image.I, 'style') self.assertNotEqual(mpl_img_lookup.kwargs['cmap'], 'jet') bokeh_curve_lookup = Store.lookup_options('bokeh', styled.Curve.I, 'style') self.assertNotEqual(bokeh_curve_lookup.kwargs['color'], 'orange') bokeh_img_lookup = Store.lookup_options('bokeh', styled.Image.I, 'style') self.assertEqual(bokeh_img_lookup.kwargs['cmap'], 'jet')
def test_style_inheritance_override(self): "Overriding an element" hist2 = self.hist(style={"style1": "style_child"}) self.assertEqual(Store.lookup_options(hist2, "style").options, dict(style1="style_child", style2="style2")) # Check plot options works as expected self.assertEqual(Store.lookup_options(hist2, "plot").options, self.default_plot)