-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathburnsev_gee.py
1357 lines (1113 loc) · 62.9 KB
/
burnsev_gee.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
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 18 10:16:47 2022
@author: snasonov
"""
from datetime import datetime,timedelta
import ee
import geemap
import os,json
#from datetime import datetime as dt
import pandas as pd
from osgeo import gdal
from osgeo.gdalconst import GA_Update
def export_alternates(folder,mosaic_col,dattype,fires_df,poly,opt,firenumber,imgtype):
def grid_footprint(footprint,nx,ny):
from shapely.geometry import Polygon, LineString, MultiPolygon
from shapely.ops import split
#polygon = footprint
polygon = Polygon(footprint['coordinates'][0])
#polygon = Polygon(footprint)
minx, miny, maxx, maxy = polygon.bounds
dx = (maxx - minx) / nx # width of a small part
dy = (maxy - miny) / ny # height of a small part
horizontal_splitters = [LineString([(minx, miny + i*dy), (maxx, miny + i*dy)]) for i in range(ny)]
vertical_splitters = [LineString([(minx + i*dx, miny), (minx + i*dx, maxy)]) for i in range(nx)]
splitters = horizontal_splitters + vertical_splitters
result = polygon
for splitter in splitters:
result = MultiPolygon(split(result, splitter))
coord_list = [list(part.exterior.coords) for part in result.geoms]
poly_list = []
for cc in coord_list:
p = ee.Geometry.Polygon(cc)
poly_list.append(p)
return(poly_list)
def apply_scale_factors(image):
opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2)
thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0)
return image.addBands(opticalBands, None, True).addBands(thermalBands, None, True)
if imgtype == 'pre':
f = 'pre_truecolor_8bit_alt'
else:
f = 'post_truecolor_8bit_alt'
#Exporting alternates
poly_area = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['areaha']]
print('Fire Area: ' + str(poly_area))
if poly_area < 10000:
n = 2
elif poly_area > 10000 and poly_area < 100000:
n = 3
elif poly_area > 100000 and poly_area < 400000:
n = 4
else:
n = 5
print('Number of tiles: ' + str(n*n))
#export pre and post rgbs, tile to avoid pixel limit issues.
footprint = poly.geometry().bounds().getInfo()
grids = grid_footprint(footprint,n,n) #3,3 works for a fire that's ~90 000 ha large, if larger, increase the number of tiles
## Export all pre qls
pre_tc_8bit = os.path.join(folder,f)
if not os.path.exists(pre_tc_8bit):
os.makedirs(pre_tc_8bit)
mosaic_col_list = mosaic_col.toList(1000)
if mosaic_col.size().getInfo() == 0:
print('No alternatives')
pass
else:
for i in range(0,mosaic_col_list.length().getInfo()):
pre_img = ee.Image(mosaic_col_list.get(i))
pre_date = pre_img.get("system:index").getInfo()
if dattype.startswith('S2'):
pre_img_export = pre_img.multiply(0.0001)
elif (dattype == 'L8') | (dattype == 'L9'):
pre_img_export = apply_scale_factors(pre_img)
elif (dattype == 'L5') | (dattype == 'L7'):
pre_img_export = apply_scale_factors(pre_img)
else:
pass
pre_img_list = []
for i in range(0,len(grids)):
roi = grids[i]
filename = os.path.join(pre_tc_8bit, dattype + '_' + pre_date + '_' + f + '_' + str(i) + '.tif')
pre_img_list.append(filename)
if dattype.startswith('S2'):
viz = {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img_export.clip(roi).visualize(**viz), filename=filename, scale=10, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L8') | (dattype == 'L9'):
viz = {'bands': ['SR_B4', 'SR_B3', 'SR_B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img_export.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L5') | (dattype == 'L7'):
viz = {'bands': ['SR_B3','SR_B2','SR_B1'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img_export.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
else:
pass
#mosaic
outfilename = dattype + '_' + pre_date + '_' + f + '.tif'
out = os.path.join(pre_tc_8bit,outfilename)
gdal.Warp(out,pre_img_list)
for file in pre_img_list: os.remove(file) #delete tiles
print('Alternates exported')
return(pre_tc_8bit)
def barc(fires_df,firenumber,outdir,poly,opt,proc):
def getfiles(d,ext):
paths = []
for file in os.listdir(d):
if file.endswith(ext):
paths.append(os.path.join(d, file))
return(paths)
#Helper function must be nested within barc
def getDate(im):
return(ee.Image(im).date().format("YYYY-MM-dd"))
def getSceneIds(im):
return(ee.Image(im).get('PRODUCT_ID'))
def mosaicByDate(indate):
d = ee.Date(indate)
#print(d)
im = col.filterBounds(poly).filterDate(d, d.advance(1, "day")).mosaic()
#print(im)
return(im.set("system:time_start", d.millis(), "system:index", d.format("YYYY-MM-dd")))
def runDateMosaic(col_list):
#get a list of unique dates within the list
date_list = col_list.map(getDate).getInfo()
udates = list(set(date_list))
udates.sort()
udates_ee = ee.List(udates)
#mosaic images by unique date
mosaic_imlist = udates_ee.map(mosaicByDate)
return(ee.ImageCollection(mosaic_imlist))
def NBR_S2(image):
nbr = image.expression(
'(NIR - SWIR) / (NIR + SWIR)', {
'NIR': image.select('B8'),
'SWIR': image.select('B12')}).rename('nbr')
return(nbr)
def NBR_Landsat(image,dattype):
if (dattype == 'L5')|(dattype == 'L7'):
nbr = image.expression(
'(NIR - SWIR) / (NIR + SWIR)', {
'NIR': image.select('SR_B4'),
'SWIR': image.select('SR_B7')}).rename('nbr')
elif (dattype == 'L8')|(dattype == 'L9'):
nbr = image.expression(
'(NIR - SWIR) / (NIR + SWIR)', {
'NIR': image.select('SR_B5'),
'SWIR': image.select('SR_B7')}).rename('nbr')
else:
print('Incorrect Landsat sensor specified')
return(nbr)
def grid_footprint(footprint,nx,ny):
from shapely.geometry import Polygon, LineString, MultiPolygon
from shapely.ops import split
#polygon = footprint
polygon = Polygon(footprint['coordinates'][0])
#polygon = Polygon(footprint)
minx, miny, maxx, maxy = polygon.bounds
dx = (maxx - minx) / nx # width of a small part
dy = (maxy - miny) / ny # height of a small part
horizontal_splitters = [LineString([(minx, miny + i*dy), (maxx, miny + i*dy)]) for i in range(ny)]
vertical_splitters = [LineString([(minx + i*dx, miny), (minx + i*dx, maxy)]) for i in range(nx)]
splitters = horizontal_splitters + vertical_splitters
result = polygon
for splitter in splitters:
result = MultiPolygon(split(result, splitter))
coord_list = [list(part.exterior.coords) for part in result.geoms]
poly_list = []
for cc in coord_list:
p = ee.Geometry.Polygon(cc)
poly_list.append(p)
return(poly_list)
def apply_scale_factors(image):
opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2)
thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0)
return image.addBands(opticalBands, None, True).addBands(thermalBands, None, True)
#Landsat cloud mask from metadata
## Check this!!!
def get_cloud(img1):
### Change as of Oct 24, 2023: cloud shadow is too inaccurate, remove
### Though it is picking up topographic shadow. Questions!
# Bits 3 and 4 are cloud and cloud shadow, respectively.
#cloudShadowBitMask = (1 << 4)
cloudBitMask = (1 << 3)
# Get the pixel QA band.
qa = img1.select('QA_PIXEL')
#set both flags to 1
#clouds = qa.bitwiseAnd(cloudBitMask).eq(0).And(qa.bitwiseAnd(cloudShadowBitMask).eq(0)).rename('cloudmsk')
clouds = qa.bitwiseAnd(cloudBitMask).eq(0).rename('cloudmsk')
return(img1.addBands(clouds))
#TODO: add scene IDs! Check S2 cloud masks
searchd = {'Id':firenumber,'sensor':opt['dattype'],
'cld_pre':'','pre_T1':'','pre_T2':'',
'cld_post':'','post_T1':'','post_T2':'',
'pre_mosaic_date':'','pre_scenes':'',
'post_mosaic_date':'','post_scenes':''}
#firelist = [firenumber]
if opt['overrideflag']:
dattype = opt['override'][firenumber]['sensor']
else:
dattype = opt['dattype']
# Select data type, only SR as an option, may need to change
if dattype == 'S2':
col = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
print('Selected S2 SR')
elif dattype == 'L9':
if proc == 'TOA':
col = ee.ImageCollection("LANDSAT/LC09/C02/T1_TOA")
print('Selected L9 TOA')
else:
col = ee.ImageCollection('LANDSAT/LC09/C02/T1_L2')
print('Selected L9 SR')
elif dattype == 'L8':
if proc == 'TOA':
col = ee.ImageCollection("LANDSAT/LC08/C02/T1_TOA")
print('Selected L8 TOA')
else:
col = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
print('Selected L8 SR')
elif dattype == 'L5':
col = ee.ImageCollection("LANDSAT/LT05/C02/T1_L2")
print('Selected L5 SR')
elif dattype == 'L7':
col = ee.ImageCollection("LANDSAT/LE07/C02/T1_L2")
print('Selected L7 SR')
else:
print('wrong data type selected')
### Create folders
outfolder = os.path.join(outdir,firenumber)
if not os.path.exists(outfolder):
os.makedirs(outfolder)
######### Find pre-fire images
# TO DO: add an option for multiple date ranges
if opt['overrideflag']:
startdate = (datetime.strptime(opt['override'][firenumber]['pre_mosaic'],'%Y-%m-%d') + timedelta(days=-2)).strftime('%Y-%m-%d') ## for reruns
enddate = (datetime.strptime(opt['override'][firenumber]['pre_mosaic'],'%Y-%m-%d') + timedelta(days=2)).strftime('%Y-%m-%d') ## for reruns
else:
startdate = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['preT1']]
searchd[opt['preT1']] = startdate
enddate = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['preT2']]
searchd[opt['preT2']] = enddate
#print pre-fire search interval
print('Pre T1: ', startdate)
print('Pre T2: ', enddate)
# Search archive
cld =100 #cloud cover percentage
searchd['cld_pre'] = cld
if dattype.startswith('S2'):
before = col.filterDate(startdate,enddate).filterBounds(poly).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',cld))
elif dattype.startswith('L'):
before = col.filterDate(startdate,enddate).filterBounds(poly).filter(ee.Filter.lt('CLOUD_COVER',cld))
else:
pass
before_list = before.toList(1000)
if before_list.size().getInfo() == 0:
print('Zero before scenes were found! Rerun!')
#failed.append(firenumber)
# Create before mosaics
pre_mosaic_col = runDateMosaic(before_list)
#pre_mosaic_col_list = pre_mosaic_col.toList(1000)
# Ask server for individual scene metadata
metadata = before.getInfo()
# Turn metadata into table format
features = metadata['features']
out = []
for i in features:
d1 = pd.DataFrame([{'id':i['id']}])
p1 = pd.DataFrame([i['properties']])
t1 = d1.join(p1)
out.append(t1)
meta_df = pd.concat(out)
def strDate(string):
u_str = string.rsplit('_')[1].rsplit('T')[0]
s = u_str[0:4] + '-' + u_str[4:6] + '-' + u_str[6:8]
return(s)
#add date column
if dattype.startswith('S2'):
meta_df['date'] = meta_df['DATATAKE_IDENTIFIER'].apply(strDate)
else:
meta_df['date'] = meta_df['DATE_ACQUIRED']
outpath = os.path.join(outfolder,'pre_sceneMetadata.csv')
meta_df.to_csv(outpath)
#make a copy of meta_df
pre_meta_scenes = meta_df.copy()
# Ask server for mosaic metadata
#mosaic_meta = pre_mosaic_col.getInfo()
# Classify to get coverage and cloud extent, fix this to check if any bands are equal to 0
def classify_extent(img1):
if dattype.startswith('S2'):
classes = img1.expression("((B2 + B3 + B4) !=0) ? 1 "
": 0",{'B2': img1.select('B2'),
'B3': img1.select('B3'),
'B4': img1.select('B4')}).rename('c').clip(poly)
else:
classes = img1.expression("((B2 + B3 + B4) !=0) ? 1 "
": 0",{'B2': img1.select('SR_B2'),
'B3': img1.select('SR_B3'),
'B4': img1.select('SR_B4')}).rename('c').clip(poly)
return(classes)
pre_mosaic_extent = pre_mosaic_col.map(classify_extent).toBands()
def classify_cc(img1):
if dattype.startswith('S2'):
classes = img1.expression("(MSK_CLDPRB > 30) ? 1 "
": 0",{'MSK_CLDPRB': img1.select('MSK_CLDPRB')}).rename('c').clip(poly)
else:
classes = img1.expression("(cloudmsk == 1) ? 0 "
": 1",{'cloudmsk': img1.select('cloudmsk')}).rename('c').clip(poly)
return(classes)
if dattype.startswith('S2'):
pre_mosaic_cc = pre_mosaic_col.map(classify_cc).toBands()
aot = pre_mosaic_col.select('AOT').toBands().divide(1000)
reduced_mean_aot = aot.reduceRegion(reducer=ee.Reducer.mean(),geometry=poly.geometry(),maxPixels=100000000000,scale=30).getInfo()
else:
pre_mosaic_cloudmsk = pre_mosaic_col.map(get_cloud)
pre_mosaic_cc = pre_mosaic_cloudmsk.map(classify_cc).toBands()
#Calculate statistics, if the image is too big this may fail.
#This step causes problems sometimes due to maxPixels limits
reduced_sum = pre_mosaic_extent.reduceRegion(reducer=ee.Reducer.sum(),geometry=poly.geometry(),scale=30,maxPixels=100000000000).getInfo()
reduced_count = pre_mosaic_extent.reduceRegion(reducer=ee.Reducer.count(),geometry=poly.geometry(),maxPixels=100000000000,scale=30).getInfo()
reduced_sum_cc = pre_mosaic_cc.reduceRegion(reducer=ee.Reducer.sum(),geometry=poly.geometry(),maxPixels=100000000000,scale=30).getInfo()
reduced_count_cc = pre_mosaic_cc.reduceRegion(reducer=ee.Reducer.count(),geometry=poly.geometry(),maxPixels=100000000000,scale=30).getInfo()
print('Pre image statistics calculated')
#Rearrange and calculate percent coverage and percent cloud cover
#extent
df_sum = pd.DataFrame([reduced_sum]).T
df_sum.columns = ['sum']
df_count = pd.DataFrame([reduced_count]).T
df_count.columns = ['count']
df_perc = df_sum.join(df_count)
df_perc['percent_coverage'] = (df_perc['sum']/df_perc['count'])*100
#cloud cover
df_sum_cc = pd.DataFrame([reduced_sum_cc]).T
df_sum_cc.columns = ['sum_cc']
df_count_cc = pd.DataFrame([reduced_count_cc]).T
df_count_cc.columns = ['count_cc']
df_perc_cc = df_sum_cc.join(df_count_cc)
df_perc_cc['percent_cc'] = (df_perc_cc['sum_cc']/df_perc_cc['count_cc'])*100
#print(df_perc_cc)
if dattype.startswith('S'):
#aot
df_mean_aot = pd.DataFrame([reduced_mean_aot]).T
df_mean_aot.columns = ['mean_aot']
#join extent and cc
meta_df_ext_temp = df_perc.join(df_perc_cc)
#get rid of cc suffix
oldnames = meta_df_ext_temp.index
newnames = [s.rsplit('_')[0] for s in oldnames]
meta_df_ext_temp.index = newnames
#get rid of aot suffix
oldnames = df_mean_aot.index
newnames = [s.rsplit('_')[0] for s in oldnames]
df_mean_aot.index = newnames
meta_df_ext = meta_df_ext_temp.join(df_mean_aot)
#print(meta_df_ext)
else:
#join extent and cc
meta_df_ext = df_perc.join(df_perc_cc)
#get rid of cc suffix
oldnames = meta_df_ext.index
newnames = [s.rsplit('_')[0] for s in oldnames]
meta_df_ext.index = newnames
#get average scene cloud cover and join to mosaic metadata
if dattype.startswith('S2'):
pre_meta_scenes_cld = pre_meta_scenes.groupby('date')['CLOUDY_PIXEL_PERCENTAGE'].mean()
temp = pd.DataFrame(pre_meta_scenes_cld)
pre_meta_scenes_cld = temp.rename(columns={'date':'date','CLOUDY_PIXEL_PERCENTAGE':'percent_cc_scene'})
else:
pre_meta_scenes_cld = pre_meta_scenes.groupby('date')['CLOUD_COVER'].mean()
temp = pd.DataFrame(pre_meta_scenes_cld)
pre_meta_scenes_cld = temp.rename(columns={'CLOUD_COVER':'percent_cc_scene'})
meta_df_ext = meta_df_ext.join(pre_meta_scenes_cld)
outpath = os.path.join(outfolder,'pre_mosaicMetadata.csv')
meta_df_ext.to_csv(outpath)
#Finally! Select best pre-mosaic. Coverage >99% and least cloud cover
#full_cov = meta_df_ext.loc[(meta_df_ext['percent_coverage'] > 99)]
full_cov = meta_df_ext.loc[(meta_df_ext['percent_coverage'] == max(meta_df_ext['percent_coverage'])) | (meta_df_ext['percent_coverage'] > 99)]
# if max(meta_df_ext['percent_coverage']) < 90:
# raise Exception('No pre-fire scenes available with coverage >=90%')
# #pre_mosaic_date = full_cov['percent_cc'].idxmin()
# if min(full_cov['percent_cc']) > 10:
# raise Exception('No pre-fire scenes available with cloud cover <= 10%')
#if greater than 90% coverage not available print error and exit
if max(meta_df_ext['percent_coverage']) < 90:
if opt['overrideflag']:
print('Override selected. Warning! Pre-image has less than 90% coverage!')
pass
else:
raise Exception('No post-fire scenes available with coverage >=90%')
if min(full_cov['percent_cc']) > 10:
if opt['overrideflag']:
print('Override selected. Warning! Pre-image has more than 10% cloud cover!')
pass
else:
raise Exception('No pre-fire scenes available with cloud cover <= 10%')
#select by minimum scene cloud cover too
x = full_cov[full_cov['percent_cc'] == full_cov['percent_cc'].min()]
#post_mosaic_date = x['percent_cc_scene'].idxmin() #initially selected by scene cloud cover
print(x)
if dattype.startswith('S'):
pre_mosaic_date = x['mean_aot'].idxmin() #Aug 12, 2024 now selecting by lowest AOT
else:
#there's no AOT band in Landsat, could potentially use the haze QA band but that's presence/absence only
pre_mosaic_date = x['percent_cc_scene'].idxmin()
#select only mosaics that have greater >= 90% coverage AND < 20% cloud cover
pre_export_sub = meta_df_ext.loc[(meta_df_ext['percent_coverage'] >=90) & (meta_df_ext['percent_cc'] < 20)]
pre_export_sub_index = pre_export_sub.index.tolist()
pre_mosaic_col_export = pre_mosaic_col.filter(ee.Filter.inList('system:index',pre_export_sub_index))
print('Pre image date selected: ' + pre_mosaic_date)
######### Find post-fire images
# TO DO: add an option for multiple date ranges
if opt['overrideflag']:
startdate = (datetime.strptime(opt['override'][firenumber]['post_mosaic'],'%Y-%m-%d') + timedelta(days=-2)).strftime('%Y-%m-%d') ## for reruns
enddate = (datetime.strptime(opt['override'][firenumber]['post_mosaic'],'%Y-%m-%d') + timedelta(days=2)).strftime('%Y-%m-%d') ## for reruns
else:
startdate = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['postT1']]
searchd['post_T1'] = startdate
enddate = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['postT2']]
searchd['post_T2'] = enddate
print('Post T1: ', startdate)
print('Post T2: ', enddate)
# Search archive
cld = 100 #cloud cover percentage
searchd['cld_post'] = cld
if dattype.startswith('S2'):
after = col.filterDate(startdate,enddate).filterBounds(poly).filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',cld))
elif dattype.startswith('L'):
after = col.filterDate(startdate,enddate).filterBounds(poly).filter(ee.Filter.lt('CLOUD_COVER',cld))
else:
pass
after_list = after.toList(1000)
#print('# of after scenes: ' + str(after_list.size().getInfo())) #for debug
if after_list.size().getInfo() == 0:
#failed.append(firenumber)
print('Zero after scenes were found! Rerun!')
# Create before mosaics
post_mosaic_col = runDateMosaic(after_list)
#post_mosaic_col_list = post_mosaic_col.toList(1000)
# Ask server for individual scene metadata
metadata = after.getInfo()
# Turn metadata into table format
features = metadata['features']
out = []
for i in features:
d1 = pd.DataFrame([{'id':i['id']}])
p1 = pd.DataFrame([i['properties']])
t1 = d1.join(p1)
out.append(t1)
meta_df = pd.concat(out)
def strDate(string):
u_str = string.rsplit('_')[1].rsplit('T')[0]
s = u_str[0:4] + '-' + u_str[4:6] + '-' + u_str[6:8]
return(s)
#add date column
if dattype.startswith('S2'):
meta_df['date'] = meta_df['DATATAKE_IDENTIFIER'].apply(strDate)
else:
meta_df['date'] = meta_df['DATE_ACQUIRED']
outpath = os.path.join(outfolder,'post_sceneMetadata.csv')
meta_df.to_csv(outpath)
#make a copy of meta_df
post_meta_scenes = meta_df.copy()
# Ask server for mosaic metadata
#mosaic_meta = post_mosaic_col.getInfo()
# Classify to get coverage and cloud extent
post_mosaic_extent = post_mosaic_col.map(classify_extent).toBands()
if dattype.startswith('S2'):
post_mosaic_cc = post_mosaic_col.map(classify_cc).toBands()
aot = post_mosaic_col.select('AOT').toBands().divide(1000)
reduced_mean_aot = aot.reduceRegion(reducer=ee.Reducer.mean(),geometry=poly.geometry(),maxPixels=100000000000,scale=30).getInfo()
else:
post_mosaic_cloudmsk = post_mosaic_col.map(get_cloud)
post_mosaic_cc = post_mosaic_cloudmsk.map(classify_cc).toBands()
#Calculate statistics, if the image is too big this may fail
reduced_sum = post_mosaic_extent.reduceRegion(reducer=ee.Reducer.sum(),geometry=poly.geometry(),scale=30,maxPixels=100000000000).getInfo()
reduced_count = post_mosaic_extent.reduceRegion(reducer=ee.Reducer.count(),geometry=poly.geometry(),scale=30,maxPixels=100000000000).getInfo()
reduced_sum_cc = post_mosaic_cc.reduceRegion(reducer=ee.Reducer.sum(),geometry=poly.geometry(),scale=30,maxPixels=100000000000).getInfo()
reduced_count_cc = post_mosaic_cc.reduceRegion(reducer=ee.Reducer.count(),geometry=poly.geometry(),scale=30,maxPixels=100000000000).getInfo()
print('Post image statistics calculated')
#Rearrange and calculate percent coverage and percent cloud cover
#extent
df_sum = pd.DataFrame([reduced_sum]).T
df_sum.columns = ['sum']
df_count = pd.DataFrame([reduced_count]).T
df_count.columns = ['count']
df_perc = df_sum.join(df_count)
df_perc['percent_coverage'] = (df_perc['sum']/df_perc['count'])*100
#cloud cover
df_sum_cc = pd.DataFrame([reduced_sum_cc]).T
df_sum_cc.columns = ['sum_cc']
df_count_cc = pd.DataFrame([reduced_count_cc]).T
df_count_cc.columns = ['count_cc']
df_perc_cc = df_sum_cc.join(df_count_cc)
df_perc_cc['percent_cc'] = (df_perc_cc['sum_cc']/df_perc_cc['count_cc'])*100
if dattype.startswith('S'):
#aot
df_mean_aot = pd.DataFrame([reduced_mean_aot]).T
df_mean_aot.columns = ['mean_aot']
#join extent and cc
meta_df_ext_temp = df_perc.join(df_perc_cc)
#get rid of cc suffix
oldnames = meta_df_ext_temp.index
newnames = [s.rsplit('_')[0] for s in oldnames]
meta_df_ext_temp.index = newnames
#get rid of aot suffix
oldnames = df_mean_aot.index
newnames = [s.rsplit('_')[0] for s in oldnames]
df_mean_aot.index = newnames
meta_df_ext = meta_df_ext_temp.join(df_mean_aot)
#print(meta_df_ext)
else:
#join extent and cc
meta_df_ext = df_perc.join(df_perc_cc)
#get rid of cc suffix
oldnames = meta_df_ext.index
newnames = [s.rsplit('_')[0] for s in oldnames]
meta_df_ext.index = newnames
#get average scene cloud cover and join to mosaic metadata
if dattype.startswith('S2'):
post_meta_scenes_cld = post_meta_scenes.groupby('date')['CLOUDY_PIXEL_PERCENTAGE'].mean()
temp = pd.DataFrame(post_meta_scenes_cld)
post_meta_scenes_cld = temp.rename(columns={'date':'date','CLOUDY_PIXEL_PERCENTAGE':'percent_cc_scene'})
else:
post_meta_scenes_cld = post_meta_scenes.groupby('date')['CLOUD_COVER'].mean()
temp = pd.DataFrame(post_meta_scenes_cld)
post_meta_scenes_cld = temp.rename(columns={'CLOUD_COVER':'percent_cc_scene'})
meta_df_ext = meta_df_ext.join(post_meta_scenes_cld)
outpath = os.path.join(outfolder,'post_mosaicMetadata.csv') ## return this only if eval run
meta_df_ext.to_csv(outpath)
if opt['evalOnly']:
barc_filename=""
pre_sw_8bit_path=""
post_sw_8bit_path=""
pre_tc_8bit_path=""
post_tc_8bit_path=""
rlist=""
return(barc_filename,pre_sw_8bit_path,post_sw_8bit_path,pre_tc_8bit_path,post_tc_8bit_path,rlist)
else:
#Finally! Select best post-mosaic. Coverage >99% or maximum available coverage, and least cloud cover
full_cov = meta_df_ext.loc[(meta_df_ext['percent_coverage'] == max(meta_df_ext['percent_coverage'])) | (meta_df_ext['percent_coverage'] > 99)]
#full_cov.sort_index(inplace=True,ascending=False) #sort descending, to get most recent image, instead of getting most recent, now looking for least cloudy with scene meta
#test = os.path.join(outfolder,'post_mosaicMetadata_fullcov.csv') #debug
#full_cov.to_csv(test) #debug
#if greater than 90% coverage not available print error and exit
if max(meta_df_ext['percent_coverage']) < 90:
if opt['overrideflag']:
print('Override selected. Warning! Post-image has less than 90% coverage!')
pass
else:
raise Exception('No post-fire scenes available with coverage >=90%')
if min(full_cov['percent_cc']) > 20:
if opt['overrideflag']:
print('Override selected. Warning! Post-image has more than 20% cloud cover!')
pass
else:
raise Exception('No post-fire scenes available with cloud cover <= 20%')
#print('ignoring cloud cover cut off')
pass
#select by minimum scene cloud cover too
x = full_cov[full_cov['percent_cc'] == full_cov['percent_cc'].min()]
#post_mosaic_date = x['percent_cc_scene'].idxmin() #initially selected by scene cloud cover
if opt['postAOT']:
if dattype.startswith('S'):
post_mosaic_date = x['mean_aot'].idxmin() #Aug 12, 2024 now selecting by lowest AOT
else:
#there's no AOT band in Landsat, could potentially use the haze QA band but that's presence/absence only
post_mosaic_date = x['percent_cc_scene'].idxmin()
else:
post_mosaic_date = x.index.max() #selecting by most recent instead
print(x)
#select only mosaics that have greater >= 90% coverage AND < 10% cloud cover
post_export_sub = meta_df_ext.loc[(meta_df_ext['percent_coverage'] >=90) & (meta_df_ext['percent_cc'] < 20)]
post_export_sub_index = post_export_sub.index.tolist()
post_mosaic_col_export = post_mosaic_col.filter(ee.Filter.inList('system:index',post_export_sub_index))
print('Post image selected: ' + post_mosaic_date)
#add pre and post images to the txt file
# if dattype.startswith('S2'):
# pre_scenes_info = pre_meta_scenes.loc[pre_meta_scenes['date'] == pre_mosaic_date]['PRODUCT_ID'].tolist()
# post_scenes_info = post_meta_scenes.loc[post_meta_scenes['date'] == post_mosaic_date]['PRODUCT_ID'].tolist()
# else:
# pre_scenes_info = pre_meta_scenes.loc[pre_meta_scenes['date'] == pre_mosaic_date]['LANDSAT_SCENE_ID'].tolist()
# post_scenes_info = post_meta_scenes.loc[post_meta_scenes['date'] == post_mosaic_date]['LANDSAT_SCENE_ID'].tolist()
pre_scenes_info = pre_meta_scenes.loc[pre_meta_scenes['date'] == pre_mosaic_date]['system:index'].tolist()
post_scenes_info = post_meta_scenes.loc[post_meta_scenes['date'] == post_mosaic_date]['system:index'].tolist()
#check if over-riding automatic selection
if opt['overrideflag']:
print('Overriding')
pre_mosaic_date = opt['override'][firenumber]['pre_mosaic'] ## for reruns
post_mosaic_date = opt['override'][firenumber]['post_mosaic'] ## for reruns
else:
pass
print('Calculating NBR')
#select pre-image and post-image
pre_col = pre_mosaic_col.filter(ee.Filter.inList("system:index",ee.List([pre_mosaic_date])))
if dattype.startswith('S2'):
pre_img = ee.Image(pre_col.toList(1).get(0)).multiply(0.0001)
else:
#TODO: no scale factors for TOA
pre_img = apply_scale_factors(ee.Image(pre_col.toList(1).get(0)))
post_col = post_mosaic_col.filter(ee.Filter.inList("system:index",ee.List([post_mosaic_date])))
if dattype.startswith('S2'):
post_img = ee.Image(post_col.toList(1).get(0)).multiply(0.0001)
else:
#TODO: no scale factors for TOA
post_img = apply_scale_factors(ee.Image(post_col.toList(1).get(0)))
#clip to boundary
#pre_img_c = pre_img.clip(poly)
#post_img_c = post_img.clip(poly)
#TODO: remove clipping here
pre_img_c = pre_img
post_img_c = post_img
#calculate NBR
if dattype.startswith('S2'):
pre_nbr = NBR_S2(pre_img_c)
post_nbr = NBR_S2(post_img_c)
else:
pre_nbr = NBR_Landsat(pre_img_c,dattype)
post_nbr = NBR_Landsat(post_img_c,dattype)
#calculate dNBR
print('Creating BARC map')
dNBR = pre_nbr.subtract(post_nbr).rename('dNBR')
#scale dNBR
dNBR_scaled = dNBR.expression('(dNBR * 1000 + 275)/5',{'dNBR': dNBR.select('dNBR')}).rename('dNBR_scaled')
classes = dNBR_scaled.expression("(dNBR_scaled >= 187) ? 4 "
": (dNBR_scaled >= 110) ? 3 "
": (dNBR_scaled >= 76) ? 2 "
": 1",{'dNBR_scaled': dNBR_scaled.select('dNBR_scaled')})
print('Applying cloud mask if necessary')
#Grab pre and post image cloud masks
cm = pre_mosaic_date + '_c'
pre_img_cloudmsk = pre_mosaic_cc.select([cm]).Not().clip(poly)
cm = post_mosaic_date + '_c'
post_img_cloudmsk = post_mosaic_cc.select([cm]).Not().clip(poly)
#Union masks and apply to classes
comb_cloudmsk = pre_img_cloudmsk.multiply(post_img_cloudmsk)
#clip, remap 0 to 9 and set 9 to NoData upon export
classes_clipped_nodata = classes.clip(poly).remap([0,1,2,3,4],[9,1,2,3,4])
mask_clouds = opt['mask_clouds']
if mask_clouds:
classes_clipped_export = classes_clipped_nodata.multiply(comb_cloudmsk) #0 is cloudmasked, or unknown
else:
classes_clipped_export = classes_clipped_nodata
#get stats
#outcsv = os.path.join(outfolder,'barc_percent.csv')
#geemap.zonal_statistics_by_group(classes_clipped_export,poly.geometry(),outcsv,statistics_type='PERCENTAGE')
roi = poly.geometry()
if not os.path.exists(outfolder):
os.makedirs(outfolder)
print('Beginning image export')
#get dates
pre_date = pre_mosaic_date.replace('-','')
post_date = post_mosaic_date.replace('-','')
if dattype.startswith('S2'):
px = 20 #20 for S2
else:
px = 30 #30 for landsat
## Define tiling rules
poly_area = fires_df[fires_df[opt['fn']] == firenumber].iloc[0][opt['areaha']]
print('Fire Area: ' + str(poly_area))
if poly_area < 10000:
n = 2
elif poly_area > 10000 and poly_area < 100000:
n = 3
elif poly_area > 100000 and poly_area < 400000:
n = 4
else:
n = 5
print('Number of tiles: ' + str(n*n))
#export pre and post rgbs, tile to avoid pixel limit issues.
footprint = poly.geometry().bounds().getInfo()
grids = grid_footprint(footprint,n,n) #3,3 works for a fire that's ~90 000 ha large, if larger, increase the number of tiles
##debug export extent image
#filename = os.path.join(outfolder,'extent_raster.tif')
#geemap.ee_export_image(post_mosaic_extent.clip(footprint), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
for i in range(0,len(grids)):
roi = grids[i]
## Export BARC
barc_folder = os.path.join(outfolder,'barc')
if not os.path.exists(barc_folder):
os.makedirs(barc_folder)
name = 'BARC_' + firenumber + '_' + pre_date + '_' + post_date + '_' + dattype +'_' + str(i) + '_.tif'
barc_filename = os.path.join(barc_folder,name)
geemap.ee_export_image(classes_clipped_export.unmask(9).clip(roi), filename=barc_filename, scale=px, file_per_band=False,crs='EPSG:3005')
ras = gdal.Open(barc_filename,GA_Update)
dat = ras.GetRasterBand(1)
dat.SetNoDataValue(9)
ras = None
dat = None
## Export cloudmasks
pre_cloud_mask_folder = os.path.join(outfolder,'pre_cloud_mask')
if not os.path.exists(pre_cloud_mask_folder):
os.makedirs(pre_cloud_mask_folder)
filename = os.path.join(pre_cloud_mask_folder,pre_date + '_cloudmsk_' + str(i) + '.tif')
geemap.ee_export_image(pre_img_cloudmsk.unmask(9).clip(roi), filename=filename, scale=px, file_per_band=False,crs='EPSG:3005')
ras = gdal.Open(filename,GA_Update)
dat = ras.GetRasterBand(1)
dat.SetNoDataValue(9)
ras = None
dat = None
post_cloud_mask_folder = os.path.join(outfolder,'post_cloud_mask')
if not os.path.exists(post_cloud_mask_folder):
os.makedirs(post_cloud_mask_folder)
filename = os.path.join(post_cloud_mask_folder,post_date + '_cloudmsk_' + str(i) + '.tif')
geemap.ee_export_image(post_img_cloudmsk.unmask(9).clip(roi), filename=filename, scale=px, file_per_band=False,crs='EPSG:3005')
ras = gdal.Open(filename,GA_Update)
dat = ras.GetRasterBand(1)
dat.SetNoDataValue(9)
ras = None
dat = None
combined_cloud_mask_folder = os.path.join(outfolder,'comb_cloud_mask')
if not os.path.exists(combined_cloud_mask_folder):
os.makedirs(combined_cloud_mask_folder)
filename = os.path.join(combined_cloud_mask_folder,pre_date + '_' + post_date + '_comb_cloudmsk_' + str(i) +'.tif')
geemap.ee_export_image(comb_cloudmsk.unmask(9).clip(roi), filename=filename, scale=px, file_per_band=False,crs='EPSG:3005')
ras = gdal.Open(filename,GA_Update)
dat = ras.GetRasterBand(1)
dat.SetNoDataValue(9)
ras = None
dat = None
## Export 8-bit truecolor images
#pre, truecolor
pre_tc_8bit = os.path.join(outfolder,'pre_truecolor_8bit')
if not os.path.exists(pre_tc_8bit):
os.makedirs(pre_tc_8bit)
filename = os.path.join(pre_tc_8bit, dattype + '_' + pre_date + '_truecolor_pre_8bit_' + str(i) + '.tif')
pre_tc_8bit_path = filename
if dattype.startswith('S2'):
viz = {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=10, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L8') | (dattype == 'L9'):
viz = {'bands': ['SR_B4', 'SR_B3', 'SR_B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L5') | (dattype == 'L7'):
viz = {'bands': ['SR_B3','SR_B2','SR_B1'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
else:
pass
post_tc_8bit = os.path.join(outfolder,'post_truecolor_8bit')
if not os.path.exists(post_tc_8bit):
os.makedirs(post_tc_8bit)
filename = os.path.join(post_tc_8bit, dattype + '_' + post_date + '_truecolor_post_8bit_' + str(i) + '.tif')
post_tc_8bit_path = filename
if dattype.startswith('S2'):
viz = {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=10, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L8') | (dattype == 'L9'):
viz = {'bands': ['SR_B4', 'SR_B3', 'SR_B2'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L5') | (dattype == 'L7'):
viz = {'bands': ['SR_B3','SR_B2','SR_B1'],'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
else:
pass
## Export swir too
pre_sw_8bit = os.path.join(outfolder,'pre_swir_8bit')
if not os.path.exists(pre_sw_8bit):
os.makedirs(pre_sw_8bit)
filename = os.path.join(pre_sw_8bit, dattype + '_' + pre_date + '_swir_pre_8bit_' + str(i) + '.tif')
pre_sw_8bit_path = filename
if dattype.startswith('S2'):
viz = {'bands': ['B12', 'B8', 'B4'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=10, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L8') | (dattype == 'L9'):
viz = {'bands': ['SR_B6', 'SR_B5', 'SR_B4'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L5') | (dattype == 'L7'):
viz = {'bands': ['SR_B5','SR_B4','SR_B3'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(pre_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
else:
pass
post_sw_8bit = os.path.join(outfolder,'post_swir_8bit')
if not os.path.exists(post_sw_8bit):
os.makedirs(post_sw_8bit)
filename = os.path.join(post_sw_8bit, dattype + '_' + post_date + '_swir_post_8bit_' + str(i) + '.tif')
post_sw_8bit_path = filename
if dattype.startswith('S2'):
viz = {'bands': ['B12', 'B8', 'B4'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=10, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L8') | (dattype == 'L9'):
viz = {'bands': ['SR_B6', 'SR_B5', 'SR_B4'], 'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
elif (dattype == 'L5') | (dattype == 'L7'):
viz = {'bands': ['SR_B5','SR_B4','SR_B3'],'min': 0, 'max':0.3,'gamma':1.5}
geemap.ee_export_image(post_img.clip(roi).visualize(**viz), filename=filename, scale=30, file_per_band=False,crs='EPSG:3005')
else:
pass
print(barc_folder)
#mosaic all
#BARC
barc_list = getfiles(barc_folder,'.tif')
outfilename = 'BARC_' + firenumber + '_' + pre_date + '_' + post_date + '_' + dattype + '.tif'
out = os.path.join(barc_folder,outfilename)
gdal.Warp(out,barc_list)
for file in barc_list: os.remove(file) #delete tiles
barc_filename = out #to return from the function
print('Barc mosaic complete')
# ## cloud masks
#pre
pre_cc_list = getfiles(pre_cloud_mask_folder,'.tif')
outfilename = pre_date + '_cloudmsk.tif'
out = os.path.join(pre_cloud_mask_folder,outfilename)
gdal.Warp(out,pre_cc_list)
for file in pre_cc_list: os.remove(file) #delete tiles
#post
post_cc_list = getfiles(post_cloud_mask_folder,'.tif')
outfilename = post_date + '_cloudmsk.tif'
out = os.path.join(post_cloud_mask_folder,outfilename)
gdal.Warp(out,post_cc_list)
for file in post_cc_list: os.remove(file) #delete tiles
#combined
comb_list = getfiles(combined_cloud_mask_folder,'.tif')
outfilename = pre_date + '_' + post_date + '_comb_cloudmsk.tif'
out = os.path.join(combined_cloud_mask_folder,outfilename)