-
Notifications
You must be signed in to change notification settings - Fork 12
/
PyGEE_SWToolbox.py
1358 lines (1086 loc) · 65 KB
/
PyGEE_SWToolbox.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
import ee
# Initialize the GEE API
# try:
# ee.Initialize()
# except Exception as e:
# ee.Authenticate()
ee.Initialize()
# geemap:A Python package for interactive mapping with Google Earth Engine, ipyleaflet, and ipywidgets
# Documentation: https://geemap.org
import geemap
from geemap import ml
import pickle
# from geemap import ee_basemaps
import matplotlib.pyplot as plt
import numpy as np
#eemont
import eemont
# import developed utilities
# import Utilities as ut
from Utilities import *
# geetols: Google earth engine tools
# https://github.com/gee-community/gee_tools
import geetools
from geetools import tools
# hydrafloods: Hydrologic Remote Sensing Analysis for Floods
#https://github.com/Servir-Mekong/hydra-floods
import hydrafloods as hf
from hydrafloods import geeutils
# Ipywidgets for GUI design
import ipywidgets as ipw
from IPython.display import display
from ipywidgets import HBox, VBox, Layout
# A simple Python file chooser widget for use in Jupyter/IPython in conjunction with ipywidgets
# https://pypi.org/project/ipyfilechooser/
from ipyfilechooser import FileChooser
# Plotly Python API for interactive graphing
import plotly
import plotly.express as px
import plotly.graph_objects as go
# Pandas - Python Data Analysis Library for data analysis and manipulation
import pandas as pd
# Miscellaneous Python modules
from datetime import datetime, timedelta
import os
class Toolbox:
def __init__(self):
#----------------------------------------------------------------------------------------------------
""" UI Design"""
#---------------------------------------------------------------------------------------------------
# Program Title
Title_text = ipw.HTML(
"<h3 class= 'text-center'><font color = 'blue'>Python-GEE Surface Water Analysis Toolbox v.1.0.3</font>")
style = {'description_width': 'initial'}
# Image Processing Tab
#************************************************************************************************
# Image Parameters UI
dataset_description = ipw.HTML(value = f"<b><font color='blue'>{'Satellite Imagery Parameters:'}</b>")
dataset_Label = ipw.Label('Select Dataset:', layout=Layout(margin='5px 0 0 5px')) #top right bottom left
Platform_options = ['Landsat-Collection 1', 'Landsat-Collection 2','Sentinel-1', 'Sentinel-2', 'USDA NAIP' ]
self.Platform_dropdown = ipw.Dropdown(options = Platform_options, value = None,
layout=Layout(width='150px', margin='5px 0 0 5px'))
filtering_Label = ipw.Label('Speckle filter:', layout=Layout(margin='5px 0 0 5px'))
filtering_options = ['Refined-Lee', 'Perona-Malik', 'P-median', 'Lee Sigma', 'Gamma MAP','Boxcar Convolution']
self.filter_dropdown = ipw.Dropdown(options = filtering_options, value = 'Refined-Lee',
layout=Layout(width='150px', margin='5px 0 0 15px'))
self.filter_dropdown.disabled = True
PlatformType = HBox([dataset_Label, self.Platform_dropdown])
FilterType = HBox([filtering_Label, self.filter_dropdown])
# Study period definition
#************************************************************************************************
# Start date picker
lbl_start_date = ipw.Label('Start Date:', layout=Layout(margin='5px 0 0 5px'))
self.start_date = ipw.DatePicker(value = datetime.now()-timedelta(7), disabled=False,
layout=Layout(width='150px', margin='5px 0 0 30px'))
start_date_box = HBox([lbl_start_date, self.start_date])
# End date picker
lbl_end_date = ipw.Label('End Date:', layout=Layout(margin='5px 0 0 5px'))
self.end_date = ipw.DatePicker(value = datetime.now(), disabled=False,
layout=Layout(width='150px', margin='5px 0 0 34px'))
end_date_box = HBox([lbl_end_date, self.end_date])
datePickers = VBox([start_date_box, end_date_box])
# Cloud threshold for filtering data
#************************************************************************************************
# Set cloud threshold
self.cloud_threshold = ipw.IntSlider(description = 'Cloud Threshold:', orientation = 'horizontal',
value = 50, step = 5, style = style)
imageParameters = VBox([dataset_description, PlatformType, FilterType, datePickers, self.cloud_threshold],
layout=Layout(width='305px', border='solid 2px black'))
# Study Area definition
#************************************************************************************************
# Option to use a map drawn boundary or upload shapefile
StudyArea_description = ipw.HTML(value = f"<b><font color='blue'>{'Study Area Definition:'}</b>")
self.user_preference = ipw.RadioButtons(options=['Map drawn boundary','Upload boundary'], value='Map drawn boundary')
self.file_selector = FileChooser(description = 'Upload', filter_pattern = ["*.shp","*.kml"], use_dir_icons = True)
# Retrieve and process satellite images
#***********************************************************************************************
# Button to retrieve and process satellite images from the GEE platform
self.imageProcessing_Button = ipw.Button(description = 'Process images',
tooltip='Click to process images', button_style = 'info',
layout=Layout(width='150px', margin='5px 0 0 50px', border='solid 2px black'))
# Study area UI and process button container
# ************************************************************************************************
StudyArea = VBox(children = [StudyArea_description, self.user_preference, self.imageProcessing_Button],
layout=Layout(width='300px', border='solid 2px black', margin='0 0 0 10px'))
# Results UI for displaying number and list of files
#*****************************************************************************************************
lbl_results = ipw.HTML(value = f"<b><font color='blue'>{'Processing Results:'}</b>")
lbl_images = ipw.Label('No. of processed images:')
self.lbl_RetrievedImages = ipw.Label()
display_no_images = HBox([lbl_images, self.lbl_RetrievedImages])
lbl_files = ipw.Label('List of files:')
self.lst_files = ipw.Select(layout=Layout(width='360px', height='100px'))
image_Results = VBox([lbl_results, display_no_images, lbl_files, self.lst_files],
layout=Layout(width='400px', border='solid 2px black', margin='0 0 0 10px'))
# Container for Image Processing Tab
#************************************************************************************************
imageProcessing_tab = HBox([imageParameters, StudyArea, image_Results])
# Water Extraction Tab
#*************************************************************************************************
# Water extraction indices
water_index_options = ['NDWI','MNDWI','DSWE', 'AWEInsh', 'AWEIsh']
lbl_indices = ipw.Label('Water Index:', layout=Layout(margin='5px 0 0 5px'))
self.water_indices = ipw.Dropdown(options = water_index_options, value = 'NDWI',
layout=Layout(width='100px', margin='5px 0 0 63px'))
display_indices = HBox([lbl_indices, self.water_indices])
# Color widget for representing water
lbl_color = ipw.Label('Color:', layout=Layout(margin='5px 0 0 5px'))
self.index_color = ipw.ColorPicker(concise = False, value = 'blue',layout=Layout(width='100px', margin='5px 0 0 101px'))
display_color_widget = HBox([lbl_color, self.index_color])
# Water index threshold selection
threshold_options = ['Simple','Otsu']
lbl_threshold_method = ipw.Label('Thresholding Method:', layout=Layout(margin='5px 0 0 5px'))
self.threshold_dropdown = ipw.Dropdown(options = threshold_options,value = 'Simple',
layout=Layout(width='100px', margin='5px 0 0 10px'))
display_thresholds = HBox([lbl_threshold_method, self.threshold_dropdown])
lbl_threshold = ipw.Label('Threshold value:', layout=Layout(margin='5px 0 5px 5px'))
self.threshold_value = ipw.BoundedFloatText(value=0.000, min = -1.0, max = 1.0, step = 0.050,
layout=Layout(width='100px', margin='5px 0 0 40px'))
display_threshold_widget = HBox([lbl_threshold, self.threshold_value])
water_index_Box = VBox([display_indices, display_thresholds, display_threshold_widget, display_color_widget],
layout=Layout(width='250px', border='solid 2px black'))
self.extractWater_Button = ipw.Button(description = 'Extract Water', tooltip='Click to extract surface water',
button_style = 'info',
layout=Layout(width='150px', margin='5px 0 0 20px', border='solid 2px black'))
Extraction_tab = HBox([water_index_Box, self.extractWater_Button])
self.extractWater_Button.disabled = True
# Spatial Analysis Tab
#**************************************************************************************************
self.water_Frequency_button = ipw.Button(description = 'Compute Water Frequency',
tooltip='Click to compute water occurence frequency',
button_style = 'info',
layout=Layout(width='200px', border='solid 2px black',margin='5 0 0 50px'))
self.water_Frequency_button.disabled = True
self.Depths_Button = ipw.Button(description = 'Compute Depth Map',
tooltip='Click to generate depth maps', button_style = 'info',
layout=Layout(width='200px', border='solid 2px black',margin='5 0 0 50px'))
self.Depths_Button.disabled = True
self.elevData_options = ipw.Dropdown(options=['NED','SRTM','User DEM'], value='NED', description='Elev. Dataset:',
layout=Layout(width='210px', margin='0 0 0 10px'), style = style)
self.elevData_options.disabled = False
# self.elev_Methods = ipw.Dropdown(options=['Random Forest','Mod_Stumpf','Mod_Lyzenga','FwDET'], value='Random Forest',
# description='Depth method:',
# layout=Layout(width='210px', margin='0 0 0 10px'), style = style)
self.elev_Methods = ipw.Dropdown(options=['Experimental','FwDET'], value='FwDET',
description='Depth method:',
layout=Layout(width='210px', margin='0 0 0 10px'), style = style)
self.elev_Methods.disabled = True
self.userDEM = ipw.Dropdown(description='Select GEE asset:',
layout=Layout(width='300px', margin='0 0 0 10px'), style = style)
lbl_Elev = ipw.Label('Elevation Dataset:', layout=Layout(margin='0 0 0 10px'))
elev_Box = HBox([self.Depths_Button, self.elev_Methods, self.elevData_options])
self.zonalAnalysis_Button = ipw.Button(description = 'Zonal Analysis',
tooltip='Click to remove clouds', button_style = 'info',
layout=Layout(width='200px', border='solid 2px black',margin='5 0 0 50px'))
# Spatial_Analysis_Tab = VBox([water_Frequency_button, elev_Box, zonalAnalysis_Button])
Spatial_Analysis_Tab = VBox([self.water_Frequency_button, elev_Box])
# Ploting and Statistics Tab
#***************************************************************************************************
lbl_Area_Plotting = ipw.HTML(value = f"<b><font color='blue'>{'Surface Water Area Computation:'}</b>")
self.area_unit = ipw.Dropdown(options = ['Square m','Square Km', 'Hectares', 'Acre'], value = 'Square m',
description = 'Unit of area:', style=style, tooltip='Select unit for areas', layout=Layout(width='200px'))
self.plot_button = ipw.Button(description = 'Compute and Plot Areas', tooltip='Click to plot graph', button_style = 'info',
layout=Layout(width='170px', margin='10 0 0 200px', border='solid 2px black'))
self.plot_button.disabled = True
lbl_Volume_Plotting = ipw.HTML(value = f"<b><font color='blue'>{'Water Volume Computation:'}</b>")
self.vol_unit = ipw.Dropdown(options = ['Cubic m','Cubic ft', 'Litres', 'ac-ft'], value = 'ac-ft',
description = 'Unit of volume:', style=style, tooltip='Select unit for volumes', layout=Layout(width='200px'))
self.volume_button = ipw.Button(description = 'Compute Volumes', tooltip='Click to plot volumes', button_style = 'info',
layout=Layout(width='170px', margin='10 0 0 200px', border='solid 2px black'))
self.volume_button.disabled = True
# lbl_depth_Plotting = ipw.Label(value ='Plot depth hydrograph at a location:', layout=Layout(margin='10px 0 0 0'))
lbl_depth_Plotting = ipw.HTML(value = f"<b><font color='blue'>{'Plot depth hydrograph at a location:'}</b>")
self.point_preference = ipw.RadioButtons(options=['Map drawn point','Enter coordinates'],
value='Map drawn point')
self.coordinates_textbox = ipw.Text(layout=Layout(width='200px'))
lbl_coordinates = ipw.Label(value='Enter Long, Lat in decimal degrees')
# point_selector = FileChooser(description = 'Upload point', filter_pattern = ["*.shp"], use_dir_icons = True)
self.depth_plot_button = ipw.Button(description = 'Plot depths', tooltip='Click to plot depth hydrograph', button_style = 'info',
layout=Layout(width='170px', margin='10 0 0 100px', border='solid 2px black'))
self.depth_plot_button.disabled = True
depth_box = VBox(children = [lbl_depth_Plotting,self.point_preference, self.depth_plot_button])
plotting_box = VBox([lbl_Area_Plotting, self.area_unit, self.plot_button, lbl_Volume_Plotting,self.vol_unit,self.volume_button, depth_box],
layout=Layout(width='310px', border='solid 2px black'))
lbl_Stats = ipw.HTML(value = f"<b><font color='blue'>{'Summary Statistics:'}</b>")
self.lbl_Max_Area = ipw.Label(value ='', layout=Layout(width='100px')) #top right bottom left
self.lbl_Min_Area = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Avg_Area = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Max_Depth = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Min_Depth = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Avg_Depth = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Max_Volume = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Min_Volume = ipw.Label(value ='', layout=Layout(width='100px'))
self.lbl_Avg_Volume = ipw.Label(value ='', layout=Layout(width='100px'))
self.cap_Max_Area = ipw.Label(value ='Max. Area:')
self.cap_Min_Area = ipw.Label(value ='Min. Area:')
self.cap_Avg_Area = ipw.Label(value ='Avg. Area:')
self.cap_Max_Depth = ipw.Label(value ='Max. Depth:')
self.cap_Min_Depth = ipw.Label(value ='Min. Depth:')
self.cap_Avg_Depth = ipw.Label(value ='Avg. Depth:')
self.cap_Max_Volume = ipw.Label(value ='Max. Volume:')
self.cap_Min_Volume = ipw.Label(value ='Min. Volume:')
self.cap_Avg_Volume = ipw.Label(value ='Avg. Volume:')
max_box = HBox([self.cap_Max_Area,self.lbl_Max_Area, self.cap_Max_Depth,self.lbl_Max_Depth, self.cap_Max_Volume,self.lbl_Max_Volume])
min_box = HBox([self.cap_Min_Area,self.lbl_Min_Area, self.cap_Min_Depth,self.lbl_Min_Depth, self.cap_Min_Volume, self.lbl_Min_Volume])
avg_box = HBox([self.cap_Avg_Area,self.lbl_Avg_Area, self.cap_Avg_Depth,self.lbl_Avg_Depth, self.cap_Avg_Volume, self.lbl_Avg_Volume])
stats_box = VBox([lbl_Stats, max_box, min_box, avg_box])
self.file_selector1 = FileChooser(description = 'Select folder and filename', filter_pattern = "*.csv", use_dir_icons = True)
self.file_selector1.title = 'Select Folder and Filename'
self.file_selector1.default_path = os.getcwd()
self.save_data_button = ipw.Button(description = 'Save Data',tooltip='Click to save computed areas to file',button_style = 'info',
layout=Layout(width='100px', border='solid 2px black',margin='5 0 0 50px'))
lbl_Save = ipw.HTML(value = f"<b><font color='blue'>{'Save Data:'}</b>")
stats_save_box = VBox(children=[stats_box, lbl_Save, self.file_selector1, self.save_data_button],
layout=Layout(width='550px', border='solid 2px black', margin='0 0 0 10px'))
plot_stats_tab = HBox(children=[plotting_box, stats_save_box])
# Downloads Tab
#***************************************************************************************************
self.files_to_download = ipw.RadioButtons(options=['Satellite Images', 'Water Mask', 'Water Frequency', 'Depth Maps',
'DSWE Images'], value='Satellite Images',
description='Files to download:', style = style)
self.download_location = ipw.RadioButtons(options=['Google Drive', 'Local Disk'],
value='Google Drive', description='Download Location:', style = style)
self.folder_name = ipw.Text(description='Folder Name:')
self.folder_selector = FileChooser(description = 'Select Folder', show_only_dirs = True, use_dir_icons = True)
self.folder_selector.title = '<b>Select a folder</b>'
self.folder_selector.default_path = os.getcwd()
self.download_button = ipw.Button(description = 'Download',
tooltip='Click to plot download water images', button_style = 'info')
self.download_button.disabled = True
download_settings = VBox(children=[self.files_to_download, self.download_location, self.folder_name])
download_tab = HBox([download_settings, self.download_button])
# variable to hold the random forest classifier
self.rf_ee_classifier = None
self.WaterMasks = None
self.visParams = None
self.freqParams = None
self.filtered_Collection = None
self.filtered_landsat = None
self.clipped_images = None
self.imageType = None
self.dates = None
self.site = None
self.img_scale = None
self.file_list = None
self.StartDate = None
self.EndDate = None
self.water_images = None
self.dswe_images = None
self.index_images = None
self.dswe_viz = None
self.depth_maps = None
self.filtered_Water_Images = None
self.depthParams = None
# Functions to control UI changes and parameter settings
#****************************************************************************************************
def platform_index_change(change):
"""
Function to set image visualization parameters, hide or show some UI componets and
show water indices that are applicable to the type of satellite image selected
args:
None
returns:
None
"""
try:
if self.Platform_dropdown.value == 'Landsat-Collection 1':
self.visParams = {'bands': ['red', 'green', 'blue'],
'min': 0,
'max': 3000,
'gamma':1.4
}
self.cloud_threshold.disabled = False
self.water_indices.disabled = False
self.index_color.disabled = False
self.threshold_value.disabled = False
self.water_indices.options = ['NDWI','MNDWI','DSWE','AWEInsh', 'AWEIsh']
self.threshold_dropdown.options = ['Simple','Otsu']
self.filter_dropdown.disabled = True
elif self.Platform_dropdown.value == 'Landsat-Collection 2':
self.visParams = {'bands': ['red', 'green', 'blue'],
'min': 0,
'max': 0.3,
}
self.cloud_threshold.disabled = False
self.water_indices.disabled = False
self.index_color.disabled = False
self.threshold_value.disabled = False
self.water_indices.options = ['NDWI','MNDWI','DSWE','AWEInsh', 'AWEIsh']
self.threshold_dropdown.options = ['Simple','Otsu']
self.filter_dropdown.disabled = True
elif self.Platform_dropdown.value == 'Sentinel-1':
self.visParams = {'min': -25,'max': 0}
self.cloud_threshold.disabled = True
self.water_indices.options = ['VV','VH']#,'NDPI','NVHI', 'NVVI']
self.index_color.disabled = False
self.threshold_value.disabled = True
self.threshold_dropdown.options = ['Otsu']
self.filter_dropdown.disabled = False
elif self.Platform_dropdown.value == 'Sentinel-2':
self.visParams = {'bands': ['red', 'green', 'blue'],
'min': 0.0,
'max': 3000}
self.cloud_threshold.disabled = False
self.water_indices.disabled = False
self.index_color.disabled = False
self.threshold_value.disabled = False
self.water_indices.options = ['NDWI','MNDWI']
self.threshold_dropdown.options = ['Simple','Otsu']
self.filter_dropdown.disabled = True
elif self.Platform_dropdown.value == 'USDA NAIP':
self.visParams = {'bands': ['R', 'G','B'],
'min': 0.0,
'max': 255.0}
self.threshold_value.disabled = False
self.water_indices.disabled = False
self.index_color.disabled = False
self.water_indices.options = ['NDWI']
self.threshold_dropdown.options = ['Simple','Otsu']
self.filter_dropdown.disabled = True
except Exception as e:
print(e)
# Link widget to function
self.Platform_dropdown.observe(platform_index_change, 'value')
def showFileSelector(button):
"""
Function to show or hide shapefile upload widget
args:
None
returns:
None
"""
if button['new']:
StudyArea.children = [StudyArea_description, self.user_preference, self.file_selector, self.imageProcessing_Button]
else:
StudyArea.children = [StudyArea_description, self.user_preference,self.imageProcessing_Button]
# Link widget to file selector function
self.user_preference.observe(showFileSelector, names='index')
def showLocationSelector(button):
"""
Function to show or hide folder selector
args:
None
returns:
None
"""
if button['new']:
download_settings.children = [self.files_to_download, self.download_location, self.folder_selector]
else:
download_settings.children = [self.files_to_download, self.download_location, self.folder_name]
# Link widget to folder selector function
self.download_location.observe(showLocationSelector, names='index')
def pointOptions_selector(button):
"""
Function to show or hide folder selector
args:
None
returns:
None
"""
if button['new']:
depth_box.children = [lbl_depth_Plotting,self.point_preference, lbl_coordinates, self.coordinates_textbox,
self.depth_plot_button]
else:
depth_box.children = [lbl_depth_Plotting,self.point_preference, self.depth_plot_button]
# Link widget to folder selector function
self.point_preference.observe(pointOptions_selector, names='index')
def indexSelection(change):
if self.water_indices.value =='DSWE':
self.threshold_value.min = 1.0
self.threshold_value.max = 4.0
self.threshold_value.step = 1.0
self.threshold_value.value = 4.0
self.threshold_dropdown.options = ['Simple']
else:
self.threshold_value.min = -1.0
self.threshold_value.max = 1.0
self.threshold_value.step = 0.050
self.threshold_value.value = 0.0
self.threshold_dropdown.options = ['Simple','Otsu']
self.water_indices.observe(indexSelection, 'value')
def thresholdSelection(change):
if self.threshold_dropdown.value =='Otsu':
self.threshold_value.disabled = True
else:
self.threshold_value.disabled = False
# Link widget to threshold method selection function
self.threshold_dropdown.observe(thresholdSelection, 'value')
def depthMethodSelection(change):
if self.elev_Methods.value == 'FwDET' or self.elev_Methods.value == 'Experimental':
self.elevData_options.disabled = False
else:
self.elevData_options.disabled = True
elev_Box.children = [self.Depths_Button, self.elev_Methods, self.elevData_options]
# Link widget to threshold method selection function
self.elev_Methods.observe(depthMethodSelection, 'value')
def demSelection(change):
if self.elevData_options.value == 'User DEM':
folder = ee.data.getAssetRoots()[0]['id']
assets = ee.data.listAssets({'parent':folder})
# filter only image assets
filtered_asset = list(filter(lambda asset: asset['type'] == 'IMAGE', assets['assets']))
# create a list of image assets
list_assets = [sub['id'] for sub in filtered_asset]
elev_Box.children = [self.Depths_Button, self.elev_Methods, self.elevData_options, self.userDEM]
self.userDEM.options = list_assets # set dropdown options to list of image assets
else:
elev_Box.children = [self.Depths_Button, self.elev_Methods, self.elevData_options]
# Link widget to function
self.elevData_options.observe(demSelection, 'value')
#****************************************************************************************************
# Full UI
#***************************************************************************************************
tab_children = [imageProcessing_tab, Extraction_tab, Spatial_Analysis_Tab, plot_stats_tab, download_tab]
tab = ipw.Tab()
tab.children = tab_children
# changing the title of the first and second window
tab.set_title(0, 'Image Processing')
tab.set_title(1, 'Water Extraction')
tab.set_title(2, 'Spatial Analysis')
tab.set_title(3, 'Plotting & Stats')
tab.set_title(4, 'Download & Export')
# Plotting outputs and feedback to user
#***************************************************************************************************
self.feedback = ipw.Output()
# OUTPUTS = VBox([self.feedback])
# create map instance
self.Map = geemap.Map()
self.Map.add_basemap('HYBRID')
GUI = VBox([Title_text,tab,self.Map])
display(GUI)
self.fig = go.FigureWidget()
self.fig.update_layout(title = '<b>Surface Water Area Hydrograph<b>',
title_x = 0.5, title_y = 0.90, title_font=dict(family="Arial",size=24),
template = "plotly_white",
xaxis =dict(title ='<b>Date<b>', linecolor = 'Black'),
yaxis=dict(title='Area (sq m)', linecolor = 'Black'),
font_family="Arial")
# display plotly figure
display(self.fig)
display(self.feedback)
# Widget-Function connections
self.imageProcessing_Button.on_click(self.process_images)
self.extractWater_Button.on_click(self.Water_Extraction)
self.plot_button.on_click(self.plot_areas)
self.save_data_button.on_click(self.save_data)
self.Depths_Button.on_click(self.calc_depths)
self.download_button.on_click(self.dowload_images)
self.water_Frequency_button.on_click(self.water_frequency)
self.depth_plot_button.on_click(self.plot_depths)
self.volume_button.on_click(self.plot_volumes)
# Function to clip images
def clipImages(self,img):
"""
Function to clip images
args:
Image
returns:
Clipped image
"""
orig = img
clipped_image = img.clip(self.site).copyProperties(orig, orig.propertyNames())
return clipped_image
def process_images(self, b):
"""
Function to retrieve and process satellite images from GEE platform
args:
None
returns:
None
"""
with self.feedback:
self.feedback.clear_output()
try:
self.fig.data = [] # clear existing plot
self.lbl_RetrievedImages.value = 'Processing....'
cloud_thresh = self.cloud_threshold.value
# Define study area based on user preference
if self.user_preference.index == 1:
file = self.file_selector.selected
self.site = load_boundary(file)
self.Map.addLayer(self.site, {}, 'AOI')
self.Map.center_object(self.site)
else:
self.site = ee.FeatureCollection(self.Map.draw_last_feature)
# get widget values
self.imageType = self.Platform_dropdown.value
filterType = self.filter_dropdown.value
self.StartDate = ee.Date.fromYMD(self.start_date.value.year,self.start_date.value.month,self.start_date.value.day)
self.EndDate = ee.Date.fromYMD(self.end_date.value.year,self.end_date.value.month,self.end_date.value.day)
boxcar = ee.Kernel.circle(**{'radius':3, 'units':'pixels', 'normalize':True})
def filtr(img):
return img.convolve(boxcar)
# filter image collection based on date, study area and cloud threshold(depends of datatype)
if self.imageType == 'Landsat-Collection 1':
self.filtered_landsat = load_Landsat_Coll_1(self.site, self.StartDate, self.EndDate, cloud_thresh)
# self.filtered_Collection = self.filtered_landsat.map(maskLandsatclouds)
self.filtered_Collection = self.filtered_landsat.map(cloudMaskL457)
elif self.imageType == 'Landsat-Collection 2':
self.filtered_landsat = load_Landsat_Coll_2(self.site, self.StartDate, self.EndDate, cloud_thresh)
self.filtered_Collection = self.filtered_landsat.map(maskLandsatclouds)
elif self.imageType == 'Sentinel-2':
Collection_before = load_Sentinel2(self.site, self.StartDate, self.EndDate, cloud_thresh)
self.filtered_Collection = Collection_before.map(maskS2clouds)
elif self.imageType == 'Sentinel-1':
Collection_before = load_Sentinel1(self.site, self.StartDate, self.EndDate)
# apply speckle filter algorithm or smoothing
if filterType == 'Gamma MAP':
corrected_Collection = Collection_before.map(slope_correction)
self.filtered_Collection = corrected_Collection.map(hf.gamma_map)
elif filterType == 'Refined-Lee':
corrected_Collection = Collection_before.map(slope_correction)
self.filtered_Collection = corrected_Collection.map(hf.refined_lee)
elif filterType == 'Perona-Malik':
corrected_Collection = Collection_before.map(slope_correction)
self.filtered_Collection = corrected_Collection.map(hf.perona_malik)
elif filterType == 'P-median':
corrected_Collection = Collection_before.map(slope_correction)
self.filtered_Collection = corrected_Collection.map(hf.p_median)
elif filterType == 'Boxcar Convolution':
corrected_Collection = Collection_before.map(slope_correction)
self.filtered_Collection = corrected_Collection.map(filtr)
elif filterType == 'Lee Sigma':
# corrected_Collection = Collection_before.map(ut.slope_correction) # slope correction before lee_sigma fails
self.filtered_Collection = Collection_before.map(hf.lee_sigma)
elif self.imageType == 'USDA NAIP':
self.filtered_Collection = load_NAIP(self.site, self.StartDate, self.EndDate)
# Clip images to study area
self.clipped_images = self.filtered_Collection.map(self.clipImages)
# Mosaic same day images
self.clipped_images = tools.imagecollection.mosaicSameDay(self.clipped_images)
# Add first image in collection to Map
first_image = self.clipped_images.first()
if self.imageType == 'Sentinel-1':
self.img_scale = first_image.select(0).projection().nominalScale().getInfo()
else:
bandNames = first_image.bandNames().getInfo()
self.img_scale = first_image.select(str(bandNames[0])).projection().nominalScale().getInfo()
self.Map.addLayer(self.clipped_images.first(), self.visParams, self.imageType)
# Get no. of processed images
no_of_images = self.filtered_Collection.size().getInfo()
# Display number of images
self.lbl_RetrievedImages.value = str(no_of_images)
# List of files
self.file_list = self.filtered_Collection.aggregate_array('system:id').getInfo()
# display list of files
self.lst_files.options = self.file_list
self.extractWater_Button.disabled = False # enable the water extraction button
self.download_button.disabled = False
except Exception as e:
print(e)
print('An error occurred during processing.')
def Water_Extraction(self, b):
"""
Function to extract surface water from satellite images
args:
None
returns:
None
"""
with self.feedback:
self.feedback.clear_output()
try:
color_palette = self.index_color.value
# Function to extract water using NDWI or MNDWI from multispectral images
def water_index(img):
"""
Function to extract surface water from Landsat and Sentinel-2 images using
water extraction indices: NDWI, MNDWI, and AWEI
args:
Image
returns:
Image with water mask
"""
index_image = ee.Image(1)
if self.water_indices.value == 'NDWI':
if self.imageType == 'Landsat-Collection 1' or self.imageType == 'Landsat-Collection 2' or self.imageType == 'Sentinel-2':
bands = ['green', 'nir']
elif self.imageType == 'USDA NAIP':
bands = ['G', 'N']
index_image = img.normalizedDifference(bands).rename('waterIndex')\
.copyProperties(img, ['system:time_start'])
elif self.water_indices.value == 'MNDWI':
if self.imageType == 'Landsat-Collection 1' or self.imageType == 'Landsat-Collection 2':
bands = ['green', 'swir1']
index_image = img.normalizedDifference(bands).rename('waterIndex')\
.copyProperties(img, ['system:time_start'])
elif self.imageType == 'Sentinel-2':
# Resample the swir bands from 20m to 10m
resampling_bands = img.select(['swir1','swir2'])
img = img.resample('bilinear').reproject(**
{'crs': resampling_bands.projection().crs(),
'scale':10
})
bands = ['green', 'swir1']
index_image = img.normalizedDifference(bands).rename('waterIndex')\
.copyProperties(img, ['system:time_start'])
elif self.water_indices.value == 'AWEInsh':
index_image = img.expression(
'(4 * (GREEN - SWIR1)) - ((0.25 * NIR)+(2.75 * SWIR2))', {
'NIR': img.select('nir'),
'GREEN': img.select('green'),
'SWIR1': img.select('swir1'),
'SWIR2': img.select('swir2')
}).rename('waterIndex').copyProperties(img, ['system:time_start'])
elif self.water_indices.value == 'AWEIsh':
index_image = img.expression(
'(BLUE + (2.5 * GREEN) - (1.5 * (NIR + SWIR1)) - (0.25 * SWIR2))', {
'BLUE':img.select('blue'),
'NIR': img.select('nir'),
'GREEN': img.select('green'),
'SWIR1': img.select('swir1'),
'SWIR2': img.select('swir2')
}).rename('waterIndex').copyProperties(img, ['system:time_start'])
return img.addBands(index_image)
def water_thresholding(img):
# Compute threshold
if self.threshold_dropdown.value == 'Simple': # Simple value no dynamic thresholding
nd_threshold = self.threshold_value.value
water_image = img.select('waterIndex').gt(nd_threshold).rename('water')\
.copyProperties(img, ['system:time_start'])
elif self.threshold_dropdown.value == 'Otsu':
reducers = ee.Reducer.histogram(255,2).combine(reducer2=ee.Reducer.mean(), sharedInputs=True)\
.combine(reducer2=ee.Reducer.variance(), sharedInputs= True)
histogram = img.select('waterIndex').reduceRegion(
reducer=reducers,
geometry=self.site.geometry(),
scale=self.img_scale,
bestEffort=True)
nd_threshold = otsu(histogram.get('waterIndex_histogram')) # get threshold from the nir band
water_image = img.select('waterIndex').gt(nd_threshold).rename('water')
water_image = water_image.copyProperties(img, ['system:time_start'])
return img.addBands(water_image)
# Function to extract water from SAR Sentinel 1 images
def add_S1_waterMask(band):
"""
Function to extract surface water from Sentinel-1 images Otsu algorithm
args:
Image
returns:
Image with water mask
"""
def wrap(img):
reducers = ee.Reducer.histogram(255,2).combine(reducer2=ee.Reducer.mean(), sharedInputs=True)\
.combine(reducer2=ee.Reducer.variance(), sharedInputs= True)
histogram = img.select(band).reduceRegion(
reducer=reducers,
geometry=self.site.geometry(),
scale=self.img_scale,
bestEffort=True)
# Calculate threshold via function otsu (see before)
threshold = otsu(histogram.get(band+'_histogram'))
# get watermask
waterMask = img.select(band).lt(threshold).rename('water')
# waterMask = waterMask.updateMask(waterMask) #Remove all pixels equal to 0
return img.addBands(waterMask)
return wrap
def maskDSWE_Water(img):
nd_threshold = self.threshold_value.value+1
waterImage = img.select('dswe').rename('water')
water = waterImage.gt(0).And(waterImage.lt(nd_threshold)).copyProperties(img, ['system:time_start'])
return img.addBands(water)
def mask_Water(img):
waterMask = img.select('water').selfMask().rename('waterMask').copyProperties(img, ['system:time_start'])
return img.addBands(waterMask)
if self.imageType == 'Sentinel-1':
band = self.water_indices.value
self.water_images = self.clipped_images.map(add_S1_waterMask(band))#.select('water')
self.WaterMasks = self.water_images.map(mask_Water)
# self.visParams = {'min': 0,'max': 1, 'palette': color_palette}
self.Map.addLayer(self.WaterMasks.select('waterMask').max(), {'palette': color_palette}, 'Water')
elif self.imageType == 'Landsat-Collection 1' or self.imageType == 'Landsat-Collection 2':
if self.water_indices.value == 'DSWE':
dem = ee.Image('USGS/SRTMGL1_003')
if self.imageType == 'Landsat-Collection 1':
self.dswe_images = DSWE(self.filtered_landsat, dem, self.site)
else:
self.dswe_images = DSWE_2(self.filtered_landsat, dem, self.site)
# Viz parameters: classes: 0, 1, 2, 3, 4, 9
self.dswe_viz = {'min':0, 'max': 9, 'palette': ['000000', '002ba1', '6287ec', '77b800', 'c1bdb6',
'000000', '000000', '000000', '000000', 'ffffff']}
self.water_images = self.dswe_images.map(maskDSWE_Water)
self.WaterMasks = self.water_images.map(mask_Water)
# Map.addLayer(dswe_images.max(), dswe_viz, 'DSWE')
else:
self.index_images = self.clipped_images.map(water_index)
self.water_images = self.index_images.map(water_thresholding)
self.WaterMasks = self.water_images.map(mask_Water)
self.Map.addLayer(self.WaterMasks.select('waterMask').max(), {'palette': color_palette}, 'Water')
else:
self.index_images = self.clipped_images.map(water_index)
self.water_images = self.index_images.map(water_thresholding)
self.WaterMasks = self.water_images.map(mask_Water)
self.Map.addLayer(self.WaterMasks.select('waterMask').max(), {'palette': color_palette}, 'Water')
self.water_Frequency_button.disabled = False
self.Depths_Button.disabled = False
self.elev_Methods.disabled = False
self.plot_button.disabled = False
except Exception as e:
print(e)
print('An error occurred during computation.')
def calc_area(self, img):
"""
Function to calculate area of water pixels
args:
Water mask image
returns:
Water image with calculated total area of water pixels
"""
global area_unit_symbol
unit = self.area_unit.value
divisor = 1
if unit =='Square Km':
divisor = 1e6
area_unit_symbol = 'Sq km'
elif unit =='Hectares':
divisor = 1e4
area_unit_symbol = 'Ha'
elif unit =='Square m':
divisor = 1
area_unit_symbol = 'Sq m'
else:
divisor = 4047
area_unit_symbol = 'acre'
pixel_area = img.select('waterMask').multiply(ee.Image.pixelArea()).divide(divisor)
img_area = pixel_area.reduceRegion(**{
'geometry': self.site.geometry(),
'reducer': ee.Reducer.sum(),
'scale': self.img_scale,
'maxPixels': 1e13
})
return img.set({'water_area': img_area})
def plot_areas(self, b):
"""
Function to plot a time series of calculated water area for each water image
and to cycle through
args:
None
returns:
None
"""
with self.feedback:
self.feedback.clear_output()
try:
global df
global save_water_data
save_water_data = 1
# Compute water areas
water_areas = self.WaterMasks.map(self.calc_area)
water_stats = water_areas.aggregate_array('water_area').getInfo()
self.dates = self.WaterMasks.aggregate_array('system:time_start')\
.map(lambda d: ee.Date(d).format('YYYY-MM-dd')).getInfo()
dates_lst = [datetime.strptime(i, '%Y-%m-%d') for i in self.dates]
y = [item.get('waterMask') for item in water_stats]
df = pd.DataFrame(list(zip(dates_lst,y)), columns=['Date','Area'])
self.fig.data = []
self.fig.add_trace(go.Scatter(x=df['Date'], y=df['Area'], name='Water Hydrograph',
mode='lines+markers', line=dict(dash = 'solid', color ='Blue', width = 0.5)))
self.fig.layout.title = '<b>Surface Water Area Hydrograph<b>'
self.fig.layout.titlefont = dict(family="Arial",size=24)
self.fig.layout.title.x = 0.5
self.fig.layout.title.y = 0.9
self.fig.layout.yaxis.title = 'Area ('+area_unit_symbol+')'