Ejemplo n.º 1
0
 def test_dataarray_dimension_order(self):
     x = np.linspace(-3, 7, 53)
     y = np.linspace(-5, 8, 89)
     z = np.exp(-1 * (x**2 + y[:, np.newaxis]**2))
     array = xr.DataArray(z, coords=[y, x], dims=['x', 'y'])
     img = Image(array)
     self.assertEqual(img.kdims, [Dimension('x'), Dimension('y')])
Ejemplo n.º 2
0
 def test_xarray_override_dims(self):
     xs = [0.1, 0.2, 0.3]
     ys = [0, 1]
     zs = np.array([[0, 1], [2, 3], [4, 5]])
     da = xr.DataArray(zs,
                       coords=[('x_dim', xs), ('y_dim', ys)],
                       name="data_name",
                       dims=['y_dim', 'x_dim'])
     da.attrs['long_name'] = "data long name"
     da.attrs['units'] = "array_unit"
     da.x_dim.attrs['units'] = "x_unit"
     da.y_dim.attrs['long_name'] = "y axis long name"
     ds = Dataset(da, kdims=["x_dim", "y_dim"], vdims=["z_dim"])
     x_dim = Dimension("x_dim")
     y_dim = Dimension("y_dim")
     z_dim = Dimension("z_dim")
     self.assertEqual(ds.kdims[0], x_dim)
     self.assertEqual(ds.kdims[1], y_dim)
     self.assertEqual(ds.vdims[0], z_dim)
     ds_from_ds = Dataset(da.to_dataset(),
                          kdims=["x_dim", "y_dim"],
                          vdims=["data_name"])
     self.assertEqual(ds_from_ds.kdims[0], x_dim)
     self.assertEqual(ds_from_ds.kdims[1], y_dim)
     data_dim = Dimension("data_name")
     self.assertEqual(ds_from_ds.vdims[0], data_dim)
Ejemplo n.º 3
0
 def test_bivariate_dframe_constructor(self):
     dist = Bivariate(
         pd.DataFrame({
             'x': [0, 1, 2],
             'y': [0, 1, 2]
         }, columns=['x', 'y']))
     self.assertEqual(dist.kdims, [Dimension('x'), Dimension('y')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 4
0
 def test_irregular_and_regular_coordinate_inference_inverted(self):
     data = self.get_irregular_dataarray(False)
     ds = Dataset(data, vdims='Value')
     self.assertEqual(
         ds.kdims,
         [Dimension('band'),
          Dimension('x'), Dimension('y')])
     self.assertEqual(ds.dimension_values(3, flat=False),
                      data.values.transpose([1, 2, 0]))
Ejemplo n.º 5
0
 def test_dataset_extract_vdims(self):
     df = pd.DataFrame({
         'x': [1, 2, 3],
         'y': [1, 2, 3],
         'z': [1, 2, 3]
     },
                       columns=['x', 'y', 'z'])
     ds = Dataset(df, kdims=['x'])
     self.assertEqual(ds.vdims, [Dimension('y'), Dimension('z')])
Ejemplo n.º 6
0
 def test_dataset_element_allowing_two_kdims_with_one_default_kdim(self):
     df = pd.DataFrame({
         'x': [1, 2, 3],
         'y': [1, 2, 3],
         'z': [1, 2, 3]
     },
                       columns=['x', 'y', 'z'])
     ds = Scatter(df)
     self.assertEqual(ds.kdims, [Dimension('x')])
     self.assertEqual(ds.vdims, [Dimension('y'), Dimension('z')])
Ejemplo n.º 7
0
 def test_bivariate_dframe_constructor(self):
     if pd is None:
         raise SkipTest("Test requires pandas, skipping.")
     dist = Bivariate(
         pd.DataFrame({
             'x': [0, 1, 2],
             'y': [0, 1, 2]
         }, columns=['x', 'y']))
     self.assertEqual(dist.kdims, [Dimension('x'), Dimension('y')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 8
0
 def test_dataset_extract_vdims_with_kdims_defined(self):
     df = pd.DataFrame({
         'x': [1, 2, 3],
         'y': [1, 2, 3],
         'z': [1, 2, 3]
     },
                       columns=['x', 'y', 'z'])
     ds = Points(df, kdims=['x', 'z'])
     self.assertEqual(ds.kdims, [Dimension('x'), Dimension('z')])
     self.assertEqual(ds.vdims, [Dimension('y')])
Ejemplo n.º 9
0
 def test_dataset_process_index(self):
     df = pd.DataFrame({
         'x': [1, 2, 3],
         'y': [1, 2, 3],
         'z': [1, 2, 3]
     },
                       columns=['x', 'y', 'z'])
     ds = Dataset(df, 'index')
     self.assertEqual(ds.kdims, [Dimension('index')])
     self.assertEqual(
         ds.vdims,
         [Dimension('x'), Dimension('y'),
          Dimension('z')])
Ejemplo n.º 10
0
    def init(cls, eltype, data, kdims, vdims):
        if kdims:
            kdim_names = [
                kd.name if isinstance(kd, Dimension) else kd for kd in kdims
            ]
        else:
            kdim_names = [kd.name for kd in eltype.kdims]

        if not isinstance(data, iris.cube.Cube):
            ndims = len(kdim_names)
            kdims = [
                kd if isinstance(kd, Dimension) else Dimension(kd)
                for kd in kdims
            ]
            vdim = vdims[0].name if isinstance(vdims[0],
                                               Dimension) else vdims[0]
            if isinstance(data, tuple):
                value_array = data[-1]
                data = {d: vals for d, vals in zip(kdim_names + [vdim], data)}
            elif isinstance(data, dict):
                value_array = data[vdim]
            coords = [(iris.coords.DimCoord(data[kd.name],
                                            long_name=kd.name,
                                            units=kd.unit), ndims - n - 1)
                      for n, kd in enumerate(kdims)]
            try:
                data = iris.cube.Cube(value_array,
                                      long_name=vdim,
                                      dim_coords_and_dims=coords)
            except:
                pass
            if not isinstance(data, iris.cube.Cube):
                raise TypeError('Data must be be an iris dataset type.')

        if kdims:
            coords = []
            for kd in kdims:
                coord = data.coords(
                    kd.name if isinstance(kd, Dimension) else kd)
                if len(coord) == 0:
                    raise ValueError('Key dimension %s not found in '
                                     'Iris cube.' % kd)
                coords.append(coord[0])
        else:
            coords = data.dim_coords
            coords = sorted(coords, key=sort_coords)
        kdims = [coord_to_dimension(crd) for crd in coords]
        if vdims is None:
            vdims = [Dimension(data.name(), unit=str(data.units))]

        return data, {'kdims': kdims, 'vdims': vdims}, {'group': data.name()}
Ejemplo n.º 11
0
 def test_xarray_dataset_names_and_units(self):
     xs = [0.1, 0.2, 0.3]
     ys = [0, 1]
     zs = np.array([[0, 1], [2, 3], [4, 5]])
     da = xr.DataArray(zs, coords=[('x_dim', xs), ('y_dim', ys)], name="data_name", dims=['y_dim', 'x_dim'])
     da.attrs['long_name'] = "data long name"
     da.attrs['units'] = "array_unit"
     da.x_dim.attrs['units'] = "x_unit"
     da.y_dim.attrs['long_name'] = "y axis long name"
     dataset = Dataset(da)
     self.assertEqual(dataset.get_dimension("x_dim"), Dimension("x_dim", unit="x_unit"))
     self.assertEqual(dataset.get_dimension("y_dim"), Dimension("y_dim", label="y axis long name"))
     self.assertEqual(dataset.get_dimension("data_name"),
                      Dimension("data_name", label="data long name", unit="array_unit"))
Ejemplo n.º 12
0
 def test_distribution_composite_not_filled(self):
     dist = Distribution(np.array([0, 1,
                                   2]), ).opts(plot=dict(filled=False))
     curve = Compositor.collapse_element(dist, backend='matplotlib')
     self.assertIsInstance(curve, Curve)
     self.assertEqual(curve.vdims,
                      [Dimension(('Value_density', 'Value Density'))])
Ejemplo n.º 13
0
    def test_construct_from_xarray(self):
        try:
            import xarray as xr
        except:
            raise SkipTest("Test requires xarray")
        coords = OrderedDict([('lat', (('y', 'x'), self.ys)),
                              ('lon', (('y', 'x'), self.xs))])
        da = xr.DataArray(self.zs, dims=['y', 'x'], coords=coords, name='z')
        dataset = Dataset(da)

        # Ensure that dimensions are inferred correctly
        self.assertEqual(dataset.kdims, [Dimension('lat'), Dimension('lon')])
        self.assertEqual(dataset.vdims, [Dimension('z')])

        # Ensure that canonicalization works on multi-dimensional coordinates
        self.assertEqual(dataset.dimension_values('lon', flat=False), self.xs)
        self.assertEqual(dataset.dimension_values('lat', flat=False), self.ys)
        self.assertEqual(dataset.dimension_values('z'), self.zs.T.flatten())
Ejemplo n.º 14
0
 def test_dataset_extract_kdims(self):
     df = pd.DataFrame({
         'x': [1, 2, 3],
         'y': [1, 2, 3],
         'z': [1, 2, 3]
     },
                       columns=['x', 'y', 'z'])
     ds = Distribution(df)
     self.assertEqual(ds.kdims, [Dimension('x')])
Ejemplo n.º 15
0
def coord_to_dimension(coord):
    """
    Converts an iris coordinate to a HoloViews dimension.
    """
    kwargs = {}
    if coord.units.is_time_reference():
        kwargs['value_format'] = get_date_format(coord)
    else:
        kwargs['unit'] = str(coord.units)
    return Dimension(coord.name(), **kwargs)
Ejemplo n.º 16
0
 def test_labels_formatter(self):
     vdim = Dimension('text', value_format=lambda x: '%.1f' % x)
     labels = Labels([(0, 1, 0.33333), (1, 0, 0.66666)], vdims=vdim)
     plot = mpl_renderer.get_plot(labels)
     artist = plot.handles['artist']
     expected = {'x': np.array([0, 1]), 'y': np.array([1, 0]),
                 'text': ['0.3', '0.7']}
     for i, text in enumerate(artist):
         self.assertEqual(text._x, expected['x'][i])
         self.assertEqual(text._y, expected['y'][i])
         self.assertEqual(text.get_text(), expected['text'][i])
Ejemplo n.º 17
0
 def test_labels_formatter(self):
     vdim = Dimension('text', value_format=lambda x: '%.1f' % x)
     labels = Labels([(0, 1, 0.33333), (1, 0, 0.66666)], vdims=vdim)
     plot = bokeh_renderer.get_plot(labels)
     source = plot.handles['source']
     glyph = plot.handles['glyph']
     expected = {'x': np.array([0, 1]), 'y': np.array([1, 0]),
                 'text': ['0.3', '0.7']}
     for k, vals in expected.items():
         self.assertEqual(source.data[k], vals)
     self.assertEqual(glyph.x, 'x')
     self.assertEqual(glyph.y, 'y')
     self.assertEqual(glyph.text, 'text')
Ejemplo n.º 18
0
    def init(cls, eltype, data, kdims, vdims):
        if kdims:
            kdim_names = [
                kd.name if isinstance(kd, Dimension) else kd for kd in kdims
            ]
        else:
            kdim_names = [kd.name for kd in eltype.kdims]

        if not isinstance(data, iris.cube.Cube):
            if isinstance(data, tuple):
                coords = [
                    iris.coords.DimCoord(vals, long_name=kd)
                    for kd, vals in zip(kdim_names, data)
                ]
                value_array = data[-1]
                vdim = vdims[0].name if isinstance(vdims[0],
                                                   Dimension) else vdims[0]
            elif isinstance(data, dict):
                vdim = vdims[0].name if isinstance(vdims[0],
                                                   Dimension) else vdims[0]
                coords = [
                    iris.coords.DimCoord(vals, long_name=kd)
                    for kd, vals in data.items() if kd in kdims
                ]
                value_array = data[vdim]
            try:
                data = iris.cube.Cube(value_array,
                                      long_name=vdim,
                                      dim_coords_and_dims=coords)
            except:
                pass
            if not isinstance(data, iris.cube.Cube):
                raise TypeError('Data must be be an iris dataset type.')

        if kdims:
            coords = []
            for kd in kdims:
                coord = data.coords(
                    kd.name if isinstance(kd, Dimension) else kd)
                if len(coord) == 0:
                    raise ValueError('Key dimension %s not found in '
                                     'Iris cube.' % kd)
                coords.append(coord[0])
        else:
            coords = data.dim_coords
            coords = sorted(coords, key=sort_coords)
        kdims = [coord_to_dimension(crd) for crd in coords]
        if vdims is None:
            vdims = [Dimension(data.name(), unit=str(data.units))]

        return data, kdims, vdims
Ejemplo n.º 19
0
    def init(cls, eltype, data, kdims, vdims):
        if not isinstance(data, iris.cube.Cube):
            raise TypeError('HoloCube data must be be an iris HoloCube type.')

        if kdims:
            if len(kdims) != len(data.dim_coords):
                raise ValueError('Supplied key dimensions must match '
                                 'HoloCube dim_coords.')
            coords = []
            for kd in kdims:
                coord = data.coords(kd.name if isinstance(kd, Dimension) else kd)
                if len(coord) == 0:
                    raise ValueError('Key dimension %s not found in '
                                     'Iris cube.' % kd)
                coords.append(coord[0])
        else:
            coords = data.dim_coords
            coords = sorted(coords, key=util.sort_coords)
        kdims = [util.coord_to_dimension(crd) for crd in coords]
        if vdims is None:
            vdims = [Dimension(data.name(), unit=str(data.units))]

        return data, kdims, vdims
Ejemplo n.º 20
0
 def test_bivariate_composite_custom_vdim(self):
     dist = Bivariate(np.random.rand(10, 2), vdims=['Test'])
     contours = Compositor.collapse_element(dist)
     self.assertIsInstance(contours, Contours)
     self.assertEqual(contours.vdims, [Dimension('Test')])
Ejemplo n.º 21
0
 def test_distribution_array_constructor(self):
     dist = Distribution(np.array([0, 1, 2]))
     self.assertEqual(dist.kdims, [Dimension('Value')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 22
0
 def test_bivariate_dict_constructor(self):
     dist = Bivariate({'x': [0, 1, 2], 'y': [0, 1, 2]}, ['x', 'y'])
     self.assertEqual(dist.kdims, [Dimension('x'), Dimension('y')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 23
0
 def test_bivariate_array_constructor_custom_vdim(self):
     dist = Bivariate(np.array([[0, 1, 2], [0, 1, 2]]), vdims=['Test'])
     self.assertEqual(dist.kdims, [Dimension('x'), Dimension('y')])
     self.assertEqual(dist.vdims, [Dimension('Test')])
Ejemplo n.º 24
0
 def test_distribution_array_constructor_custom_vdim(self):
     dist = Distribution(np.array([0, 1, 2]), vdims=['Test'])
     self.assertEqual(dist.kdims, [Dimension('Value')])
     self.assertEqual(dist.vdims, [Dimension('Test')])
Ejemplo n.º 25
0
 def test_bivariate_array_constructor(self):
     dist = Bivariate(np.array([[0, 1, 2], [0, 1, 2]]))
     self.assertEqual(dist.kdims, [Dimension('x'), Dimension('y')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 26
0
 def test_distribution_dict_constructor(self):
     dist = Distribution({'Value': [0, 1, 2]})
     self.assertEqual(dist.kdims, [Dimension('Value')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 27
0
 def test_distribution_series_constructor(self):
     if pd is None:
         raise SkipTest("Test requires pandas")
     dist = Distribution(pd.Series([0, 1, 2], name='Value'))
     self.assertEqual(dist.kdims, [Dimension('Value')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 28
0
 def test_bivariate_composite_empty_not_filled(self):
     dist = Bivariate([]).opts(plot=dict(filled=True))
     contours = Compositor.collapse_element(dist)
     self.assertIsInstance(contours, Contours)
     self.assertEqual(contours.vdims, [Dimension('Density')])
     self.assertEqual(len(contours), 0)
Ejemplo n.º 29
0
 def test_distribution_dframe_constructor(self):
     if pd is None:
         raise SkipTest("Test requires pandas, skipping.")
     dist = Distribution(pd.DataFrame({'Value': [0, 1, 2]}))
     self.assertEqual(dist.kdims, [Dimension('Value')])
     self.assertEqual(dist.vdims, [Dimension('Density')])
Ejemplo n.º 30
0
 def test_bivariate_composite_filled(self):
     dist = Bivariate(np.random.rand(10, 2)).opts(plot=dict(filled=True))
     contours = Compositor.collapse_element(dist)
     self.assertIsInstance(contours, Polygons)
     self.assertEqual(contours.vdims, [Dimension('Density')])