def test_set_mask(self): grid = self.get_gridxy() grid.parent['coordinate_system'] = Variable(name='coordinate_system') self.assertFalse(np.any(grid.get_mask())) mask = np.zeros(grid.shape, dtype=bool) mask[1, 1] = True self.assertTrue(grid.is_vectorized) grid.set_mask(mask) self.assertTrue(np.all(grid.get_mask()[1, 1])) self.assertIn('coordinate_system', grid.parent) self.assertTrue(grid.is_vectorized) for mvar in grid.get_member_variables(): if mvar.name != grid._mask_name: self.assertIsNone(mvar.get_mask()) path = self.get_temporary_file_path('foo.nc') grid.write(path) nvc = RequestDataset(path).get() self.assertIsInstance(nvc, Field) ngrid = Grid(nvc['x'], nvc['y'], parent=nvc) # Mask is not written to coordinate variables. for mvar in ngrid.get_member_variables(): if mvar.name == grid.mask_variable.name: self.assertTrue(mvar.get_mask()[1, 1]) else: self.assertIsNone(mvar.get_mask()) # Test with a parent. grid = self.get_gridxy(with_parent=True) for k in ['tas', 'rhs']: self.assertIsNone(grid.parent[k].get_mask()) new_mask = grid.get_mask(create=True) self.assertFalse(new_mask.any()) new_mask[1:3, 1] = True grid.set_mask(new_mask, cascade=True) for k in ['tas', 'rhs']: backref_var = grid.parent[k] mask = backref_var.get_mask() self.assertTrue(mask.any()) if k == 'tas': self.assertTrue(mask[:, 1, 1:3].all()) if k == 'rhs': self.assertTrue(mask[1:3, 1, :].all()) self.assertEqual(mask.sum(), 20)
def test_system_masking(self): """Test behavior of the grid mask. This is an independently managed variable.""" x = Variable('xc', value=[1, 2, 3], dimensions='dimx') y = Variable('yc', value=[10, 20, 30, 40], dimensions='dimy') grid = Grid(x, y) data = Variable('data', value=np.zeros(grid.shape), dimensions=['dimy', 'dimx']) grid.parent.add_variable(data) gmask = grid.get_mask() self.assertIsNone(gmask) self.assertIsNone(grid.mask_variable) new_mask = np.zeros(grid.shape, dtype=bool) new_mask[1, 1] = True grid.set_mask(new_mask, cascade=True) self.assertIsInstance(grid.mask_variable, Variable) actual = grid.get_mask() self.assertNumpyAll(actual, new_mask) actual = get_variable_names(grid.get_member_variables()) desired = [x.name, y.name, grid._mask_name] self.assertAsSetEqual(actual, desired) self.assertNumpyAll(grid.get_mask(), data.get_mask()) path = self.get_temporary_file_path('foo.nc') grid.parent.write(path) with self.nc_scope(path) as ds: actual = ds.variables[grid.mask_variable.name] self.assertNumpyAll(grid.get_mask(), actual[:].mask) # Test mask is used when read from file. actual_field = RequestDataset(path).get() self.assertNumpyAll(grid.get_mask(), actual_field.grid.get_mask()) self.assertEqual(actual_field.grid.get_mask().sum(), 1) self.assertTrue(actual_field.grid.is_vectorized) self.assertEqual(actual_field.grid.get_mask().dtype, bool) actual_field.set_abstraction_geom() self.assertNumpyAll(actual_field.geom.get_mask(), grid.get_mask())