Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

aggregate_results.py 3.8 KB

You have to be logged in to leave a comment. Sign In
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  1. import argparse
  2. from dataclasses import dataclass
  3. from functools import partial, reduce
  4. from pathlib import Path
  5. from typing import Any, Optional, Tuple
  6. from joblib import delayed, Parallel
  7. import geopandas as gpd
  8. import numpy as np
  9. import pandas as pd
  10. import rioxarray
  11. from shapely.geometry import box, Polygon
  12. from tqdm import tqdm
  13. classes = [0, 1, 2]
  14. WORKERS = 16
  15. lat_point_list = [50.854457, 52.518172, 50.072651, 48.853033, 50.854457]
  16. lon_point_list = [4.377184, 13.407759, 14.435935, 2.349553, 4.377184]
  17. polygon_geom = Polygon(zip(lon_point_list, lat_point_list))
  18. crs = {"init": "epsg:4326"}
  19. @dataclass
  20. class Result:
  21. bounds: Tuple[float, float, float, float]
  22. crs: Any
  23. conifer: Optional[float]
  24. broadleaf: Optional[float]
  25. @property
  26. def total(self) -> Optional[float]:
  27. if (self.conifer is None) and (self.broadleaf is None):
  28. return None
  29. if (self.conifer is None) and (self.broadleaf is not None):
  30. raise NotImplementedError
  31. if (self.conifer is not None) and (self.broadleaf is None):
  32. raise NotImplementedError
  33. return self.conifer + self.broadleaf
  34. def to_gdf(self):
  35. if self.bounds and self.crs:
  36. gdf = gpd.GeoDataFrame(
  37. index=[0],
  38. data={
  39. "conifer": [self.conifer],
  40. "broadleaf": [self.broadleaf],
  41. "total": [self.total],
  42. },
  43. crs=self.crs,
  44. geometry=[box(*self.bounds)],
  45. )
  46. return gdf
  47. return None
  48. def process_tile(tile: Path, forest_tile: Path, *, year: str, limit: int) -> Result:
  49. with rioxarray.open_rasterio(tile, chunks=(1, 512, 512)).squeeze(
  50. drop=True
  51. ) as ds, rioxarray.open_rasterio(forest_tile, chunks=(1, 512, 512)).squeeze(
  52. drop=True
  53. ) as ds_mask:
  54. res = []
  55. for c in classes[1:]:
  56. a = ds.values
  57. b = ds_mask.values
  58. if (b.sum() / b.size) * 100 < limit:
  59. return Result(
  60. conifer=None, broadleaf=None, bounds=ds.rio.bounds(), crs=ds.rio.crs
  61. )
  62. dead = a[(a == c) & (b == 1)].sum()
  63. forest = b.sum()
  64. res.append((dead / forest) * 100)
  65. return Result(
  66. conifer=res[0], broadleaf=res[1], bounds=ds.rio.bounds(), crs=ds.rio.crs
  67. )
  68. def main():
  69. parser = argparse.ArgumentParser()
  70. parser.add_argument(
  71. "--limit",
  72. dest="limit",
  73. type=int,
  74. default=10,
  75. help="Min. forest cover to include pixel [%]",
  76. )
  77. parser.add_argument("datapath", type=Path, nargs="+")
  78. args = parser.parse_args()
  79. years = [2017, 2018, 2019, 2020]
  80. for year in years:
  81. inpath = None
  82. for dpath in args.datapath:
  83. if f"processed.lus.{year}" in str(dpath):
  84. inpath = dpath
  85. if not inpath:
  86. raise NotImplementedError
  87. print(f"Processing year: {year}...")
  88. tiles_forest_mask = sorted(inpath.glob("*.tif"))
  89. def swap_dir(x: Path, search: str, replace: str) -> Path:
  90. path_elements = list(x.parts)
  91. idx = path_elements.index(search)
  92. path_elements[idx] = replace
  93. return Path(*path_elements)
  94. tiles = [
  95. swap_dir(t, f"processed.lus.{year}", f"predicted.{year}")
  96. for t in tiles_forest_mask
  97. ]
  98. results = Parallel(n_jobs=WORKERS)(
  99. delayed(partial(process_tile, year=year, limit=args.limit))(*d)
  100. for d in tqdm(list(zip(tiles, tiles_forest_mask)))
  101. )
  102. gpd.GeoDataFrame(
  103. pd.concat([r.to_gdf() for r in results], ignore_index=True)
  104. ).to_file(f"data/aggregated_{year}.shp")
  105. if __name__ == "__main__":
  106. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...