nismod / snail

spatial networks impact assessment library 🐌
https://nismod.github.io/snail/
MIT License
9 stars 1 forks source link

Helper to save some attribute/calculation from split geometries back to raster #60

Open tomalrussell opened 4 months ago

tomalrussell commented 4 months ago

Given a GeoDataFrame of split geometries, and some attribute (e.g. length_km) that we want to save, provide a helper function to aggregate those split vector elements back to a raster data structure - along the lines of:

raster_height = 100
raster_width = 100

length_raster = numpy.zeros((raster_height, raster_width))

splits_df = # data frame of split geometries, with length_km calculated
length_per_cell = splits_df[['cell_index', 'length_km']].groupby('cell_index').sum()

for row in length_per_cell.reset_index().itertuples():
    col, row = row.cell_index
    length_raster[row, col] = row.length_km

with rasterio.open(
        f'outputs/length.tif',
        'w',
        driver='GTiff',
        height=length_raster.shape[0],
        width=length_raster.shape[1],
        count=1,
        dtype=length_raster.dtype,
        crs='+proj=latlong',
        transform=raster_transform,
        compress='lzw'
    ) as dataset:
    dataset.write(length_raster, 1)