Example #1
0
File: geo.py Project: ioam/geoviews
 def trimesh(self):
     trimesh = super(QuadMesh, self).trimesh()
     node_params = util.get_param_values(trimesh.nodes)
     node_params['crs'] = self.crs
     nodes = TriMesh.node_type(trimesh.nodes.data, **node_params)
     return TriMesh((trimesh.data, nodes), crs=self.crs,
                    **util.get_param_values(trimesh))
Example #2
0
 def trimesh(self):
     trimesh = super(QuadMesh, self).trimesh()
     node_params = get_param_values(trimesh.nodes)
     nodes = TriMesh.node_type(trimesh.nodes.data, **node_params)
     return TriMesh((trimesh.data, nodes),
                    crs=self.crs,
                    **get_param_values(trimesh))
Example #3
0
    def _process_element(self, element):
        proj = self.p.projection
        irregular = any(element.interface.irregular(element, kd)
                        for kd in element.kdims)

        zs = element.dimension_values(2, flat=False)
        if irregular:
            X, Y = [np.asarray(element.interface.coords(
                element, kd, expanded=True, edges=False))
                    for kd in element.kdims]
        else:
            X = element.interface.coords(element, 0, True, True, False)
            if np.all(X[0, 1:] < X[0, :-1]):
                X = X[:, ::-1]
            Y = element.interface.coords(element, 1, True, True, False)
            if np.all(Y[1:, 0] < Y[:-1, 0]):
                Y = Y[::-1, :]

        if X.shape != zs.shape:
            X = X[:-1] + np.diff(X, axis=0)/2.
            X = X[:, :-1] + (np.diff(X, axis=1)/2.)
        if Y.shape != zs.shape:
            Y = Y[:-1] + np.diff(Y, axis=0)/2.
            Y = Y[:, :-1] + (np.diff(Y, axis=1)/2.)

        coords = proj.transform_points(element.crs, X, Y)
        PX, PY = coords[..., 0], coords[..., 1]

        # Mask quads which are wrapping around the x-axis
        wrap_proj_types = (ccrs._RectangularProjection,
                           ccrs._WarpedRectangularProjection,
                           ccrs.InterruptedGoodeHomolosine,
                           ccrs.Mercator)

        if isinstance(proj, wrap_proj_types):
            with np.errstate(invalid='ignore'):
                edge_lengths = np.hypot(
                    np.diff(PX, axis=1),
                    np.diff(PY, axis=1)
                )
                to_mask = (
                    (edge_lengths >= abs(proj.x_limits[1] -
                                         proj.x_limits[0]) / 2) |
                    np.isnan(edge_lengths)
                )
            if np.any(to_mask):
                mask = np.zeros(zs.shape, dtype=np.bool_)
                mask[:, 1:][to_mask] = True
                mask[:, 2:][to_mask[:, :-1]] = True
                mask[:, :-1][to_mask] = True
                mask[:, :-2][to_mask[:, 1:]] = True
                mask[1:, 1:][to_mask[:-1]] = True
                mask[1:, :-1][to_mask[:-1]] = True
                mask[:-1, 1:][to_mask[1:]] = True
                mask[:-1, :-1][to_mask[1:]] = True
                zs[mask] = np.NaN

        params = get_param_values(element)
        return element.clone((PX, PY, zs), crs=self.p.projection, **params)
Example #4
0
    def _process_element(self, element):
        proj = self.p.projection
        irregular = any(element.interface.irregular(element, kd)
                        for kd in element.kdims)
        zs = element.dimension_values(2, flat=False)
        if irregular:
            X, Y = [np.asarray(element.interface.coords(
                element, kd, expanded=True, edges=False))
                    for kd in element.kdims]
        else:
            X = element.interface.coords(element, 0, True, True, False)
            if np.all(X[0, 1:] < X[0, :-1]):
                X = X[:, ::-1]
            Y = element.interface.coords(element, 1, True, True, False)
            if np.all(Y[1:, 0] < Y[:-1, 0]):
                Y = Y[::-1, :]

        if X.shape != zs.shape:
            X = X[:-1] + np.diff(X, axis=0)/2.
            X = X[:, :-1] + (np.diff(X, axis=1)/2.)
        if Y.shape != zs.shape:
            Y = Y[:-1] + np.diff(Y, axis=0)/2.
            Y = Y[:, :-1] + (np.diff(Y, axis=1)/2.)

        coords = proj.transform_points(element.crs, X, Y)
        PX, PY = coords[..., 0], coords[..., 1]

        # Mask quads which are wrapping around the x-axis
        wrap_proj_types = (ccrs._RectangularProjection,
                           ccrs._WarpedRectangularProjection,
                           ccrs.InterruptedGoodeHomolosine,
                           ccrs.Mercator)
        if isinstance(proj, wrap_proj_types):
            with np.errstate(invalid='ignore'):
                edge_lengths = np.hypot(
                    np.diff(PX, axis=1),
                    np.diff(PY, axis=1)
                )
                to_mask = (
                    (edge_lengths >= abs(proj.x_limits[1] -
                                         proj.x_limits[0]) / 2) |
                    np.isnan(edge_lengths)
                )
            if np.any(to_mask):
                mask = np.zeros(zs.shape, dtype=np.bool)
                mask[:, 1:][to_mask] = True
                mask[:, 2:][to_mask[:, :-1]] = True
                mask[:, :-1][to_mask] = True
                mask[:, :-2][to_mask[:, 1:]] = True
                mask[1:, 1:][to_mask[:-1]] = True
                mask[1:, :-1][to_mask[:-1]] = True
                mask[:-1, 1:][to_mask[1:]] = True
                mask[:-1, :-1][to_mask[1:]] = True
                zs[mask] = np.NaN

        params = get_param_values(element)
        return QuadMesh((PX, PY, zs), crs=self.p.projection, **params)
Example #5
0
 def get_data(self, element, ranges, style):
     if not isinstance(element.data['geometry'], poly_types):
         style['fill_alpha'] = 0
     if isinstance(element.data['geometry'], line_types):
         el_type = Contours
         style['plot_method'] = 'multi_line'
         style.pop('fill_color', None)
         style.pop('fill_alpha', None)
     else:
         el_type = Polygons
     polys = el_type([element.data], crs=element.crs, **util.get_param_values(element))
     return super(GeoShapePlot, self).get_data(polys, ranges, style)
Example #6
0
 def get_data(self, element, ranges, style):
     if not isinstance(element.data['geometry'], poly_types):
         style['fill_alpha'] = 0
     if isinstance(element.data['geometry'], line_types):
         el_type = Contours
         style['plot_method'] = 'multi_line'
         style.pop('fill_color', None)
         style.pop('fill_alpha', None)
     else:
         el_type = Polygons
     polys = el_type([element.data], crs=element.crs, **util.get_param_values(element))
     return super(GeoShapePlot, self).get_data(polys, ranges, style)
Example #7
0
 def _process(self, element, key=None):
     regridder, arrays = self._get_regridder(element)
     x, y = element.kdims
     ds = xr.Dataset({vd: regridder(arr) for vd, arr in arrays.items()})
     ds = ds.rename({'lon': x.name, 'lat': y.name})
     params = get_param_values(element)
     if is_geographic(element):
         try:
             return Image(ds, crs=element.crs, **params)
         except:
             return QuadMesh(ds, crs=element.crs, **params)
     try:
         return HvImage(ds, **params)
     except:
         return HvQuadMesh(ds, **params)
Example #8
0
 def _process(self, element, key=None):
     regridder, arrays = self._get_regridder(element)
     x, y = element.kdims
     ds = xr.Dataset({vd: regridder(arr) for vd, arr in arrays.items()})
     ds = ds.rename({'lon': x.name, 'lat': y.name})
     params = get_param_values(element)
     if is_geographic(element):
         try:
             return Image(ds, crs=element.crs, **params)
         except:
             return QuadMesh(ds, crs=element.crs, **params)
     try:
         return HvImage(ds, **params)
     except:
         return HvQuadMesh(ds, **params)
Example #9
0
    def _process_element(self, element):
        proj = self.p.projection
        irregular = any(
            element.interface.irregular(element, kd) for kd in element.kdims)
        zs = element.dimension_values(2, flat=False)
        if irregular:
            X, Y = [
                np.asarray(element.interface.coords(element, kd,
                                                    expanded=True))
                for kd in element.kdims
            ]
        else:
            X = element.dimension_values(0, expanded=True)
            Y = element.dimension_values(1, expanded=True)
            zs = zs.T

        coords = proj.transform_points(element.crs, X, Y)
        PX, PY = coords[..., 0], coords[..., 1]

        # Mask quads which are wrapping around the x-axis
        wrap_proj_types = (ccrs._RectangularProjection,
                           ccrs._WarpedRectangularProjection,
                           ccrs.InterruptedGoodeHomolosine, ccrs.Mercator)
        if isinstance(proj, wrap_proj_types):
            with np.errstate(invalid='ignore'):
                edge_lengths = np.hypot(np.diff(PX, axis=1), np.diff(PY,
                                                                     axis=1))
                to_mask = ((edge_lengths >=
                            abs(proj.x_limits[1] - proj.x_limits[0]) / 2)
                           | np.isnan(edge_lengths))
            if np.any(to_mask):
                mask = np.zeros(zs.shape, dtype=np.bool)
                mask[:, 1:][to_mask] = True
                mask[:, 2:][to_mask[:, :-1]] = True
                mask[:, :-1][to_mask] = True
                mask[:, :-2][to_mask[:, 1:]] = True
                mask[1:, 1:][to_mask[:-1]] = True
                mask[1:, :-1][to_mask[:-1]] = True
                mask[:-1, 1:][to_mask[1:]] = True
                mask[:-1, :-1][to_mask[1:]] = True
                zs[mask] = np.NaN

        params = get_param_values(element)
        if PX.ndim < 2:
            PX = PX.reshape(zs.shape)
        if PY.ndim < 2:
            PY = PY.reshape(zs.shape)
        return QuadMesh((PX, PY, zs), crs=self.projection, **params)
Example #10
0
    def groupby(cls,
                dataset,
                dims,
                container_type=HoloMap,
                group_type=None,
                **kwargs):
        """
        Groups the data by one or more dimensions returning a container
        indexed by the grouped dimensions containing slices of the
        cube wrapped in the group_type. This makes it very easy to
        break up a high-dimensional dataset into smaller viewable chunks.
        """
        import iris

        if not isinstance(dims, list): dims = [dims]
        dims = [dataset.get_dimension(d, strict=True) for d in dims]
        constraints = [d.name for d in dims]
        slice_dims = [d for d in dataset.kdims if d not in dims]

        # Update the kwargs appropriately for Element group types
        group_kwargs = {}
        group_type = dict if group_type == 'raw' else group_type
        if issubclass(group_type, Element):
            group_kwargs.update(util.get_param_values(dataset))
            group_kwargs['kdims'] = slice_dims
        group_kwargs.update(kwargs)

        drop_dim = any(d not in group_kwargs['kdims'] for d in slice_dims)

        unique_coords = product(
            *[cls.values(dataset, d, expanded=False) for d in dims])
        data = []
        for key in unique_coords:
            constraint = iris.Constraint(**dict(zip(constraints, key)))
            extracted = dataset.data.extract(constraint)
            if drop_dim:
                extracted = group_type(extracted,
                                       kdims=slice_dims,
                                       vdims=dataset.vdims).columns()
            cube = group_type(extracted, **group_kwargs)
            data.append((key, cube))
        if issubclass(container_type, NdMapping):
            with item_check(False), sorted_context(False):
                return container_type(data, kdims=dims)
        else:
            return container_type(data)
Example #11
0
 def get_data(self, element, ranges, style):
     mapping = dict(self._mapping)
     if self.static_source: return {}, mapping, style
     if hasattr(element.data, 'with_scale'):
         feature = element.data.with_scale(self.scale)
     else:
         feature = copy.copy(element.data)
         feature.scale = self.scale
     geoms = list(feature.geometries())
     if isinstance(geoms[0], line_types):
         el_type = Contours
         style['plot_method'] = 'multi_line'
         style.pop('fill_color', None)
         style.pop('fill_alpha', None)
     else:
         el_type = Polygons
     polys = el_type(geoms, crs=element.crs, **util.get_param_values(element))
     return super(FeaturePlot, self).get_data(polys, ranges, style)
Example #12
0
 def get_data(self, element, ranges, style):
     mapping = dict(self._mapping)
     if self.static_source: return {}, mapping, style
     if hasattr(element.data, 'with_scale'):
         feature = element.data.with_scale(self.scale)
     else:
         feature = copy.copy(element.data)
         feature.scale = self.scale
     geoms = list(feature.geometries())
     if isinstance(geoms[0], line_types):
         el_type = Contours
         style['plot_method'] = 'multi_line'
         style.pop('fill_color', None)
         style.pop('fill_alpha', None)
     else:
         el_type = Polygons
     polys = el_type(geoms, crs=element.crs, **util.get_param_values(element))
     return super(FeaturePlot, self).get_data(polys, ranges, style)
Example #13
0
    def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
        """
        Groups the data by one or more dimensions returning a container
        indexed by the grouped dimensions containing slices of the
        cube wrapped in the group_type. This makes it very easy to
        break up a high-dimensional dataset into smaller viewable chunks.
        """
        import iris

        if not isinstance(dims, list): dims = [dims]
        dims = [dataset.get_dimension(d, strict=True) for d in dims]
        constraints = [d.name for d in dims]
        slice_dims = [d for d in dataset.kdims if d not in dims]

        # Update the kwargs appropriately for Element group types
        group_kwargs = {}
        group_type = dict if group_type == 'raw' else group_type
        if issubclass(group_type, Element):
            group_kwargs.update(util.get_param_values(dataset))
            group_kwargs['kdims'] = slice_dims
        group_kwargs.update(kwargs)

        drop_dim = any(d not in group_kwargs['kdims'] for d in slice_dims)

        unique_coords = product(*[cls.values(dataset, d, expanded=False)
                                  for d in dims])
        data = []
        for key in unique_coords:
            constraint = iris.Constraint(**dict(zip(constraints, key)))
            extracted = dataset.data.extract(constraint)
            if drop_dim:
                extracted = group_type(extracted, kdims=slice_dims,
                                       vdims=dataset.vdims).columns()
            cube = group_type(extracted, **group_kwargs)
            data.append((key, cube))
        if issubclass(container_type, NdMapping):
            with item_check(False), sorted_context(False):
                return container_type(data, kdims=dims)
        else:
            return container_type(data)