-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_meoteq.py
1727 lines (1437 loc) · 67.9 KB
/
utils_meoteq.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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Built-in modules
import os
import glob
import re
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
# Basics of Python data handling and visualization
from matplotlib.colors import ListedColormap
import geopandas as gpd
from geopandas import GeoDataFrame as gdf
import rasterio as rio
from shapely import geometry
from rasterstats import zonal_stats
import seaborn as sns
import copy
import numpy as np
from shapely.geometry import Polygon
from rasterio.warp import calculate_default_transform, reproject, Resampling
from typing import List, Union, Tuple, Optional
import pandas as pd
from eolearn.core import EOPatch, EOTask,FeatureType, AddFeature, MapFeatureTask
from eolearn.io import ExportToTiff
from eolearn.features import LinearInterpolation
from collections import defaultdict
import fiona
import rasterio
import rasterio.mask
import geopandas as gpd
from shapely import wkt
import rasterio as rio
from shapely import geometry
from sentinelhub import bbox_to_dimensions
from pathlib import Path
from utils import (get_extent,
draw_outline,
draw_bbox,
draw_feature,
draw_true_color,
unzip_file,
load_tiffs,
load_list_tiffs,
days_to_datetimes,
datetimes_to_days,
reproject_tiff,
upscale_tiff,
mask_tiff)
def polygrid(poly, xres, yres, crs):
"""
Create grid of eopatch (bounds)
:param poly: bounds of eopatch
:param xres: desired pixel's width resolution
:param yres: desired pixel's hight resolution
:param crs: reference corrdinate system
:return: grid
"""
# Get corners
xmin,ymin,xmax,ymax = poly.total_bounds
# Define poly vertical and horizontal limits
cols = list(np.arange(xmin, xmax, xres))
rows = list(np.arange(ymin, ymax, yres))
rows.reverse()
# Create polygons
polygons = []
for x in cols:
for y in rows:
polygons.append(Polygon([(x,y), (x+xres, y), (x+xres, y+yres), (x, y+yres)]))
# Return gpd
grid = gpd.GeoDataFrame({'geometry':polygons}, crs=crs)
return grid
def create_grid(eopatch:EOPatch, model:str, AOI:str):
"""
Create grid and centroids of eopatch (bounds) at orignal and target resolution
:param eopatch: bounds of eopatch
:param model: desired pixel's width resolution
:param AOI: desired pixel's hight resolution
:return: original grid, original centroids, target grid, target centroids
"""
assert AOI in ['Italy','California','South_Africa']
assert model in ['NO2','PM2_5']
if model == 'NO2':
target_resolution = 1000
else:
if AOI == 'Italy':
target_resolution = 1000
else:
target_resolution = 10000
# Create original rectangular grid for pixels corresponding to NO2/PM2.5
bounds = list(eopatch.bbox)
xres = (bounds[2]-bounds[0])/eopatch.data[model].shape[1]
yres = (bounds[3]-bounds[1])/eopatch.data[model].shape[2]
bounds = geometry.box(bounds[0], bounds[1], bounds[2], bounds[3])
bounds = gpd.GeoDataFrame({"id":1,"geometry":[bounds]}, crs="EPSG:4326")
grid = polygrid(bounds, xres,yres, 4326)
centroids = gpd.GeoDataFrame(geometry= grid.centroid)
# Create downscaled rectangular grid (target) for pixels corresponding to NO2/PM2.5
bounds_down = list(eopatch.bbox)
res_down = bbox_to_dimensions(eopatch.bbox, target_resolution)
xres_down = (bounds_down[2]-bounds_down[0])/res_down[0]
yres_down = (bounds_down[3]-bounds_down[1])/res_down[1]
bounds_down = geometry.box(bounds_down[0], bounds_down[1], bounds_down[2], bounds_down[3])
bounds_down = gpd.GeoDataFrame({"id":1,"geometry":[bounds_down]}, crs="EPSG:4326")
grid_down = polygrid(bounds_down, xres_down,yres_down, 4326)
centroids_down = gpd.GeoDataFrame(geometry= grid_down.centroid)
return grid, centroids, grid_down, centroids_down
def reclassify_legend(AOI:str):
"""
Visulize the landcover
:param AOI: area of intrest
:return: color ramp, legend explians the color
"""
assert AOI in ['Italy','California','South_Africa']
if AOI == 'California':
# Define the colors
cmap = ListedColormap(["white", "red", "yellow", "green","blue"])
# Add a legend for labels
legend_labels = {"white": "NODATA",
"red": "urban",
"yellow": "agriculture",
"green": "natural",
"blue": "water",
}
elif AOI == 'South_Africa':
# Define the colors
cmap = ListedColormap(["white", "red", "purple", "yellow", "green"])
# Add a legend for labels
legend_labels = {"white": "NODATA",
"red": "urban",
"purple": "indtrans",
"yellow": "agriculture",
"green": "natural"
}
elif AOI == 'Italy':
# Define the colors
cmap = ListedColormap(["white", "salmon", "brown", "yellow", "green", "lightblue"])
# Add a legend for labels
legend_labels = {"white": "NODATA",
"salmon": "urban",
"brown": "industry and transport",
"yellow": "agriculture",
"green": "natural",
"lightblue": "water"}
return cmap, legend_labels
def reclassify_land_cover(eopatch:EOPatch, feature_name:str, AOI:str,land_cover_path:str,land_cover_name:str, out_name:str,number_of_classes:int):
"""
Reclassify the land cover
:param eopatch: EOPatch for the land cover
:param feature_name: Name of mask timeless data (land cover layer) in the eopatch.
:param AOI: Area of intrest
:param land_cover_path: Directory file where land cover layer is stored
:param land_cover_name: Name of land cover raster
:param out_name: Name of output reclassified raster
:param number_of_classes: Number of reclassifed classes
:return: None
"""
assert AOI in ['Italy','California','South_Africa']
land_cover_path = str(land_cover_path)
if AOI == 'California':
# Reclassify values
array = eopatch.mask_timeless[feature_name]
eopatch.mask_timeless[feature_name][np.isin(array, [20,30,60,70,90,111,116,121])] = 3 # Natural
eopatch.mask_timeless[feature_name][np.isin(array, [40])] = 2 # Agriculture
eopatch.mask_timeless[feature_name][np.isin(array, [50])] = 1 # Urban
eopatch.mask_timeless[feature_name][np.isin(array, [80,200])] = 4 # water
elif AOI == 'South_Africa':
# Reclassify values
array = eopatch.mask_timeless[feature_name]
eopatch.mask_timeless[feature_name][np.isin(array, list(range(1,32)))] = 4 # Natural
eopatch.mask_timeless[feature_name][np.isin(array, list(range(32,47)))] = 3 # Agriculture
eopatch.mask_timeless[feature_name][np.isin(array, list(range(47,66)))] = 1 # Urban
eopatch.mask_timeless[feature_name][np.isin(array, list(range(66,74)))] = 2 # Industrial, roads, rail, mines, landfills
elif AOI == 'Italy':
array = eopatch.mask_timeless[feature_name]
eopatch.mask_timeless[feature_name][array==128] = 0 # no value
eopatch.mask_timeless[feature_name][np.isin(array, [1,2,11])] = 1 # Urban fabric
eopatch.mask_timeless[feature_name][np.isin(array, list(range(3,10)))] = 2 # Industry and transport
eopatch.mask_timeless[feature_name][np.isin(array, list(range(12,23)))] = 3 # Agriculture
eopatch.mask_timeless[feature_name][array == 10] = 4 # Natural
eopatch.mask_timeless[feature_name][np.isin(array, list(range(23,40)))] = 4 # Natural
eopatch.mask_timeless[feature_name][np.isin(array, list(range(40,45)))] = 5 # Water
#eopatch.mask_timeless[feature_name][np.isin(array, [0])] = 5 # Water
src = rio.open(land_cover_path + '/' + land_cover_name)
affine = src.transform
export_geotiff(land_cover_path + '/'+ out_name +'.tif', eopatch.mask_timeless[feature_name][:, :, 0], affine, 4326)
def _percs_landuse_usa(zstats, minpixels):
"""Function to do zonal statistcs for California land cover - percentage of each land cover inside each pixel """
empty = []
urban = []
agri = []
natural = []
water = []
for indx, vals in enumerate(zstats):
# Does it reach min?
if vals['count']<minpixels:
empty.append(np.nan)
urban.append(np.nan)
agri.append(np.nan)
natural.append(np.nan)
water.append(np.nan)
else:
# Empty
if 0 in vals:
empty.append(vals[0]/vals['count'])
else:
empty.append(0)
# Urban
if 1 in vals:
urban.append(vals[1]/vals['count'])
else:
urban.append(0)
# Agriculture
if 2 in vals:
agri.append(vals[2]/vals['count'])
else:
agri.append(0)
# Natural areas
if 3 in vals:
natural.append(vals[3]/vals['count'])
else:
natural.append(0)
# water
if 4 in vals:
water.append(vals[4]/vals['count'])
else:
water.append(0)
# Set to nan if mostly empty
urban = [urban[i] if empty[i]<0.5 else np.nan for i in range(len(urban))]
agri = [agri[i] if empty[i]<0.5 else np.nan for i in range(len(agri))]
natural = [natural[i] if empty[i]<0.5 else np.nan for i in range(len(natural))]
water = [water[i] if empty[i]<0.5 else np.nan for i in range(len(water))]
return urban, agri, natural, water
def _percs_landuse_sa(zstats, minpixels):
"""Function to do zonal statistcs for South Africa land cover - percentage of each land cover inside each pixel """
empty = []
urban = []
indtrans = []
agri = []
natural = []
for indx, vals in enumerate(zstats):
# Does it reach min?
if vals['count']<minpixels:
empty.append(np.nan)
urban.append(np.nan)
indtrans.append(np.nan)
agri.append(np.nan)
natural.append(np.nan)
else:
# Empty
if 0 in vals:
empty.append(vals[0]/vals['count'])
else:
empty.append(0)
# Urban
if 1 in vals:
urban.append(vals[1]/vals['count'])
else:
urban.append(0)
# Industry and transport
if 2 in vals:
indtrans.append(vals[2]/vals['count'])
else:
indtrans.append(0)
# Agriculture
if 3 in vals:
agri.append(vals[3]/vals['count'])
else:
agri.append(0)
# Natural areas
if 4 in vals:
natural.append(vals[4]/vals['count'])
else:
natural.append(0)
# Set to nan if mostly empty
urban = [urban[i] if empty[i]<0.5 else np.nan for i in range(len(urban))]
indtrans = [indtrans[i] if empty[i]<0.5 else np.nan for i in range(len(indtrans))]
agri = [agri[i] if empty[i]<0.5 else np.nan for i in range(len(agri))]
natural = [natural[i] if empty[i]<0.5 else np.nan for i in range(len(natural))]
return urban, indtrans, agri, natural
def _percs_landuse_italy(zstats, minpixels):
"""Function to do zonal statistcs for Italy land cover - percentage of each land cover inside each pixel """
empty = []
urban = []
indtrans = []
agri = []
natural = []
water = []
for indx, vals in enumerate(zstats):
# Does it reach min?
if vals['count']<minpixels:
empty.append(np.nan)
urban.append(np.nan)
indtrans.append(np.nan)
agri.append(np.nan)
natural.append(np.nan)
water.append(np.nan)
else:
# Empty
if 0 in vals:
empty.append(vals[0]/vals['count'])
else:
empty.append(0)
# Urban
if 1 in vals:
urban.append(vals[1]/vals['count'])
else:
urban.append(0)
# Industry and transport
if 2 in vals:
indtrans.append(vals[2]/vals['count'])
else:
indtrans.append(0)
# Agriculture
if 3 in vals:
agri.append(vals[3]/vals['count'])
else:
agri.append(0)
# Natural areas
if 4 in vals:
natural.append(vals[4]/vals['count'])
else:
natural.append(0)
if 5 in vals:
water.append(vals[5]/vals['count'])
else:
water.append(0)
# Set to nan if mostly empty
urban = [urban[i] if empty[i]<0.5 else np.nan for i in range(len(urban))]
indtrans = [indtrans[i] if empty[i]<0.5 else np.nan for i in range(len(indtrans))]
agri = [agri[i] if empty[i]<0.5 else np.nan for i in range(len(agri))]
natural = [natural[i] if empty[i]<0.5 else np.nan for i in range(len(natural))]
water = [water[i] if empty[i]<0.5 else np.nan for i in range(len(water))]
return urban, indtrans, agri, natural, water
LC_PERCS = dict(Italy= _percs_landuse_italy,
California = _percs_landuse_usa,
South_Africa = _percs_landuse_sa)
def percs_landuse(zstats, minpixels, AOI):
assert AOI in ['Italy','California', 'South_Africa']
if AOI == 'South_Africa':
urban, indtrans, agri, natural = LC_PERCS[AOI](zstats, minpixels)
return urban, indtrans, agri, natural
elif AOI == 'Italy':
urban, indtrans, agri, natural, water = LC_PERCS[AOI](zstats, minpixels)
return urban, indtrans, agri, natural, water
elif AOI == 'California':
urban, agri, natural, water = LC_PERCS[AOI](zstats, minpixels)
return urban, agri, natural, water
def land_cover_stats(eopatch:EOPatch,feature_name:str, target_grid, target_centroids, target_bbox, AOI:str, model:str, land_cover_path:str, land_cover_name:str, out_path:str):
"""
Zonal statisics for perecntage land cover classes in each pixel
:param eopatch: EOPatch for reclassified landcover
:param feature_name: Name of mask timeless data (reclassified land cover layer) in the eopatch
:param target_grid: Grid of training data at target resolution
:param target_bbox: Directory file where land cover layer is stored
:param AOI: Name of land cover raster
:param land_cover_path: Name of output reclassified raster
:param land_cover_name: Number of reclassifed classes
:param out_path: Number of reclassifed classes
:return: None
"""
assert AOI in ['Italy','California','South_Africa']
assert model in ['NO2','PM2_5']
if model == 'NO2':
target_resolution = 1000
t=1
buffer_value = 50
else:
if AOI == 'Italy':
target_resolution = 1000
t = 1
buffer_value = 50
else:
target_resolution = 10000
t = 10
buffer_value = 5
land_cover_path = str(land_cover_path)
src = rio.open(land_cover_path + '/' + land_cover_name)
affine = src.transform
array = eopatch.mask_timeless[feature_name]
array = array[:, :, 0] # Remove one dimension
zstats = zonal_stats(target_grid, array, affine=affine, stats="count", categorical=True)
count_pixels = []
for zst in zstats:
count_pixels.append(zst["count"])
min_pixels = 0.75*max(count_pixels)
res_down = bbox_to_dimensions(target_bbox, target_resolution)
bounds = list(target_bbox)
xres = (bounds[2]-bounds[0])/res_down[0]
yres = (bounds[3]-bounds[1])/res_down[1]
# Rasterize
LC_grid = copy.deepcopy(target_grid)
minx, miny, maxx, maxy = LC_grid.geometry.total_bounds
sizey = round((maxy-miny)/yres)
sizex = round((maxx-minx)/xres)
transform = rio.transform.from_bounds(minx, miny, maxx, maxy, sizex, sizey)
if AOI == 'California':
urban, agri, natural, water = percs_landuse(zstats, minpixels=min_pixels, AOI=AOI)
LC_grid[f'urban_{t}km'] = urban
LC_grid[f'agri_{t}km'] = agri
LC_grid[f'natural_{t}km'] = natural
LC_grid[f'water_{t}km'] = water
perc = 30
for lc_class in [f'urban_{t}km', f'agri_{t}km', f'natural_{t}km',f'water_{t}km']:
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class]))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class +'.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
buffs = copy.deepcopy(target_centroids)
buffs['geometry'] = buffs.geometry.buffer(xres * buffer_value)
for lc_class in ['urban','agri', 'natural', 'water']:
# Open dataset
src = rio.open(out_path + f'/{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif')
affine = src.transform
land_cover_eop = load_tiffs(datapath=Path(out_path),
feature=(FeatureType.MASK_TIMELESS, feature_name),
filename=f'{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif',
image_dtype=np.float32,
no_data_value=9999)
array = land_cover_eop.mask_timeless[feature_name]
array = array[:, :, 0] # Remove one dimension
zstats = zonal_stats(buffs, array, affine=affine, stats="mean", nodata=np.nan)
vals = []
for index, value in enumerate(zstats):
vals.append(value['mean'])
# Add to grid
LC_grid[lc_class + '_50km'] = vals
# Rasterize
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class + '_50km']))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class + '_50km' + '.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
elif AOI == 'South_Africa':
urban, indtrans, agri, natural = percs_landuse(zstats, minpixels=min_pixels, AOI=AOI)
LC_grid = copy.deepcopy(target_grid)
LC_grid[f'urban_{t}km'] = urban
LC_grid[f'indtrans_{t}km'] = indtrans
LC_grid[f'agri_{t}km'] = agri
LC_grid[f'natural_{t}km'] = natural
perc = 30
for lc_class in [f'urban_{t}km', f'indtrans_{t}km', f'agri_{t}km',f'natural_{t}km']:
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class]))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class +'.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
buffs = copy.deepcopy(target_centroids)
buffs['geometry'] = buffs.geometry.buffer(xres * buffer_value)
for lc_class in ['urban','indtrans', 'agri', 'natural']:
# Open dataset
src = rio.open(out_path + f'/{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif')
affine = src.transform
land_cover_eop = load_tiffs(datapath=Path(out_path),
feature=(FeatureType.MASK_TIMELESS, feature_name),
filename=f'{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif',
image_dtype=np.float32,
no_data_value=9999)
array = land_cover_eop.mask_timeless[feature_name]
array = array[:, :, 0] # Remove one dimension
zstats = zonal_stats(buffs, array, affine=affine, stats="mean", nodata=np.nan)
vals = []
for index, value in enumerate(zstats):
vals.append(value['mean'])
# Add to grid
LC_grid[lc_class + '_50km'] = vals
# Rasterize
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class + '_50km']))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class + '_50km' + '.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
elif AOI == 'Italy':
urban, indtrans, agri, natural, water = percs_landuse(zstats, minpixels=min_pixels, AOI=AOI)
LC_grid = copy.deepcopy(target_grid)
LC_grid[f'urban_{t}km'] = urban
LC_grid[f'indtrans_{t}km'] = indtrans
LC_grid[f'agri_{t}km'] = agri
LC_grid[f'natural_{t}km'] = natural
LC_grid[f'water_{t}km'] = water
perc = 10
for lc_class in [f'urban_{t}km', f'indtrans_{t}km', f'agri_{t}km',f'natural_{t}km',f'water_{t}km']:
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class]))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class +'.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
buffs = copy.deepcopy(target_centroids)
buffs['geometry'] = buffs.geometry.buffer(xres * buffer_value)
for lc_class in ['urban','indtrans', 'agri', 'natural','water']:
# Open dataset
src = rio.open(out_path + f'/{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif')
affine = src.transform
land_cover_eop = load_tiffs(datapath=Path(out_path),
feature=(FeatureType.MASK_TIMELESS, feature_name),
filename=f'{feature_name}_'+ model + '_' + lc_class +f'_{t}km.tif',
image_dtype=np.float32,
no_data_value=9999)
array = land_cover_eop.mask_timeless[feature_name]
array = array[:, :, 0] # Remove one dimension
zstats = zonal_stats(buffs, array, affine=affine, stats="mean", nodata=np.nan)
vals = []
for index, value in enumerate(zstats):
vals.append(value['mean'])
# Add to grid
LC_grid[lc_class + '_50km'] = vals
# Rasterize
shapes = ((geom, value) for geom, value in zip(LC_grid.geometry, LC_grid[lc_class + '_50km']))
lc = rio.features.rasterize(shapes, out_shape=(sizey, sizex), transform=transform)
export_geotiff(out_path + f'/{feature_name}_'+ model + '_' + lc_class + '_50km' + '.tif', lc, transform, 4326)
print(f"{perc}% Done", end="\r")
perc+=10
return LC_grid
def export_geotiff(path, rast, trans, epsg):
"""
Export array as geotiff raster
Taken from https://rasterio.readthedocs.io/en/latest/api
"""
new_dataset = rio.open(path, 'w', driver='GTiff',
height = rast.shape[0], width = rast.shape[1],
count=1, dtype=str(rast.dtype),
crs="EPSG:"+str(epsg),
transform=trans)
new_dataset.write(rast, 1)
new_dataset.close()
def upscale_mean_tiff(input_filename: str, output_filename: str, out_shape: Tuple[int, int]):
"""
Upscale a tiff file given a target shape using average resampling. Writes out first channel only
"""
with rio.open(input_filename) as dataset:
# resample data to target shape
data = dataset.read(
out_shape=(
dataset.count,
out_shape[0],
out_shape[1]
),
resampling=Resampling.average)
# scale image transform
transform = dataset.transform * dataset.transform.scale(
(dataset.width / data.shape[-1]),
(dataset.height / data.shape[-2])
)
out_meta = dataset.meta
out_meta.update({"driver": "GTiff",
"height": data.shape[1],
"width": data.shape[2],
"transform": transform,
"count": 1})
with rio.open(output_filename, 'w', **out_meta) as dest:
dest.write(data[:1])
def upscale_nearest_tiff(input_filename: str, output_filename: str, out_shape: Tuple[int, int]):
""" Upscale a tiff file given a target shape using nearest neighbour resampling. Writes out first channel only """
with rio.open(input_filename) as dataset:
# resample data to target shape
data = dataset.read(
out_shape=(
dataset.count,
out_shape[0],
out_shape[1]
),
resampling=Resampling.nearest)
# scale image transform
transform = dataset.transform * dataset.transform.scale(
(dataset.width / data.shape[-1]),
(dataset.height / data.shape[-2])
)
out_meta = dataset.meta
out_meta.update({"driver": "GTiff",
"height": data.shape[1],
"width": data.shape[2],
"transform": transform,
"count": 1})
with rio.open(output_filename, 'w', **out_meta) as dest:
dest.write(data[:1])
def ValidData(eopatch,band,min_modis_qa):
"""
Masked the low quality MODIS pixels
:param eopatch: Eopatch where MODIS data are stored
:param band: Bands number in the eopatch
:param min_modis_qa: Threshold quality assurance value
:return: Masked array of MODIS band
"""
eopatch.data['AOD_QA'][..., band][eopatch.data['AOD_QA'][..., band] == min_modis_qa] = np.nan
modis_AOD_QA = eopatch.data['AOD_QA'][..., band]
qa_data = np.unique(modis_AOD_QA)
qa_data = qa_data.astype(np.int16)
qa_data = qa_data.tolist()
qa_data = [x for x in qa_data if x != 0]
for i in qa_data:
mask811 = 0b111100000000
mask02 = 0b000000000111
qa811 = (i & mask811) >> 8
qa02 = (i & mask02) >> 0
if qa811 == 0 and qa02 == 1:
i = float(i)
modis_AOD_QA=np.where(modis_AOD_QA==i, 0, modis_AOD_QA)
else:
i = float(i)
modis_AOD_QA=np.where(modis_AOD_QA==i, 1, modis_AOD_QA)
return modis_AOD_QA
def filter_MODIS(modis_eops, modis_qa_eops):
"""
Filter the low quality MODIS pixels and add new filtered band to the eopatch
:param modis_eops: Eopatch where MODIS bands are stored
:param modis_qa_eops: Eopatch where QA bands are stored
:return: None
"""
feature = (FeatureType.DATA, 'AOD_Valid')
add_feature = AddFeature(feature)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
for index, modis_eop in enumerate(modis_eops):
## Call the AOD_QA EOpatch for the same AOD EOpatch
modis_qa_eop = modis_qa_eops[index]
## Check how many bands in the AOD eopatch
modis_AOD = modis_eop.data['AOD']
t, w, h, b = modis_AOD.shape
## Loop through bands
Masked_data=[]
for band in range(b):
## Take the band in the AOD Eopatch
MODIS_AOD = modis_eop.data['AOD'][..., band]
## Creat mask of clear and high quality pixels for the band in AOD Eopatch from MODIS QA Eopatch
valmask = ValidData(modis_qa_eop,band,min_modis_qa = 0)
## Creat Masked Array of MODIS AOD
Masked_MODIS_AOD = np.ma.array(MODIS_AOD, mask=valmask,fill_value=np.nan)
## Put the maske array in a list
Masked_data.append(Masked_MODIS_AOD)
## Stack the mask arrays for the availabe bands into one array
data = np.ma.stack(Masked_data, axis=-1)
## Add the masked arrays as data in the AOD Eopatch
modis_eop = add_feature.execute(modis_eop, data)
def modis_stats(modis_eops,path):
"""
Compute Statistics (mean, minimum, and maximum) to derive a single daily observation and export a new single daily tiff
:param modis_eops: Eopatch where MODIS bands are stored
:param path: Path of directory where to save the new single daily observation
:return: None
"""
MODIS_NO_DATA_VALUE = -28672
## Tasks to compute statistics of valid AOD (mean, maximum, minimum)
mean = MapFeatureTask((FeatureType.DATA,'AOD_Valid'), # input features
(FeatureType.DATA_TIMELESS,'Stats_MODIS'), # output feature
np.nanmean, # a function to apply to each feature
axis=-1)
maximum = MapFeatureTask((FeatureType.DATA,'AOD_Valid'), # input features
(FeatureType.DATA_TIMELESS,'Stats_MODIS'), # output feature
np.nanmax, # a function to apply to each feature
axis=-1)
minimum = MapFeatureTask((FeatureType.DATA,'AOD_Valid'), # input features
(FeatureType.DATA_TIMELESS,'Stats_MODIS'), # output feature
np.nanmin, # a function to apply to each feature
axis=-1)
## Task to export the merged tiff (mean of daily measurments)
export_tiff = ExportToTiff((FeatureType.DATA_TIMELESS, 'Stats_MODIS'))
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
for modis_eop in modis_eops:
modis_eop.data['AOD_Valid'][modis_eop.data['AOD_Valid'] == MODIS_NO_DATA_VALUE] = np.nan
tiffname = modis_eop.meta_info['Names'][0]
t,w,h,b = modis_eop.data['AOD'].shape
for stats, file_name in [(mean, 'daily_mean_AOD'), (maximum, 'daily_maximum_AOD'), (minimum, 'daily_minimum_AOD')]:
stats(modis_eop)
filled_values = modis_eop.data_timeless['Stats_MODIS'][0]
filled_values.data[filled_values.data == 1.e+20] = np.nan
modis_eop.data_timeless['Stats_MODIS'][0] = filled_values
modis_eop.data_timeless['Stats_MODIS'] = np.resize(modis_eop.data_timeless['Stats_MODIS'],(w, h,1))
export_tiff.execute(modis_eop, filename=str(path)+'/'+file_name+'/'+tiffname)
def fill_modis_gaps(modis_eop, modis_products: list, path):
"""
Fill the gap in MODIS data
:param modis_eops: Eopatch where MODIS data are stored
:param path: Path of directory where save the new filled MODIS data
:return: None
"""
feature = (FeatureType.DATA_TIMELESS, 'filled_AOD')
add_feature = AddFeature(feature)
for modis_p in modis_products:
linear_interp = LinearInterpolation(modis_p)
linear_interp(modis_eop)
## Loop into the patch and sign the mean value of MODIS observations to the emaining missing pixels
mean_AOD = modis_eop.data['daily_mean_AOD']
t, w, h, _ = mean_AOD.shape
for i in range(t):
for modis_p in modis_products:
filled_values = modis_eop.data[modis_p][i]
filled_values[np.isnan(filled_values)] = np.nanmean(filled_values)
modis_eop.data[modis_p][i] = filled_values
for i in range(t):
tiffname = modis_eop.meta_info['tiff_names'][i]
for modis_p in modis_products:
## extract the band
data = modis_eop.data[modis_p][i]
add_feature.execute(modis_eop,data)
## Task to export the band (mean of daily measurments)
export_tiff = ExportToTiff((FeatureType.DATA_TIMELESS, 'filled_AOD'))
export_tiff.execute(modis_eop, filename=str(path)+'/'+modis_p+'/'+tiffname)
def export_s5p_band(s5p_eop, s5p_products:list, path):
"""
Export S5P bands to same bounding box to make sure they are coincide
:param s5p_eop: Eopatch where S5P data are stored
:param s5p_products: S5P products to be extracted (NO2, UV Aerosol Index)
:param s5p_products: Path of directory where save the extracted S5P bands
:return: None
"""
## Task to add the filtered NO2 band
add_s5p = (FeatureType.DATA_TIMELESS, 'S5P')
add_s5p_band = AddFeature(add_s5p)
## Task to export the merged tiff (mean of daily measurments)
export_tiff = ExportToTiff((FeatureType.DATA_TIMELESS, 'S5P'))
for s5p_p in s5p_products:
t,x,y,b = s5p_eop.data[s5p_p].shape
for index in range(t):
no2_array = s5p_eop.data[s5p_p][index][...,0]
# add dimension
no2_array= np.expand_dims(no2_array, axis=-1)
## execute the add task
add_s5p_band.execute(s5p_eop,no2_array)
## tiff name (filtered NO2)
tiffname = s5p_eop.meta_info['Names_' + s5p_p][index]
## export the tiff (filtered NO2)
export_tiff.execute(s5p_eop, filename=str(path)+'/'+ s5p_p + '/' +tiffname)
def target_img(target_dates, AOI:str, model:str):
"""
Select the names of target images and the names of predictors images
:param target_dates: Eopatch where S5P data are stored
:param AOI: Area of interest
:param model: Model (PM 2.5 , NO2)
:return: None
"""
assert AOI in ['Italy','South_Africa','California']
assert model in ['NO2','PM2_5']
## Extract target tiff name
CAMS_PM25_tiffnames = []
CAMS_NO2_tiffnames = []
S5P_NO2_tiffnames = []
uv_aerosol_tiffnames = []
modis_tiffnames = []
era5_tiffnames = [[],[],[],[]]
if model == 'PM2_5':
era5_products = ['rh', 'srwc', 'u', 'v']
for index in target_dates.index:
day, h = target_dates.iloc[index]
CAMS_tiffname = f'CAMS_PM2_5_day{day}_h00.tif'
CAMS_NO2_tiffname = f'CAMS_NO2_day{day}_h00.tif'
uv_aerosol_tiffname = f'S5P_AER_AI_OFFL_L2_day{day}_T00.tif'
modis_tiffname = f'MCD19A2_day{day}.tif'
if AOI == 'Italy':
S5P_NO2_tiffname = f'S5P_NO2_OFFL_L2_day{day}_T00.tif'
else:
S5P_NO2_tiffname = f'S5P_NO2__OFFL_L2_day{day}_T00.tif'
for index, era5_p in enumerate(era5_products):
era5_tiffname = f'ERA5_{era5_p}_day{day-1}_h00.tif'
era5_tiffnames[index].append(era5_tiffname)
era5_tiffname = f'ERA5_{era5_p}_day{day}_h00.tif'
era5_tiffnames[index].append(era5_tiffname)
CAMS_PM25_tiffnames.append(CAMS_tiffname)
CAMS_NO2_tiffnames.append(CAMS_NO2_tiffname)
S5P_NO2_tiffnames.append(S5P_NO2_tiffname)
uv_aerosol_tiffnames.append(uv_aerosol_tiffname)
modis_tiffnames.append(modis_tiffname)
elif model == 'NO2':
era5_products = ['rh', 'srwc', 'u', 'v']
for index in target_dates.index:
day, h = target_dates.iloc[index]
CAMS_tiffname = f'CAMS_PM2_5_day{day}_h00.tif'
CAMS_NO2_tiffname = f'CAMS_NO2_day{day}_h00.tif'
aerosol_tiffnme = f'S5P_AER_AI_OFFL_L2_day{day}_T00.tif'
modis_name= f'MCD19A2_day{day}.tif'
if AOI == 'Italy':
S5P_NO2_tiffname = f'S5P_NO2_OFFL_L2_day{day}_T00.tif'
else:
S5P_NO2_tiffname = f'S5P_NO2__OFFL_L2_day{day}_T00.tif'
for index, era5_p in enumerate(era5_products):
era5_tiffname = f'ERA5_{era5_p}_day{day-1}_h00.tif'
era5_tiffnames[index].append(era5_tiffname)
era5_tiffname = f'ERA5_{era5_p}_day{day}_h00.tif'
era5_tiffnames[index].append(era5_tiffname)
S5P_NO2_tiffnames.append(S5P_NO2_tiffname)
uv_aerosol_tiffnames.append(aerosol_tiffnme)
CAMS_NO2_tiffnames.append(CAMS_NO2_tiffname)
CAMS_PM25_tiffnames.append(CAMS_tiffname)
modis_tiffnames.append(modis_name)
all_tiffnames = []
all_tiffnames.append(CAMS_PM25_tiffnames)
all_tiffnames.append(CAMS_NO2_tiffnames)
all_tiffnames.append(S5P_NO2_tiffnames)
all_tiffnames.append(uv_aerosol_tiffnames)
all_tiffnames.append(modis_tiffnames)
all_tiffnames.append(era5_tiffnames)
return all_tiffnames
def _parse_stats_mean(eopatch, product, path,day):
# Tasks to calculate mean of data
if product == 'NO2':
eopatch.data['Daily'][eopatch.data['Daily'] == -9999.0] = np.nan
eopatch.data['Daily'][eopatch.data['Daily'] > 1] = np.nan
mean = MapFeatureTask((FeatureType.DATA,'Daily'), # input features
(FeatureType.DATA_TIMELESS,'daily_product'), # output feature
np.nanmean, # a function to apply to each feature
axis=0)
# Task to export the merged tiff (mean of daily measurments)
export_tiff = ExportToTiff((FeatureType.DATA_TIMELESS, 'daily_product'))
## Compute and export the mean daily value
mean(eopatch)
tiffname = eopatch.meta_info['Names_'+ product][day]
tiffname = tiffname.replace(tiffname[-6:], "00")
export_tiff.execute(eopatch, filename=str(path)+'/'+product+'/'+tiffname)
def _parse_stats_mean_era5_u(eopatch, product, path,day):
# Tasks to calculate mean of data
mean_abs = MapFeatureTask((FeatureType.DATA,'Daily'), # input features
(FeatureType.DATA_TIMELESS,'daily_product'), # output feature
lambda f: np.nanmean(abs(f), axis=0)) # a function to apply to each feature
# Task to export the merged tiff (mean of daily measurments)
export_tiff = ExportToTiff((FeatureType.DATA_TIMELESS, 'daily_product'))
## Compute and export the mean daily value
mean_abs(eopatch)
tiffname = eopatch.meta_info['Names_'+ product][day]
tiffname = tiffname.replace(tiffname[-10:], "00")
export_tiff.execute(eopatch, filename=str(path)+'/'+product+'/'+tiffname)
def _parse_stats_mean_era5(eopatch, product, path,day):
# Tasks to calculate mean of data
mean_abs = MapFeatureTask((FeatureType.DATA,'Daily'), # input features
(FeatureType.DATA_TIMELESS,'daily_product'), # output feature
lambda f: np.nanmean(abs(f), axis=0)) # a function to apply to each feature