I am following the example from Vectorfield — hvPlot 0.9.0 documentation
But I changed the shape to match the size of my current dataset.
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
def sample_data(shape=(904, 999)):
"""
Return ``(x, y, u, v, crs)`` of some vector data
computed mathematically. The returned crs will be a rotated
pole CRS, meaning that the vectors will be unevenly spaced in
regular PlateCarree space.
"""
crs = ccrs.UTM(10)
x = np.linspace(311.9, 391.1, shape[1])
y = np.linspace(-23.6, 24.8, shape[0])
x2d, y2d = np.meshgrid(x, y)
u = 10 * (2 * np.cos(2 * np.deg2rad(x2d) + 3 * np.deg2rad(y2d + 30)) ** 2)
v = 20 * np.cos(6 * np.deg2rad(x2d))
return x, y, u, v, crs
xs, ys, U, V, crs = sample_data()
mag = np.sqrt(U**2 + V**2)
angle = (np.pi/2.) - np.arctan2(U/mag, V/mag)
ds = xr.Dataset({'mag': xr.DataArray(mag, dims=('y', 'x'), coords={'y': ys, 'x': xs}),
'angle': xr.DataArray(angle, dims=('y', 'x'), coords={'y': ys, 'x': xs})},
attrs={'crs': crs, 'crs_wkt': doppscat.attrs["crs_wkt"]})
ds
Then the following code returns memory error with a number of points greater than the data points.
ds.hvplot.vectorfield(x='x', y='y', angle='angle', mag='mag', hover=False).opts(magnitude='mag')
I suspect that this is because of the projection. I tried to use Dask by chunking the data, but it doesn’t seem to be integrated with Dask.
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/util.py:1075, in get_min_distance(element)
1074 from scipy.spatial.distance import pdist
-> 1075 return pdist(element.array([0, 1])).min()
1076 except Exception:
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/scipy/spatial/distance.py:2233, in pdist(X, metric, out, **kwargs)
2232 pdist_fn = metric_info.pdist_func
-> 2233 return pdist_fn(X, out=out, **kwargs)
2234 elif mstr.startswith("test_"):
MemoryError: Unable to allocate 2.97 TiB for an array with shape (407790741060,) and data type float64
During handling of the above exception, another exception occurred:
MemoryError Traceback (most recent call last)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/IPython/core/formatters.py:972, in MimeBundleFormatter.__call__(self, obj, include, exclude)
969 method = get_real_method(obj, self.print_method)
971 if method is not None:
--> 972 return method(include=include, exclude=exclude)
973 return None
974 else:
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/core/dimension.py:1286, in Dimensioned._repr_mimebundle_(self, include, exclude)
1279 def _repr_mimebundle_(self, include=None, exclude=None):
1280 """
1281 Resolves the class hierarchy for the class rendering the
1282 object using any display hooks registered on Store.display
1283 hooks. The output of all registered display_hooks is then
1284 combined and returned.
1285 """
-> 1286 return Store.render(self)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/core/options.py:1428, in Store.render(cls, obj)
1426 data, metadata = {}, {}
1427 for hook in hooks:
-> 1428 ret = hook(obj)
1429 if ret is None:
1430 continue
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py:287, in pprint_display(obj)
285 if not ip.display_formatter.formatters['text/plain'].pprint:
286 return None
--> 287 return display(obj, raw_output=True)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py:255, in display(obj, raw_output, **kwargs)
253 elif isinstance(obj, (CompositeOverlay, ViewableElement)):
254 with option_state(obj):
--> 255 output = element_display(obj)
256 elif isinstance(obj, (Layout, NdLayout, AdjointLayout)):
257 with option_state(obj):
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py:149, in display_hook.<locals>.wrapped(element)
147 try:
148 max_frames = OutputSettings.options['max_frames']
--> 149 mimebundle = fn(element, max_frames=max_frames)
150 if mimebundle is None:
151 return {}, {}
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py:195, in element_display(element, max_frames)
192 if type(element) not in Store.registry[backend]:
193 return None
--> 195 return render(element)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/ipython/display_hooks.py:76, in render(obj, **kwargs)
73 if renderer.fig == 'pdf':
74 renderer = renderer.instance(fig='png')
---> 76 return renderer.components(obj, **kwargs)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/renderer.py:396, in Renderer.components(self, obj, fmt, comm, **kwargs)
393 embed = (not (dynamic or streams or self.widget_mode == 'live') or config.embed)
395 if embed or config.comms == 'default':
--> 396 return self._render_panel(plot, embed, comm)
397 return self._render_ipywidget(plot)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/renderer.py:403, in Renderer._render_panel(self, plot, embed, comm)
401 doc = Document()
402 with config.set(embed=embed):
--> 403 model = plot.layout._render_model(doc, comm)
404 if embed:
405 return render_model(model, comm)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/viewable.py:737, in Viewable._render_model(self, doc, comm)
735 if comm is None:
736 comm = state._comm_manager.get_server_comm()
--> 737 model = self.get_root(doc, comm)
739 if self._design and self._design.theme.bokeh_theme:
740 doc.theme = self._design.theme.bokeh_theme
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/layout/base.py:306, in Panel.get_root(self, doc, comm, preprocess)
302 def get_root(
303 self, doc: Optional[Document] = None, comm: Optional[Comm] = None,
304 preprocess: bool = True
305 ) -> Model:
--> 306 root = super().get_root(doc, comm, preprocess)
307 # ALERT: Find a better way to handle this
308 if hasattr(root, 'styles') and 'overflow-x' in root.styles:
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/viewable.py:659, in Renderable.get_root(self, doc, comm, preprocess)
657 wrapper = self._design._wrapper(self)
658 if wrapper is self:
--> 659 root = self._get_model(doc, comm=comm)
660 if preprocess:
661 self._preprocess(root)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/layout/base.py:174, in Panel._get_model(self, doc, root, parent, comm)
172 root = root or model
173 self._models[root.ref['id']] = (model, parent)
--> 174 objects, _ = self._get_objects(model, [], doc, root, comm)
175 props = self._get_properties(doc)
176 props[self._property_mapping['objects']] = objects
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/layout/base.py:156, in Panel._get_objects(self, model, old_objects, doc, root, comm)
154 else:
155 try:
--> 156 child = pane._get_model(doc, root, model, comm)
157 except RerenderError as e:
158 if e.layout is not None and e.layout is not self:
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/pane/holoviews.py:411, in HoloViews._get_model(self, doc, root, parent, comm)
409 plot = self.object
410 else:
--> 411 plot = self._render(doc, comm, root)
413 plot.pane = self
414 backend = plot.renderer.backend
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/panel/pane/holoviews.py:506, in HoloViews._render(self, doc, comm, root)
503 if comm:
504 kwargs['comm'] = comm
--> 506 return renderer.get_plot(self.object, **kwargs)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/bokeh/renderer.py:68, in BokehRenderer.get_plot(self_or_cls, obj, doc, renderer, **kwargs)
61 @bothmethod
62 def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs):
63 """
64 Given a HoloViews Viewable return a corresponding plot instance.
65 Allows supplying a document attach the plot to, useful when
66 combining the bokeh model with another plot.
67 """
---> 68 plot = super().get_plot(obj, doc, renderer, **kwargs)
69 if plot.document is None:
70 plot.document = Document() if self_or_cls.notebook_context else curdoc()
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/renderer.py:240, in Renderer.get_plot(self_or_cls, obj, doc, renderer, comm, **kwargs)
237 defaults = [kd.default for kd in plot.dimensions]
238 init_key = tuple(v if d is None else d for v, d in
239 zip(plot.keys[0], defaults))
--> 240 plot.update(init_key)
241 else:
242 plot = obj
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/plot.py:955, in DimensionedPlot.update(self, key)
953 def update(self, key):
954 if len(self) == 1 and key in (0, self.keys[0]) and not self.drawn:
--> 955 return self.initialize_plot()
956 item = self.__getitem__(key)
957 self.traverse(lambda x: setattr(x, '_updated', True))
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/bokeh/element.py:1885, in ElementPlot.initialize_plot(self, ranges, plot, plots, source)
1883 if self.autorange:
1884 self._setup_autorange()
-> 1885 self._init_glyphs(plot, element, ranges, source)
1886 if not self.overlaid:
1887 self._update_plot(key, plot, style_element)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/bokeh/element.py:1804, in ElementPlot._init_glyphs(self, plot, element, ranges, source)
1802 else:
1803 style = self.style[self.cyclic_index]
-> 1804 data, mapping, style = self.get_data(element, ranges, style)
1805 current_id = element._plot_id
1807 with abbreviated_exception():
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/bokeh/chart.py:281, in VectorFieldPlot.get_data(self, element, ranges, style)
279 else:
280 xidx, yidx = (0, 1)
--> 281 lens = self._get_lengths(element, ranges)/input_scale
282 cdim = element.get_dimension(self.color_index)
283 cdata, cmapping = self._get_color_data(element, ranges, style,
284 name='line_color')
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/bokeh/chart.py:256, in VectorFieldPlot._get_lengths(self, element, ranges)
254 magnitudes = magnitudes / max_magnitude
255 if self.rescale_lengths:
--> 256 base_dist = get_min_distance(element)
257 magnitudes = magnitudes * base_dist
258 else:
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/util.py:1077, in get_min_distance(element)
1075 return pdist(element.array([0, 1])).min()
1076 except Exception:
-> 1077 return _get_min_distance_numpy(element)
File ~/miniforge3/envs/coringa/lib/python3.9/site-packages/holoviews/plotting/util.py:1060, in _get_min_distance_numpy(element)
1058 warnings.filterwarnings('ignore', r'invalid value encountered in')
1059 xys = xys.astype('float32').view(np.complex64)
-> 1060 distances = np.abs(xys.T-xys)
1061 np.fill_diagonal(distances, np.inf)
1062 distances = distances[distances>0]
MemoryError: Unable to allocate 5.93 TiB for an array with shape (903096, 903096) and data type complex64
UPDATE:
I just checked and even without a crs it gives the error.
Why do we have to calculate the distance between all points?