-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFFMT-GEE-Code
2137 lines (1744 loc) · 83.9 KB
/
FFMT-GEE-Code
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
///// ********************************************************************************************************************* /////
///// App Name: Multi-Source and Multi-Temporal Google Earth Engine App for Emergency Flood Mapping /////
///// /////
///// This App created by Ebrahim Hamidi, Ph.D candidate at the University of Alabama and reviewed by /////
///// Brad G. Peter, Assistant Professor, Department of Geosciences, University of Arkansas. /////
///// /////
///// This GEE App partioally funded by CUAHSI Hydroinformatics Innovation Fellowship (HIF) program in 2023. /////
///// /////
///// /////
///// This project aims to monitor global scale flood extents by developing a user-friendly Google Earth Engine (GEE) App. /////
///// The product of this study will help emergency responders as well as the scientific community with rapid and reliable /////
///// flood inundation information and improves the current methods of flood mapping. /////
///// ********************************************************************************************************************* /////
/// *** Drawing tool preparation *** ///
var drawingTools = Map.drawingTools();
drawingTools.setShown(false);
while (drawingTools.layers().length() > 0) {
var layer = drawingTools.layers().get(0);
drawingTools.layers().remove(layer);
}
var dummyGeometry =
ui.Map.GeometryLayer({geometries: null, name: 'geometry', color: '23cba7'});
drawingTools.layers().add(dummyGeometry);
function clearGeometry() {
var layers = drawingTools.layers();
layers.get(0).geometries().remove(layers.get(0).geometries().get(0));
}
function drawRectangle() {
clearGeometry();
drawingTools.setShape('rectangle');
drawingTools.draw();
}
function drawPolygon() {
clearGeometry();
drawingTools.setShape('polygon');
drawingTools.draw();
}
/// *** Get the geometry from the drawn tools *** ///
var aoi = drawingTools.layers().get(0).getEeObject();
clearGeometry();
/// *** Map floods based on the user defined threshold value *** ///
function sarFloodMapper(aoi) {
Map.clear()
// Set the drawing mode back to null; turns drawing off.
drawingTools.setShape(null);
/// *** Get the date and indices thrshold information from user panel interface *** ///
var startDay = app.startDateRange.startBoxDay.getValue()
var startMonth = app.startDateRange.startBoxMonth.getValue()
var startYear = app.startDateRange.startBoxYear.getValue()
var endDay = app.endDateRange.endBoxDay.getValue()
var endMonth = app.endDateRange.endBoxMonth.getValue()
var endYear = app.endDateRange.endBoxYear.getValue()
var lcluSelected = app.lcluSelect.lclu_info.getValue();
/// *** Check days and months information *** ///
var missDate_error = ui.Panel({
widgets: [
ui.Label({value: 'Error: Unfiled date period!', style: {fontWeight: '500', fontSize: '24px', color:'crimson' , margin: '3px 3px 3px 3px'}}),
],
style: {
position: 'top-center',
width: '315px',
backgroundColor: 'white',
border: '3px solid gray'
}
})
var missDateError = "off"
if (startDay == undefined || startMonth == undefined || startYear == undefined || endDay == undefined || endMonth == undefined || endYear == undefined || startDay == "" || startMonth == "" || startYear == "" || endDay == "" ||endMonth == "" || endYear == "") {
var text_error_1 = ui.Label('The flood event period input date is missing. Please fill all the date boxes to ensure accurate data."', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
missDate_error.add(ui.Panel([text_error_1]))
var text_error_2 = ui.Label('For example, for the Hurricane Harvey flood event in Galveston Bay, the period could be defined:', {fontSize: '14px', color:'1928E1', margin: '1px 3px 3px 10px'});
var text_error_3 = ui.Label('From: "25-08-2017"', {fontSize: '14px', color:'7F8087', margin: '1px 3px 3px 10px'});
var text_error_4 = ui.Label('To: "10-09-2017"', {fontSize: '14px', color:'7F8087', margin: '1px 3px 3px 10px'});
missDate_error.add(ui.Panel([text_error_2, text_error_3, text_error_4]))
missDateError = "on"
}
if (missDateError == "on"){
Map.add(missDate_error)
}
var dateStart = ee.Number.parse(startDay).getInfo()
var monthStart = ee.Number.parse(startMonth).getInfo()
var yearStart = ee.Number.parse(startYear).getInfo()
var dateEnd = ee.Number.parse(endDay).getInfo()
var monthEnd = ee.Number.parse(endMonth).getInfo()
var yearEnd = ee.Number.parse(endYear).getInfo()
var RefDateStart = 01
var RefStartDay = app.refStartDateRange.refStartBoxDay.getValue()
if (RefStartDay != undefined) {
if (RefStartDay != "") {
RefDateStart = ee.Number.parse(RefStartDay).getInfo()
}
}
var RefMonthStart = 06
var RefStartMonth = app.refStartDateRange.refStartBoxMonth.getValue()
if (RefStartMonth != undefined) {
if (RefStartMonth != "") {
RefMonthStart = ee.Number.parse(RefStartMonth).getInfo()
}
}
var RefYearStart = 2017
var RefStartYear = app.refStartDateRange.refStartBoxYear.getValue()
if (RefStartYear != undefined) {
if (RefStartYear != "") {
RefYearStart = ee.Number.parse(RefStartYear).getInfo()
}
}
var RefDateEnd = 15
var RefEndDay = app.refEndDateRange.refEndBoxDay.getValue()
if (RefEndDay != undefined) {
if (RefEndDay != "") {
RefDateEnd = ee.Number.parse(RefEndDay).getInfo()
}
}
var RefMonthEnd = 06
var RefEndMonth = app.refEndDateRange.refEndBoxMonth.getValue()
if (RefEndMonth != undefined) {
if (RefEndMonth != "") {
RefMonthEnd = ee.Number.parse(RefEndMonth).getInfo()
}
}
var RefYearEnd = 2017
var RefEndYear = app.refEndDateRange.refEndBoxYear.getValue()
if (RefEndYear != undefined) {
if (RefEndYear != "") {
RefYearEnd = ee.Number.parse(RefEndYear).getInfo()
}
}
var userDefinedNDFIThre = 1.5
var userThreNDFI = app.threValue.threBoxNDFI.getValue()
if (userThreNDFI != undefined) {
if (userThreNDFI != "") {
userDefinedNDFIThre = ee.Number.parse(userThreNDFI).getInfo()
}
}
var userDefinedDIIThre = 1.5
var userThreDII = app.threValue.threBoxDII.getValue()
if (userThreDII != undefined) {
if (userThreDII != "") {
userDefinedDIIThre = ee.Number.parse(userThreDII).getInfo()
}
}
var userDefinedMNDWIThre = 0.4
var userThreMNDWI = app.threValue.threBoxMNDWI.getValue()
if (userThreMNDWI != undefined) {
if (userThreMNDWI != "") {
userDefinedMNDWIThre = ee.Number.parse(userThreMNDWI).getInfo()
}
}
/// *** Date set up from the the user panel interface information *** ///
var start = yearStart + '-'+ monthStart + '-'+ dateStart
var end = yearEnd + '-' + monthEnd + '-'+ dateEnd
var errors = ui.Panel({
widgets: [
ui.Label({value: 'Error: Incorrect Input Date!', style: {fontWeight: '500', fontSize: '24px', color:'crimson' , margin: '3px 3px 3px 3px'}}),
],
style: {
position: 'top-center',
width: '315px',
backgroundColor: 'white',
border: '3px solid gray'
}
})
var dateError = "off"
var currentyear = ee.Number.parse(ee.Date(Date.now()).get('year'))
currentyear = ee.Number.parse(ee.String(currentyear))
if (yearStart < 2014 || yearStart > currentyear || yearStart == "") {
var text_error_1 = ui.Label('* Start year value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
if (yearEnd < 2014 || yearEnd > currentyear) {
var text_error_1 = ui.Label('* End year value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
if (monthStart < 1 || monthStart > 12) {
var text_error_1 = ui.Label('* Start month value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
if (monthEnd < 1 || monthEnd > 12) {
var text_error_1 = ui.Label('* End month value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
if (dateStart < 1 || dateStart > 31) {
var text_error_1 = ui.Label('* Start day value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
else {
if (monthStart == 2) {
if (dateStart > 28) {
var text_error_1 = ui.Label('* Start day value error. The input month has 28 days.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
}
if (monthStart == 4 || monthStart == 6 || monthStart == 9 || monthStart == 11) {
if (dateStart > 30) {
var text_error_1 = ui.Label('* Start day value error. The input month has 30 days.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
}
}
if (dateEnd < 1 || dateEnd > 31) {
var text_error_1 = ui.Label('* End day value error.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
else {
if (monthEnd == 2) {
if (dateEnd > 28) {
var text_error_1 = ui.Label('* End day value error. The input month has 28 days.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
}
if (monthEnd == 4 || monthEnd == 6 || monthEnd == 9 || monthEnd == 11) {
if (dateEnd > 30) {
var text_error_1 = ui.Label('* End day value error. The input month has 30 days.', {fontSize: '16px', color:'1928E1', margin: '1px 3px 3px 10px'});
errors.add(ui.Panel([text_error_1]))
dateError = "on"
}
}
}
if (dateError == "on"){
Map.add(errors)
}
/// *** Referenced Date set up from the the user panel interface information *** ///
var refStart = RefYearStart + '-'+ RefMonthStart + '-'+ RefDateStart
var refEnd = RefYearEnd + '-' + RefMonthEnd + '-'+ RefDateEnd
/// *** Define area of interest *** ///
var bounds = aoi//ee.Geometry
drawingTools.setShown(false);
clearGeometry();
/// *** Set the date and indices thrshold information from user panel interface *** ///
// [before_start, before_end, after_start, after_end, user_defined_SAR_indices_thre, mndwi_threshold]
// var params = ['2017-06-01', '2017-06-15', start, end, userDefinedNDFIThre, userDefinedDIIThre, userDefinedMNDWIThre]
var params = [refStart, refEnd, start, end, userDefinedNDFIThre, userDefinedDIIThre, userDefinedMNDWIThre]
// SAR Input Data
var before_start = params[0]
var before_end = params[1]
var after_start = params[2]
var after_end = params[3]
var polarization = "VH"
var pass_direction = "ASCENDING"
// User defined k threshols values
var k_ndfi = params[4]
var k_dii = params[5]
// MNDWI flooded pixels Threshold Criteria
var mndwi_threshold = params[6]
// Datasets -----------------------------------
var dem = ee.Image("NASA/NASADEM_HGT/001").select('elevation')
var slope = ee.Terrain.slope(dem)
var swater = ee.Image('JRC/GSW1_0/GlobalSurfaceWater').select('seasonality')
var water_mask = swater
var collection = ee.ImageCollection('COPERNICUS/S1_GRD')
.filter(ee.Filter.eq('instrumentMode', 'IW'))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', polarization))
.filter(ee.Filter.eq('orbitProperties_pass', pass_direction))
.filter(ee.Filter.eq('resolution_meters', 10))
.filterBounds(bounds)
.select(polarization)
var before = collection.filterDate(before_start, before_end)
var after = collection.filterDate(after_start, after_end)
print("Sentinel-1 GRD Before", before)
print("Sentinel-1 GRD After", after)
// Generating Reference and Flood Multi-temporal SAR Data ------------------------
var mean_before = before.mean().clip(bounds)
var min_after = after.min().clip(bounds)
// Caculate NDFI ------------------------
var mean_before_abs = mean_before.abs()
var min_after_abs = min_after.abs()
var ndfi = mean_before_abs.subtract(min_after_abs).divide(mean_before_abs.add(min_after_abs)).rename('NDFI')
var ndfi_filtered = ndfi.focal_mean({radius: 50, kernelType: 'circle', units: 'meters'})
// NDFI Normalization -----------------------
var ndfi_min = ndfi_filtered.reduceRegion({
reducer: ee.Reducer.min(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var ndfi_max = ndfi_filtered.reduceRegion({
reducer: ee.Reducer.max(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var ndfi_rang = ee.Number(ndfi_max.get('NDFI')).subtract(ee.Number(ndfi_min.get('NDFI')))
var ndfi_subtctMin = ndfi_filtered.subtract(ee.Number(ndfi_min.get('NDFI')))
var ndfi_norm = ndfi_subtctMin.divide(ndfi_rang)
// NDFI Thresholding ------------------------
var ndfi_mean = ndfi_norm.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var ndfi_std = ndfi_norm.reduceRegion({
reducer: ee.Reducer.stdDev(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var ndfi_th = ee.Number(ndfi_mean.get('NDFI')).subtract(ee.Number(k_ndfi).multiply(ee.Number(ndfi_std.get('NDFI'))))
print('NDFI Threshold', ndfi_th)
// Apply Thresholding Value on NDFI
ndfi_filtered = ndfi_norm.lt(ndfi_th)
// NDFI Masking -------------------------------------
var swater_mask = swater.gte(4)
swater_mask = swater.mask().where(swater_mask.eq(0),0)
var slope_mask = slope.lt(5)
var swater_clip = swater_mask.updateMask(swater_mask.eq(1)).clip(bounds)
var ndfi_flooded_masked = ndfi_filtered
.updateMask(ndfi_filtered.eq(1))
.updateMask(swater_mask.eq(0))
.updateMask(slope_mask.eq(1))
var connections = ndfi_flooded_masked.connectedPixelCount().gte(25)
var ndfi_flood = ndfi_flooded_masked.updateMask(connections.eq(1))
//------------------------------------------------------------------------
// Caculate NDFI ------------------------
var dii_image = min_after.abs().subtract(mean_before.abs())
var dii_image_filtered = dii_image.focal_mean({radius: 50, kernelType: 'circle', units: 'meters'})
// DII Normalization
var dii_image_min = dii_image_filtered.reduceRegion({
reducer: ee.Reducer.min(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var dii_image_max = dii_image_filtered.reduceRegion({
reducer: ee.Reducer.max(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var dii_image_rang = ee.Number(dii_image_max.get('VH')).subtract(ee.Number(dii_image_min.get('VH')))
var dii_image_subtctMin = dii_image_filtered.subtract(ee.Number(dii_image_min.get('VH')))
var dii_image_norm = dii_image_subtctMin.divide(dii_image_rang)
if (app.checkbox_2.imagehistogram.getValue() === true) {
// Histogram chart properties
var histogramPanel = ui.Panel({
style:
{height: '235px', width: '350px', position: 'bottom-right', shown: false}
})
Map.add(histogramPanel);
if (!histogramPanel.style().get('shown')) {
histogramPanel.style().set('shown', true);
}
// Desplay histograms
var histogram
= ui.Chart.image.histogram({ image: ndfi_norm.addBands(dii_image_norm), region: bounds, scale: 10, maxPixels: 1e13})
.setSeriesNames(['NDFI', 'DII'])
.setOptions({
title: 'SAR Indices Histogram',
hAxis: {
title: 'SAR Pixel Value',
titleTextStyle: {italic: false, bold: true},
},
vAxis:
{title: 'Frequency', titleTextStyle: {italic: false, bold: true}},
colors: ['e8b807', '24d6e8']
});
histogramPanel.widgets().reset([histogram])
}
// DII Thresholding ------------------------
var dii_image_mean = dii_image_norm.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var dii_image_std = dii_image_norm.reduceRegion({
reducer: ee.Reducer.stdDev(),
geometry: bounds,
scale: 10,
maxPixels: 1e13
})
var dii_image_th = ee.Number(dii_image_mean.get('VH')).add(ee.Number(k_dii).multiply(ee.Number(dii_image_std.get('VH'))))
print('dii_image_th = ', dii_image_th)
// Apply Thresholding on DII
dii_image_filtered = dii_image_norm.gt(dii_image_th)
// DII Masking -------------------------------------
var dii_image_masked = dii_image_filtered
.updateMask(dii_image_filtered.eq(1))
.updateMask(swater_mask.eq(0))
.updateMask(slope_mask.eq(1))
var dii_image_connections = dii_image_masked.connectedPixelCount().gte(25)
dii_image_masked = dii_image_masked.updateMask(dii_image_connections.eq(1))
var dii_image_flood = dii_image_masked.updateMask(dii_image_masked.eq(1))
/// *** Validation Using Sentinel-2 Surface Reflectance Imagery Data *** ///
var sentinel2_before = ee.ImageCollection("COPERNICUS/S2").filterBounds(bounds).filterDate(before_start, before_end)
var sentinel2_after = ee.ImageCollection("COPERNICUS/S2").filterBounds(bounds).filterDate(after_start, after_end)
var sentinel2_before_mosaic = sentinel2_before.mosaic().clip(bounds)
var sentinel2_after_mosaic = sentinel2_after.mosaic().clip(bounds)
print("Sentinel-2 Before", sentinel2_before)
print("Sentinel-2 After", sentinel2_after)
// Cloud Cover Masks
var qa = sentinel2_after_mosaic.select('QA60')
var radix = 2
var opaqueBit = 10
var cirrusBit = 11
var clouds_1 = qa.bitwiseAnd(Math.pow(radix,opaqueBit)).neq(0).rename('opaque')
var clouds_2 = qa.bitwiseAnd(Math.pow(radix,cirrusBit)).neq(0).rename('cirrus')
var all_clouds = clouds_1.add(clouds_2).gt(0)
var cloudsMasked = sentinel2_after_mosaic.updateMask(all_clouds.eq(0))
// Calculating MNDWI from optical imagery
var green = cloudsMasked.select('B3')
var swir1 = cloudsMasked.select('B11')
var mndwi = green.subtract(swir1).divide(green.add(swir1)).rename('MNDWI')
print(mndwi,"mndwimndwi")
var mndwi_filtered = mndwi.gt(mndwi_threshold)
var mndwi_masking = mndwi_filtered
.updateMask(swater_mask.eq(0))
.updateMask(mndwi_filtered.eq(1))
var mndwi_connections = mndwi_masking.connectedPixelCount().gte(25)
var mndwi_flood = mndwi_filtered.updateMask(mndwi_connections.eq(1))
print(mndwi,"mndwi_floodmndwi_flood")
// Combined NDFI and DII flood extents -----------------------------------
var combined_ndfi_dii = ndfi_flood.mask().add(dii_image_flood.mask()).gt(0)
var combined_ndfi_dii = combined_ndfi_dii.updateMask(combined_ndfi_dii.eq(1))
// Combined NDFI, DII and MNDWI (optical) flood extents -----------------------------------
var combined_ndfi_dii_MNDWI = combined_ndfi_dii.mask().add(mndwi_flood.mask()).gt(0)
var combined_ndfi_dii_MNDWI = combined_ndfi_dii_MNDWI.updateMask(combined_ndfi_dii_MNDWI.eq(1))
// Display the maps --------------------------------------------------------------------------------
Map.addLayer(mean_before, {min: -29, max: -9, palette: []}, "SAR Image Before Flood (Mean)", 0)
Map.addLayer(min_after, {min: -29, max: -12, palette: []}, "SAR Image After Flood (Min)", 1)
if (app.checkbox_7.displayNDFIandDIIimage.getValue() === true) {
Map.addLayer(ndfi_norm, {min: 0, max: 1, palette: []}, "NDFI Image", 0)
Map.addLayer(dii_image_norm, {min: 0, max: 1, palette: []}, "DII Image", 0)
}
if (app.checkbox_1.calibration.getValue() === true) {
Map.addLayer(sentinel2_after_mosaic, {bands:['B4','B3','B2'], min: 350, max: 1500}, 'Optical Image After Flood',0)
Map.addLayer(mndwi_flood, {palette: 'e4156b'}, "Optical MNDWI Flood", 0)
}
Map.addLayer(swater_clip, {palette: ['#f6adff']}, "Open Waters", 0)
if (app.checkbox_3.displayNDFIandDIIflood.getValue() === true) {
Map.addLayer(ndfi_flood, {palette: 'fbc708'}, 'NDFI Flood',0)
Map.addLayer(dii_image_flood, {palette: '24d6e8'}, 'DII Flood',0)
}
Map.addLayer(combined_ndfi_dii, {palette: '56ff6b'}, "Combined NDFI & DII Flood", 1)
Map.setOptions('HYBRID')
Map.centerObject(bounds)
// function downloadImg() {
if (app.checkbox_4.getDownloadLink.getValue() === true) {
var viewBounds = bounds;
var downloadArgs = {
name: 'combined_ndfi_dii',
crs: 'EPSG:5070',
scale: 30,
region: viewBounds.toGeoJSONString()
};
var url = combined_ndfi_dii.getDownloadURL(downloadArgs);
var textstyle = {
'fontSize':'12px',
'fontWeight':'bold'
};
var urlDownloadLabel = ui.Label('Click to Download Merged NDFI&DII Flood Map', textstyle);
urlDownloadLabel.setUrl(url);
urlDownloadLabel.style().set({shown: true});
panelDownload.add(ui.Panel([
urlDownloadLabel
]))
Map.add(panelDownload)
}
/// *** Extract information from the calculated flood extent maps *** ///
// Calculate area of flood extent
var flood_pixel_area = combined_ndfi_dii.multiply(ee.Image.pixelArea());
var flooded_area_sqm = flood_pixel_area.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 10,
bestEffort: true
});
// Convert flooded extent from m^2 to km^2
var flooded_area_sqkm = flooded_area_sqm
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
/// *** Calculate affected Land cover and land use using using "NLCD 2019: USGS National Land Cover Database" ***///
if (lcluSelected == "USA") {
var dataset = ee.ImageCollection('USGS/NLCD_RELEASES/2019_REL/NLCD');
var nlcd2016 = dataset.filter(ee.Filter.eq('system:index', '2016')).first();
var LCLU = nlcd2016.select('landcover').clip(aoi);
// Flooded cultivated lands
var cultivated_mask = LCLU.eq(82).or(LCLU.eq(81))
var cultivated = LCLU.updateMask(cultivated_mask)
var lclu_data = 'the National Land Cover Database (NLCD) 30-m product land cover database for USA'
}
if (lcluSelected == "Globe") {
var dataset = ee.ImageCollection("ESA/WorldCover/v200")
var worldCover = dataset.first();
var LCLU = worldCover.clip(aoi);
// Flooded cultivated lands
var cultivated_mask = LCLU.eq(40)
var cultivated = LCLU.updateMask(cultivated_mask)
var lclu_data = 'the European Space Agency (ESA) WorldCover 10m product global land cover map'
}
// Calculate affected cropland using the resampled flood layer
var cultivated_flooded = combined_ndfi_dii.updateMask(cultivated)
// get pixel area of affected cropland layer
var cultivated_pixelarea = cultivated_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var cultivated_area = cultivated_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
// convert area to square km
var crop_area_sqkm = cultivated_area
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
// Flooded Urban lands
if (lcluSelected == "USA") {
var urban_mask = LCLU.eq(21).or(LCLU.eq(22)).or(LCLU.eq(23)).or(LCLU.eq(24))
} if (lcluSelected == "Globe") {
var urban_mask = LCLU.eq(50)
}
var urban = LCLU.updateMask(urban_mask)
// Calculate affected cropland using the resampled flood layer
var urban_flooded = combined_ndfi_dii.updateMask(urban)
// get pixel area of affected cropland layer
var urban_pixelarea = urban_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var urban_area = urban_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 30,
maxPixels: 1e9
});
// convert area to square km
var urban_area_sqkm = urban_area
.getNumber("NDFI")
.divide(1000)
.round()
.divide(1000);
// Exposed people
// Load JRC Global Human Settlement Popluation Density layer, Resolution: 250, "Number of people per cell is given".
var dataset = ee.ImageCollection('WorldPop/GP/100m/pop').filterDate('2017');
var count_population = dataset.select('population').mosaic().clip(aoi);
// Create a raster showing exposed population only using the resampled flood layer
var people_affected = count_population
.updateMask(combined_ndfi_dii)
.updateMask(count_population);
print("people_affected", people_affected)
//Sum pixel values of exposed population raster
var people_affected_count = people_affected.reduceRegion({
reducer: ee.Reducer.sum(),
geometry: aoi,
scale: 100,
maxPixels:1e9
});
// get number of exposed people as integer
var people_affected_number = people_affected_count.getNumber('population').round();
print("people_affected_number2", people_affected_number)
// ***** Flooded Heavy Industry ***** //
var LCZones_dataset = ee.ImageCollection("RUB/RUBCLIM/LCZ/global_lcz_map/latest")
var LCZones = LCZones_dataset.select("LCZ_Filter").first().clip(aoi);
var Industry_mask = LCZones.eq(10)
var Industry = LCZones.updateMask(Industry_mask)
// Calculate affected cropland using the resampled flood layer
var Industry_flooded = combined_ndfi_dii.updateMask(Industry)
// get pixel area of affected cropland layer
var Industry_pixelarea = Industry_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var Industry_area = Industry_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 100,
maxPixels: 1e9
});
// convert area to square km
var Industry_area_sqkm = Industry_area
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
// ***** Dense Building affected ***** //
var DenseBuild_mask = LCZones.eq(1).or(LCZones.eq(2)).or(LCZones.eq(3)).or(LCZones.eq(7))
var DenseBuild = LCZones.updateMask(DenseBuild_mask)
// Calculate affected cropland using the resampled flood layer
var DenseBuild_flooded = combined_ndfi_dii.updateMask(DenseBuild)
// get pixel area of affected cropland layer
var DenseBuild_pixelarea = DenseBuild_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var DenseBuild_area = DenseBuild_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 100,
maxPixels: 1e9
});
// convert area to square km
var DenseBuild_area_sqkm = DenseBuild_area
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
// ***** Open Arrangement Building affected ***** //
var OpArrBuild_mask = LCZones.eq(4).or(LCZones.eq(5)).or(LCZones.eq(6))
var OpArrBuild = LCZones.updateMask(OpArrBuild_mask)
// Calculate affected cropland using the resampled flood layer
var OpArrBuild_flooded = combined_ndfi_dii.updateMask(OpArrBuild)
// get pixel area of affected cropland layer
var OpArrBuild_pixelarea = OpArrBuild_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var OpArrBuild_area = OpArrBuild_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 100,
maxPixels: 1e9
});
// convert area to square km
var OpArrBuild_area_sqkm = OpArrBuild_area
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
// ***** Sparse Arrangement Building affected ***** //
var SpArrBuild_mask = LCZones.eq(9)
var SpArrBuild = LCZones.updateMask(SpArrBuild_mask)
// Calculate affected cropland using the resampled flood layer
var SpArrBuild_flooded = combined_ndfi_dii.updateMask(SpArrBuild)
// get pixel area of affected cropland layer
var SpArrBuild_pixelarea = SpArrBuild_flooded.multiply(ee.Image.pixelArea());
// sum pixels of affected cropland layer
var SpArrBuild_area = SpArrBuild_pixelarea.reduceRegion({
reducer: ee.Reducer.sum(), //sum all pixels with area information
geometry: aoi,
scale: 100,
maxPixels: 1e9
});
// convert area to square km
var SpArrBuild_area_sqkm = SpArrBuild_area
.getNumber("NDFI")
.divide(10000)
.round()
.divide(100);
var settled_flooded = urban_flooded.mask().add(DenseBuild_flooded.mask()).gt(0)
settled_flooded = settled_flooded.updateMask(settled_flooded.eq(1))
settled_flooded = settled_flooded.mask().add(OpArrBuild_flooded.mask()).gt(0)
settled_flooded = settled_flooded.updateMask(settled_flooded.eq(1))
settled_flooded = settled_flooded.mask().add(SpArrBuild_flooded.mask()).gt(0)
settled_flooded = settled_flooded.updateMask(settled_flooded.eq(1))
var lclu_Crop_settled = cultivated_flooded.mask().clip(bounds)
.add(settled_flooded.mask().remap([0,1],[0,5]))
.rename('lclu_Crop_settled')
lclu_Crop_settled = lclu_Crop_settled.remap([0,1,3,5,6,8,9],[0,1,2,3,4,5,6])
lclu_Crop_settled = lclu_Crop_settled.updateMask(lclu_Crop_settled.gt(0));
if (app.checkbox_5.LCLU_affected.getValue() === true) {
Map.addLayer(lclu_Crop_settled,{min:0,max:4,palette:['dadada','0400ff', 'ff7704', 'fbff00']},'Flooded Cropland & Settled', 0)
}
// Display the results on panels --------------------------------------------------------------------------------
// set position of panel where the results will be displayed
var results = ui.Panel({
style: {
position: 'bottom-right',
padding: '1px 15px',
width: '350px'
}
});
//Prepare the visualtization parameters of the labels
var textVis_firstline = {
'margin':'0px 8px 2px 0px',
'color':'0310B4',
'fontSize':'16px',
'fontWeight':'bold'
};
var textVis = {
'margin':'5px 8px 2px 0px',
'color':'5DADE2',
'fontWeight':'bold'
};
var numberVIS = {
'margin':'0px 0px 2px 0px',
'color':'FF5733',
'fontWeight':'bold'
};
var statiscticsVIS = {
'margin':'0px 0px 1px 0px',
'color':'0310B4',
'fontWeight':'bold'
};
var subTextVis = {
'margin':'0px 5px 2px 0px',
'fontSize':'12px',
'color':'grey'
};
var titleTextVis = {
'margin':'0px 0px 15px 0px',
'fontSize': '20px',
'font-weight':'',
'color': '088F8F'
};
// Extract date from meta data
function dates(imgcol){
var range = imgcol.reduceColumns(ee.Reducer.minMax(), ["system:time_start"]);
var printed = ee.String('Earliest ')
.cat(ee.Date(range.get('min')).format('YYYY-MM-dd'))
.cat(', latest ')
.cat(ee.Date(range.get('max')).format('YYYY-MM-dd'));
return printed;
}
// User defined threshold information for flood extent estimation
var text1_1 = ui.Label('Extracted Flood Information',textVis_firstline);
var number1_2 = ui.Label('The kf value of '+ params[4] +' for NDFI and '+ params[5] + ' for DII'+' considered for calculating thresholds and extracting flood. The earliest and latest dates of data availability are:', subTextVis);
// Sentinel-1 and Sentinel-2 Satellite Data
var text2_2 = ui.Label('processing...',subTextVis);
dates(after).evaluate(function(val){text2_2.setValue('Senintel-1 imagery: '+val)});
var text2_a = ui.Label('Sentinel-2 Satellite Data:',textVis);
var text2_2_a = ui.Label('processing...',subTextVis);
dates(sentinel2_after).evaluate(function(val){text2_2_a.setValue('Senintel-2 imagery: '+val)});
var text_histogram = ui.Label('SAR Indices Image Histograms:',textVis);
var text2_2_b = ui.Label('Flooded Areas (square km):',textVis);
var text_data_LCLU = ui.Label('* The resources for "Flooded Areas" information is '+ lclu_data +'. The user can change this dataset via the listbox in "II. Change LCLU dataset" section of the Input Panel.', subTextVis);
// Estimated flood extent
var number2 = ui.Label('processing...',numberVIS);
flooded_area_sqkm.evaluate(function(val){number2.setValue('Total flood extent: ' +val)}),numberVIS;
var number3 = ui.Label('processing...',numberVIS);
crop_area_sqkm.evaluate(function(val){number3.setValue('Cropland flooded: ' +val)}),numberVIS;
var number4 = ui.Label('processing...',numberVIS);
urban_area_sqkm.evaluate(function(val){number4.setValue('Urban flooded: ' +val)}),numberVIS;
var text2_2_d = ui.Label('Vulnerable Area Affected (square km):',textVis);
var text_data_urbanlands = ui.Label('* The resources for "Vulnerable Area Affected" information is global map of Local Climate Zones (LCZs) at 100m pixel size for characterizing urban landscapes.', subTextVis);
var number6 = ui.Label('processing...',numberVIS);
Industry_area_sqkm.evaluate(function(val){number6.setValue('Heavey Industry: ' +val)}),numberVIS;
var number7 = ui.Label('processing...',numberVIS);
DenseBuild_area_sqkm.evaluate(function(val){number7.setValue('Dense Arraignment Building: ' +val)}),numberVIS;
var number8 = ui.Label('processing...',numberVIS);
OpArrBuild_area_sqkm.evaluate(function(val){number8.setValue('Open Arraignment Building: ' +val)}),numberVIS;
var number9 = ui.Label('processing...',numberVIS);
SpArrBuild_area_sqkm.evaluate(function(val){number9.setValue('Sparse Arraignment Building: ' +val)}),numberVIS;
var text2_2_c = ui.Label('Number of Population Threatened:',textVis);
var text_data_population = ui.Label('* The resources for "Number of Population Threatened" information is WorldPop Global Project Population Data at 100m pixel size for estimating human population distributions.', subTextVis);
var text_datasets = ui.Label('Used Datasets:', {fontSize: '13px', margin: '0px 0px 2px 0px', fontWeight:'bold', color:'gray'});
var number5 = ui.Label('processing...',numberVIS);
people_affected_number.evaluate(function(val){number5.setValue(val+' person(s)')}),numberVIS;
// Disclaimer
var text_disclaimer = ui.Label('***Disclaimer: This product has been automatically derived. Subsequently, expert validation is required to assess the viability of the final product for use in decision-making and action planning by responsible parties.***',subTextVis)
// Add the labels to the panel
results.add(ui.Panel([
ui.Label({value: 'Result Panel', style: {fontWeight: '700', fontSize: '16px', color:'B3B5CB' , margin: '1px 1px 1px 100px'}}),
text1_1,
number1_2,
text2_2,
text2_2_a,
text2_2_b,
number2,
]));
if (app.checkbox_6.getStrategicInfo.getValue() === true) {
results.add(ui.Panel([
number3,
number4,
text2_2_d,
number6,
number7,
number8,
number9,
text2_2_c,
number5,
]));
}
if (app.checkbox_1.calibration.getValue() === false) {
if (app.checkbox_6.getStrategicInfo.getValue() === true) {
results.add(ui.Panel([
text_disclaimer,
text_datasets,
text_data_LCLU,
text_data_urbanlands,
text_data_population,
]));
}
else{
results.add(ui.Panel([
text_disclaimer,
]));
}
}
// Add the panel to the map
app.rootResultPanels.panel.clear();
app.rootResultPanels.panel.add(results)//.add(controlPanel);
ui.root.remove(app.rootResultPanels.panel);
ui.root.insert(1, app.rootResultPanels.panel)
//----------------------------- Display legend on the map --------------------------//
// https://mygeoblog.com/2016/12/09/add-a-legend-to-to-your-gee-map/
// set position of panel
var legend = ui.Panel({
style: {
position: 'bottom-right',
padding: '8px 15px',
}
});
// Create legend title
var legendTitle = ui.Label('Legend',titleTextVis);
// Creates and styles
var makeRow = function(color, name) {
// Create the label that is actually the colored box.
var colorBox = ui.Label({
style: {
backgroundColor: color,
// Use padding to give the box height and width.
padding: '6px',
margin: '0 0 4px 0'
}
});
// Create the label filled with the description text.
var description = ui.Label({
value: name,
style: {margin: '0 0 4px 6px'}
});
// return the panel
return ui.Panel({
widgets: [colorBox, description],
layout: ui.Panel.Layout.Flow('horizontal')
});
};
// Palette with the colors
var palette =['#d6aa06', '#19b5ff', '#e4156b', '56ff6b', 'f6adff'];
// name of the legend
var names = ['NDFI flood', 'DII flood', 'MNDWI flood', 'NDFI&DII flood', "Open Waters"];
var palette =['56ff6b', 'f6adff', '#e4156b', '#d6aa06', '#19b5ff'];
// name of the legend
var names = ['Merged NDFI&DII flood', "Open Waters", 'MNDWI flood', 'NDFI flood', 'DII flood'];
if (app.checkbox_3.displayNDFIandDIIflood.getValue() === true) {