corteva / rioxarray

geospatial xarray extension powered by rasterio
https://corteva.github.io/rioxarray
Other
511 stars 81 forks source link

Tests Constructor #585

Open sehHeiden opened 1 year ago

sehHeiden commented 1 year ago

For creating simple tests I would like to have/ get a simple method to construct DataArray in Rioarray.

For example with: DataArray(data=np.ones([1, 5, 5], np.uint8), dims=("band", "y", "x"), transform=affine) or as alternative: DataArray(data=np.ones([1, 5, 5], np.uint8), dims=("band", "y", "x"), index=index) with indexes['x'], indexes['y'], indexes['z'].

snowman2 commented 1 year ago

Reference for adding geospatial metadata: https://corteva.github.io/rioxarray/stable/getting_started/crs_management.html

Too generate coordinates from a transform to add to the DataArray, affine_to_coords is helpful.

sehHeiden commented 1 year ago

Seams like things are better than I expected.

    from geopandas import GeoDataFrame, GeoSeries
    from xarray import DataArray
    from affine import Affine

    positions = GeoSeries([Polygon([(-0.5, -0.5), (-0.5, 1.5), (1.5, 1.5), (1.5, -0.5)]),
                           Polygon([(1.5, 1.5), (1.5, 4.5), (4.5, 4.5), (4.5, 1.5)])])
    test_gdf = GeoDataFrame({'FL_GEO_ha': [4, 9],
                             'geometry': positions},
                            crs=4326)

    affine = Affine(1, 0, 0,
                    0, -1, 0)
    test_raster = DataArray([[10, 10, 0, 0, 0, ],
                             [10, 10, 0, 0, 0, ],
                             [0, 0, 50, 50, 50, ],
                             [0, 0, 50, 50, 50, ],
                             [0, 0, 50, 50, 50, ], ],)
    test_raster = test_raster.rio.write_crs(4326)
    test_raster = test_raster.rio.write_transform(affine)
    # test_raster.indexes = affine_to_coords(affine, 5, 5)

Which does not work as I expected. Because the result of affine_to_coords cannot be set to the indexes attribut. a) is that the right input? b) has the input the correct datatype, c) which way do I have to set the input?

I also tried a zonal stat on that DataArray with the GeoSeries. But the output or mean is 10 and None. So there is Elements of the DataArray are at different possitions that I thought they would be (GeoSeries). Can you help me finding mistake in my thought process?

snowman2 commented 1 year ago

I think this is closer to what you are looking for:

test_raster = DataArray(..., coords=affine_to_coords(...))