This repository has been archived by the owner on Sep 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
s5p-aggregate.py
74 lines (55 loc) · 1.91 KB
/
s5p-aggregate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import argparse
import warnings
from os import makedirs
from pathlib import Path
import geopandas
import numpy as np
import rioxarray
def main(raster_path, shp_path, col_name, agg_func, export_dir):
raster = rioxarray.open_rasterio(raster_path)
shp = geopandas.read_file(shp_path).to_crs("EPSG:4326")
if col_name is None:
col_name = f"{agg_func}_raster"
def _agg(row):
try:
return (
raster.rio.clip([row.geometry], shp.crs)
.reduce(eval(f"np.nan{agg_func}"))
.values.item(0)
)
except rioxarray.exceptions.NoDataInBounds:
return np.nan
shp[col_name] = shp.apply(_agg, axis=1)
export_path = export_dir / agg_func
makedirs(export_path, exist_ok=True)
shp.to_file(f"{export_path}/{raster_path.stem}__{shp_path.stem}.shp")
if __name__ == "__main__":
# Ignore warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
# CLI ARGUMENTS
parser = argparse.ArgumentParser(
description=(
"Export a shapefile with a column containing aggregated"
"data extracted from an input raster file"
)
)
parser.add_argument("raster", help="path to the a raster tif file", type=str)
parser.add_argument("shp", help="path to the shapefile", type=str)
parser.add_argument(
"--col-name", help="name of the column to be created in the shapefile", type=str
)
parser.add_argument(
"--agg-func", help="aggregation function", type=str, default="mean"
)
args = parser.parse_args()
# PATHS
# export: directory for shapefile
EXPORT_DIR = "aggregated"
main(
raster_path=Path(args.raster),
shp_path=Path(args.shp),
col_name=args.col_name,
agg_func=args.agg_func,
export_dir=Path(EXPORT_DIR),
)