def test_rasterize(tmpdir): path = str(tmpdir.join('polygons.shp')) ds = generate_test_dataset(dims=dict(x=100, y=100, time=5)) df = generate_test_geodataframe() schema = gpd.io.file.infer_schema(df) schema['properties']['date'] = 'date' df.to_file(path, schema=schema) # Rasterize raster = vector.rasterize(path, ds) # Check that the raster contains all fields as variables assert set(raster.data_vars).union({'geometry'}) == set(df.columns) # Check dtypes assert np.issubdtype(raster.float.dtype, np.floating) assert np.issubdtype(raster.integer.dtype, np.signedinteger) assert np.issubdtype(raster.category.dtype, np.signedinteger) # Check that extent, projection etc. are identical to the reference raster assert_equal(warp.get_bounds(raster), warp.get_bounds(ds)) assert_equal_crs(warp.get_crs(raster), warp.get_crs(ds)) assert_equal(warp.get_transform(raster), warp.get_transform(ds)) # Check raster content shape = (ds.dims['y'], ds.dims['x']) transform = warp.get_transform(ds) for i, row in df.iterrows(): poly = row['geometry'] mask = rasterio.features.rasterize([poly], out_shape=shape, transform=transform) # Erode mask to avoid edge effects mask = ndimage.morphology.binary_erosion(mask) == 1 for v in raster.data_vars: if 'legend' in raster[v].attrs: expected = sorted(raster[v].attrs['legend'], key=lambda x: x[1] == str(row[v]))[-1][0] else: expected = row[v] values = raster[v].isel(time=0).values values[mask] assert_allclose(values[mask], expected)
def test_reprojection_with_target(generator): src_crs = epsg4326 dst_crs = sinusoidal ds = generator(crs=src_crs) src_bounds = warp.get_bounds(ds) dst_bounds_latlon = BoundingBox( left=src_bounds.left - 1, bottom=src_bounds.bottom - 1, right=src_bounds.right + 1, top=src_bounds.top + 1, ) dst_bounds = BoundingBox(*rasterio.warp.transform_bounds( src_crs, dst_crs, **dst_bounds_latlon._asdict() )) dst_width, dst_height = 35, 21 resx = (dst_bounds.right - dst_bounds.left) / (dst_width - 1) resy = (dst_bounds.bottom - dst_bounds.top) / (dst_height - 1) res = (abs(resx), abs(resy)) xoff = dst_bounds.left yoff = dst_bounds.top dst_transform = Affine(resx, 0, xoff, 0, resy, yoff) target = generator( dims={'x': dst_width, 'y': dst_height, 'time': 1}, extent=dst_bounds, crs=dst_crs ) projected = [ warp.Reprojection(crs=dst_crs, transform=dst_transform, width=dst_width, height=dst_height).apply(ds), warp.Reprojection(crs=dst_crs, extent=dst_bounds, res=res).apply(ds), warp.Reprojection(crs=dst_crs, extent=dst_bounds, width=dst_width, height=dst_height).apply(ds), warp.Reprojection(target=target).apply(ds), ] for i, proj in enumerate(projected[1:]): print(i) xr_assert_equal(proj, projected[0]) assert_almost_equal(warp.get_resolution(proj), res) assert_almost_equal(warp.get_bounds(proj), dst_bounds) assert_almost_equal(warp.get_transform(proj), dst_transform) assert_equal_crs(warp.get_crs(proj), dst_crs)