-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGEE_PICX_code
2283 lines (1941 loc) · 89.6 KB
/
GEE_PICX_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 script: GEE-PICX: Phenological Imaging and Cloud-free Xport *
* Script Authors: Luisa Pflumm, Hyeonmin Kang *
* Date: 15.11.2024 *
* Contact: [email protected], [email protected] *
* Code License: Apache 2.0 *
* Description: *
* - GEE-PICX allows generating and exporting cloud-free and analysis-ready *
* composites of satellite images (Landsat or Sentinel-2) for user-defined *
* areas and time steps *
* - GEE-PICX follows five design principles: *
* 1. Flexibility of user input. *
* Users can select the satellite platform (Landsat or Sentinel-2), study area *
* boundaries, time range, maximum cloud cover (for single images), aggregation *
* mode, and image bands. Relevant scenes are automatically selected from the *
* data catalogue according to user input. Moreover, the modular design allows *
* users to easily add custom indices. *
* 2. Ease of use. The application features a self-explanatory graphical user *
* interface. It only requires a Google account, web browser, and internet *
* connection, with no additional hardware or software requirements due to *
* server-side processing. *
* 3. Export of large data sets. Export size is limited only by Google drive storage *
* capacity. *
* 4. Generation of analysis-ready data. Produces cloud-free image composites with *
* spectral bands, spectral indices, and a quality assessment band (valid scenes *
* per pixel). Export image resolution and coordinate reference system are *
* customizable. *
* 5. Data visualisation. Data sets can be visualised in the browser prior to export. *
* - Note: Users can request export of imagery from multiple years and/or narrow the *
* selection to specific consecutive months (also crossing the year boundary) *
* to create seasonal image aggregates. *
* - Note: The more extensive the time range or the study area, the longer it can take *
* to export the data. Visualization in App might fail when too large. *
****************************************************************************************
---------->>>>>> Click "Run" above this code editor window to start App! <<<<<<----------
---------->>>>>> ------------------------------------------------------- <<<<<<----------
---------->>>>>> No need to change code below, work with user interface. <<<<<<----------
/*****************************
****** Global variables *****
*****************************/
// Define global variables used in the script
var selFeature;
var currentData;
var selectedDataset;
var selectedIndex;
var startYear;
var endYear;
var startMonth;
var endMonth;
var exportScale;
var exportCrs;
var exportScaleClicked;
var maxCloudProbability;
var reducerString = "_median";
var reducers = ee.Reducer.median();
var maxPixels = 900000000000;
// Available datasets and their bands
var dataset = {
"Landsat-5,7,8,9": ["LS_all"],
"Landsat-8,9": ["LS_89"],
"Sentinel-2": ["S2"]
};
// All available bands
var allBands = {
"B": ["B"],
"G": ["G"],
"R": ["R"],
"NIR": ["NIR"],
"SWIR1": ["SWIR1"],
"SWIR2": ["SWIR2"],
"RedEdge1 (only S2)": ["RedEdge1"],
"RedEdge4 (only S2)": ["RedEdge4"],
};
// Composite dictionary for different band combinations
var compositeDic = {'True color composites [R-G-B]' : ["R", "G","B"],
'False color urban [SWIR2-SWIR1-R]' : ["SWIR2","SWIR1","R"],
'Color Infrared (vegetation)[NIR-R-G]' : ["NIR","R","G"],
'Agriculture [SWIR1-NIR-B]' : ["SWIR1","NIR","B"],
'Healthy Vegetation [NIR-SWIR1-B]': ["NIR","SWIR1","B"],
'Land/Water [NIR-SWIR1-R]':["NIR","SWIR1","R"],
'Natural With Atmospheric Removal [SWIR2-NIR-G]': ["SWIR2","NIR","G"],
'Shortwave Infrared [SWIR2-NIR-R]': ["SWIR2","NIR","R"],
'Vegetation Analysis [SWIR1-NIR-R]': ["SWIR1","NIR","R"]
};
// Dictionaries and lists of available indices
var indexDic = {'NDVI' : ['NDVI'],
'EVI' : ['EVI'],
'SAVI' : ['SAVI'],
'MSAVI' : ['MSAVI'],
'NDMI': ['NDMI'],
'NBR':['NBR'],
//'NBR2': ['NBR2'], //uncomment to add NBR2 to list
'NDWI': ['NDWI'],
'BSI': ['BSI'],
'GNDVI' : ['GNDVI'],
'NDBI' : ['NDBI'],
'NDSI' : ['NDSI']
};
var indexList = [['B'], ['G'], ['R'], ['NIR'], ['SWIR1'],
['SWIR2'], ['RedEdge1'], ['RedEdge4'], ['NDVI'],
['EVI'], ['SAVI'], ['MSAVI'], ['NDMI'],
['NBR'], //['NBR2'], //uncomment to add NBR2 to list
['NDWI'], ['BSI'],
['GNDVI'], ['NDBI'], ['NDSI'],
['valid_pixels']];
// Load image collections
// Landsat
var imCol5 = ee.ImageCollection('LANDSAT/LT05/C02/T1_L2');
var imCol7 = ee.ImageCollection('LANDSAT/LE07/C02/T1_L2');
var imCol8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2');
var imCol9 = ee.ImageCollection('LANDSAT/LC09/C02/T1_L2');
var imCol = imCol5.merge(imCol7).merge(imCol8).merge(imCol9);
var landsatMerged = ee.ImageCollection(imCol);
// Sentinel
var sentinel = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED");
var s2Clouds = ee.ImageCollection("COPERNICUS/S2_CLOUD_PROBABILITY");
var drawingTools = Map.drawingTools();
/**************************
* ***** Functions *****
**************************/
// Some of the following functions are the same or transformed functions
// in the scripts of "Introduction to Google Earth Engine Course" from Marius Philipp (University Wuerzburg).
// When the functions have the same forms as his script, you can see the script's name.
function processingLS89(startYear,endYear,startMonth,endMonth,maxCloudProbability){
var mergedImage = imCol8.merge(imCol9);
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
// Filter images for the first part of the year
var monthFilteredImage1= mergedImage.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'));
// Filter images for the second part of the year
var monthFilteredImage2= mergedImage.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'))
// Merge the filtered images from both parts
var monthFilteredImageMerged = monthFilteredImage1.merge(monthFilteredImage2).sort("system:time_start");
// Apply additional filters and processing steps to the merged images
var filteredImage = monthFilteredImageMerged
.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.map(maskL8)
.map(renameBandsL8)
.map(applyScaleFactorsLS);
} else {
// Filter images for the selected time range and apply additional filters and processing steps
var filteredImage = mergedImage.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear, 'year'))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
.map(maskL8)
.map(renameBandsL8)
.map(applyScaleFactorsLS);
}
print("Single Landsat 8/9 images (coudmasked)", filteredImage.sort('system:time_start'));
// Add spectral indices
var lsCollection = filteredImage.map(ndvi)
.map(evi)
.map(savi)
.map(msavi)
.map(ndmiLs)
.map(nbr)
//.map(nbr2) //uncomment to add NBR2 to list
.map(ndwi)
.map(bsi)
.map(gndvi)
.map(ndbi)
.map(ndsi);
// Sort Imagecollection by time
lsCollection = lsCollection.sort('system:time_start');
// Define date of earliest available data
var startDate = ee.Date(lsCollection.first().get('system:time_start'));
// Define date of latest available data
var endDate = ee.Date(lsCollection.limit(1, 'system:time_start', false)
.first().get('system:time_start'));
// Convert start date year string into a number
var startAnn = ee.Number.parse(startDate.format('YYYY'));
// Convert end date year string into a number
var endAnn = ee.Number.parse(endDate.format('YYYY'));
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
// Define months as a sequence from first month with available data until endmonth
var months = ee.List.sequence(startMonth, 12).cat(ee.List.sequence(1, endMonth));
// Define years as a sequence from the first year with available data until year before endyear
var years = ee.List.sequence(startAnn, endAnn.subtract(1));
// Create aggregated images per year
var finalLSCol = ee.ImageCollection.fromImages(
years.map(function(y) {
// Filter by year
var ic1 = lsCollection.filter(ee.Filter.calendarRange(y, y, 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12,'month'));
var ic2 = lsCollection.filter(ee.Filter.calendarRange(ee.Number(y).add(1), ee.Number(y).add(1), 'year'))
.filter(ee.Filter.calendarRange(1, endMonth,'month'));
var bothImages = ic1.merge(ic2);
// Check number of images within one year
var bothImagesSize = bothImages.size();
var count = bothImages.select('B').reduce(ee.Reducer.count()).rename('valid_pixels');
// Apply reducer
var reducedImages = bothImages.reduce(reducers);
// Get the middle image of the collection for the system:time_start info
//var bothImagesSizeDiv = bothImagesSize.divide(2);
//var bothImagesSizeDivRound = ee.Number(bothImagesSizeDiv).ceil();
var imagesList = bothImages.toList(bothImagesSize);
var imagesMid = imagesList.get(0);
var originalBandNames = bothImages.first().bandNames();
// Return aggregated current year and define the current year,
// date and the unix time of the middle image wihtin the year
return reducedImages
.rename(originalBandNames)
.set('Year', y)
.set('No_of_images', bothImagesSize)
.addBands(count)
.float()
.copyProperties(ee.Image(imagesMid),['system:time_start']);
})
);
} else {
var finalLSCol = createMedianCol(lsCollection);
}
print("Aggregated export images", finalLSCol);
// Years that exist in the aggregated export images
var yearsFromMedian = finalLSCol.aggregate_array("Year");
// Inserted years in the app
var yearsFromApp = ee.List.sequence(startYear, endYear)
// Years of not existing images
var difference = yearsFromApp.removeAll(yearsFromMedian);
// Convert each item in the list to a string
var stringList = difference.map(function(item) {
return ee.String(ee.Number(item).toInt().format());
});
// Join the strings with a comma
var joinedString = stringList.join(', ');
// Check if the list is not empty
var isEmpty = difference.size().eq(0);
isEmpty.evaluate(function(isListEmpty) {
if (!isListEmpty) {
print("Warning! No images in year ", joinedString.getInfo());
}
});
return finalLSCol;
}
function checkNumberOfImagesL89(startYear,endYear,startMonth,endMonth,maxCloudProbability){
var mergedImage = imCol8.merge(imCol9);
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
// Filter images for the first part of the year
var monthFilteredImage1= mergedImage.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'));
// Filter images for the second part of the year
var monthFilteredImage2= mergedImage.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'))
// Merge the filtered images from both parts
var monthFilteredImageMerged = monthFilteredImage1.merge(monthFilteredImage2).sort("system:time_start");
// Apply additional filters and processing steps to the merged images
var filteredImage = monthFilteredImageMerged
.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
} else {
// Filter images for the selected time range and apply additional filters and processing steps
var filteredImage = mergedImage.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear, 'year'))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
}
return filteredImage.size()
}
// preprocess landsat4, 5, 7
function filterLandsat457(image,startMonth,endMonth,maxCloudProbability){
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
var filteredImage1 = image.filter(ee.Filter.bounds(selFeature)) // filter based on bounding geometry
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability)) // filter cloud
.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year')) //filter date
.filter(ee.Filter.calendarRange(1, endMonth, 'month'))
.map(maskL8) // additional cloud mask
.map(renameBandsL457) // rename bands
.map(applyScaleFactorsLS); //apply scale factors
var filteredImage2 = image.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'))
.map(maskL8)
.map(renameBandsL457)
.map(applyScaleFactorsLS);
var filteredImage = filteredImage1.merge(filteredImage2).sort("system:time_start");
} else {
var filteredImage = image.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
.map(maskL8)
.map(renameBandsL457)
.map(applyScaleFactorsLS);
}
return filteredImage;
}
// preprocess landsat 8, 9
function filterLandsat8(image,startMonth,endMonth,maxCloudProbability){
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
var filteredImage1 = image.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'))
.map(maskL8)
.map(renameBandsL8)
.map(applyScaleFactorsLS);
var filteredImage2 = image.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'))
.map(maskL8)
.map(renameBandsL8)
.map(applyScaleFactorsLS);
var filteredImage = filteredImage1.merge(filteredImage2).sort("system:time_start")
} else {
var filteredImage = image.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUD_COVER', maxCloudProbability))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
.map(maskL8)
.map(renameBandsL8)
.map(applyScaleFactorsLS)
.sort("system:time_start");
}
return filteredImage;
}
function mergeLandsat(startYear, endYear,startMonth,endMonth){
var mergedImage = filterLandsat457(imCol5,startMonth,endMonth,maxCloudProbability)
.merge(filterLandsat457(imCol7,startMonth,endMonth,maxCloudProbability))
.merge(filterLandsat8(imCol8,startMonth,endMonth,maxCloudProbability))
.merge(filterLandsat8(imCol9,startMonth,endMonth,maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear,'year'));
// Add all indices as bands to image collection
var lsCollection = mergedImage.map(ndvi)
.map(evi)
.map(savi)
.map(msavi)
.map(ndmiLs)
.map(nbr)
//.map(nbr2) //uncomment to add NBR2 to list
.map(ndwi)
.map(bsi)
.map(gndvi)
.map(ndbi)
.map(ndsi);
print("Single Landsat 5,7,8,9 images (cloudmasked)", mergedImage.sort('system:time_start'));
lsCollection = lsCollection.sort('system:time_start')
// Define date of earliest available data
var startDate = ee.Date(lsCollection.first().get('system:time_start'));
// Define date of latest available data
var endDate = ee.Date(lsCollection.limit(1, 'system:time_start', false)
.first().get('system:time_start'));
// Convert start date year string into a number
var startAnn = ee.Number.parse(startDate.format('YYYY'));
// Convert end date year string into a number
var endAnn = ee.Number.parse(endDate.format('YYYY'));
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
// Define months as a sequence from first month with available data until endmonth
var months = ee.List.sequence(startMonth, 12).cat(ee.List.sequence(1, endMonth));
// Define years as a sequence from the first year with available data until year before endyear
var years = ee.List.sequence(startAnn, endAnn.subtract(1));
// Create aggregated images per year
var finalLandsatCol = ee.ImageCollection.fromImages(
years.map(function(y) {
// Filter by year
var ic1 = lsCollection.filter(ee.Filter.calendarRange(y, y, 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12,'month'));
var ic2 = lsCollection.filter(ee.Filter.calendarRange(ee.Number(y).add(1), ee.Number(y).add(1), 'year'))
.filter(ee.Filter.calendarRange(1, endMonth,'month'));
var bothImages = ic1.merge(ic2);
// Check number of images within one year
var bothImagesSize = bothImages.size();
var count = bothImages.select('B').reduce(ee.Reducer.count()).rename('valid_pixels');
// Apply reducer
var reducedImages = bothImages.reduce(reducers);
// Get the middle image of the collection for the system:time_start info
// ----> required by GEE to work with times
//var bothImagesSizeDiv = bothImagesSize.divide(2);
//var bothImagesSizeDivRound = bothImagesSizeDiv.ceil();
var imagesList = bothImages.toList(bothImagesSize);
var imagesMid = imagesList.get(0);
var originalBandNames = bothImages.first().bandNames();
// Return aggregated current year and define the current year,
// date and the unix time of the middle image wihtin the year
return reducedImages
.rename(originalBandNames)
.set('Year', y)
.set('No_of_images', bothImagesSize)
.addBands(count)
.float()
.copyProperties(ee.Image(imagesMid),['system:time_start']);
})
);
} else {
var finalLandsatCol = createMedianCol(lsCollection);
}
print("Aggregated export images landsat merged", finalLandsatCol);
// Years that exist in the aggregated export images
var yearsFromMedian = finalLandsatCol.aggregate_array("Year");
// Inserted years in the app
var yearsFromApp = ee.List.sequence(startYear, endYear)
// Years of not existing images
var difference = yearsFromApp.removeAll(yearsFromMedian);
// Convert each item in the list to a string
var stringList = difference.map(function(item) {
return ee.String(ee.Number(item).toInt().format());
});
// Join the strings with a comma
var joinedString = stringList.join(', ');
// Check if the list is not empty
var isEmpty = difference.size().eq(0);
isEmpty.evaluate(function(isListEmpty) {
if (!isListEmpty) {
print("Warning! No images in year ", joinedString.getInfo());
}
});
return finalLandsatCol;
}
function checkNumberOfImagesLS(startYear, endYear,startMonth,endMonth){
var lsCollection = filterLandsat457(imCol5,startMonth,endMonth,maxCloudProbability)
.merge(filterLandsat457(imCol7,startMonth,endMonth,maxCloudProbability))
.merge(filterLandsat8(imCol8,startMonth,endMonth,maxCloudProbability))
.merge(filterLandsat8(imCol9,startMonth,endMonth,maxCloudProbability))
.filter(ee.Filter.calendarRange(startYear, endYear,'year'))
.sort('system:time_start');
return lsCollection.size();
}
var checkNumberOfImagesS2 = function(startYear,endYear,startMonth,endMonth,maxCloudProbability){
var sentinel2Bounded = sentinel.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE', maxCloudProbability));
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
var s2Image1= sentinel2Bounded.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'));
var s2Image2= sentinel2Bounded.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'));
var s2Filtered = s2Image1.merge(s2Image2).sort("system:time_start").map(maskEdges);
} else {
var s2Filtered = sentinel2Bounded.filter(ee.Filter.calendarRange(startYear, endYear, 'year'))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
.map(maskEdges);
}
return s2Filtered.size()
}
// filter sentinel-2 by time and aoi and mask clouds.
var filterAndMaskS2 = function(startYear,endYear,startMonth,endMonth,maxCloudProbability){
var sentinel2Bounded = sentinel.filter(ee.Filter.bounds(selFeature))
.filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE', maxCloudProbability));
var s2CloudsBounded = s2Clouds.filter(ee.Filter.bounds(selFeature));
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
var s2Image1= sentinel2Bounded.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'));
var s2Image2= sentinel2Bounded.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'));
var s2Filtered = s2Image1.merge(s2Image2).sort("system:time_start").map(maskEdges);
var s2CloudsImage1= s2CloudsBounded.filter(ee.Filter.calendarRange(startYear.add(1), endYear, 'year'))
.filter(ee.Filter.calendarRange(1, endMonth, 'month'));
var s2CloudsImage2= s2CloudsBounded.filter(ee.Filter.calendarRange(startYear, endYear.subtract(1), 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12, 'month'));
var s2CloudsFiltered = s2CloudsImage1.merge(s2CloudsImage2).sort("system:time_start");
} else {
var s2Filtered = sentinel2Bounded.filter(ee.Filter.calendarRange(startYear, endYear, 'year'))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'))
.map(maskEdges);
var s2CloudsFiltered = s2CloudsBounded.filter(ee.Filter.calendarRange(startYear, endYear, 'year'))
.filter(ee.Filter.calendarRange(startMonth, endMonth, 'month'));
}
// https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_CLOUD_PROBABILITY
var s2FilteredAndCloudMasked = ee.Join.saveFirst('cloud_mask').apply({
primary: s2Filtered,
secondary: s2CloudsFiltered,
condition:
ee.Filter.equals({leftField: 'system:index', rightField: 'system:index'})
});
var s2FilteredAndCloudMaskedFinished = ee.ImageCollection(s2FilteredAndCloudMasked).map(function(img) {
var clouds = ee.Image(img.get('cloud_mask')).select('probability');
var isNotCloud = clouds.lt(50);
return img.updateMask(isNotCloud);
});
// rename bands and apply scale factors
var s2FilteredCloudMaskedRenamedHarmonized = s2FilteredAndCloudMaskedFinished.map(renameBandsS2)
.map(applyScaleFactorsS2);
// add spectral index
var s2Collection = s2FilteredCloudMaskedRenamedHarmonized.map(ndvi)
.map(evi)
.map(savi)
.map(msavi)
.map(ndmiS2)
.map(nbr)
//.map(nbr2) //uncomment to add NBR2 to list
.map(ndwi)
.map(bsi)
.map(gndvi)
.map(ndbi)
.map(ndsi);
print("Single Sentinel-2 images (cloudmasked)",s2FilteredCloudMaskedRenamedHarmonized.sort('system:time_start'));
s2Collection = s2Collection.sort('system:time_start')
// Define date of earliest available data
var startDate = ee.Date(s2Collection.first().get('system:time_start'));
// Define date of latest available data
var endDate = ee.Date(s2Collection.limit(1, 'system:time_start', false)
.first().get('system:time_start'));
// Convert start date year string into a number
var startAnn = ee.Number.parse(startDate.format('YYYY'));
// Convert end date year string into a number
var endAnn = ee.Number.parse(endDate.format('YYYY'));
if (ee.Number(startMonth).getInfo() > ee.Number(endMonth).getInfo()) {
// Define months as a sequence from first month with available data until endmonth
var months = ee.List.sequence(startMonth, 12).cat(ee.List.sequence(1, endMonth));
// Define years as a sequence from the first year with available data until year before endyear
var years = ee.List.sequence(startAnn, endAnn.subtract(1));
// Create aggregated images per year
var finalS2Col = ee.ImageCollection.fromImages(
years.map(function(y) {
// Filter by year
var ic1 = s2Collection.filter(ee.Filter.calendarRange(y, y, 'year'))
.filter(ee.Filter.calendarRange(startMonth, 12,'month'));
var ic2 = s2Collection.filter(ee.Filter.calendarRange(ee.Number(y).add(1), ee.Number(y).add(1), 'year'))
.filter(ee.Filter.calendarRange(1, endMonth,'month'));
var bothImages = ic1.merge(ic2);
// Check number of images within one year
var bothImagesSize = bothImages.size();
var count = bothImages.select('B').reduce(ee.Reducer.count()).rename('valid_pixels');
// Apply reducer
var reducedImages = bothImages.reduce(reducers);
// Get the middle image of the collection for the system:time_start info
// ----> required by GEE to work with times
//var bothImagesSizeDiv = bothImagesSize.divide(2);
//var bothImagesSizeDivRound = ee.Number(bothImagesSizeDiv).ceil();
var imagesList = bothImages.toList(bothImagesSize);
var imagesMid = imagesList.get(0);
var originalBandNames = bothImages.first().bandNames();
// Return aggregated current year and define the current year,
// date and the unix time of the middle image wihtin the year
return reducedImages
.rename(originalBandNames)
.set('Year', y)
.set('No_of_images', bothImagesSize)
.addBands(count)
.float()
.copyProperties(ee.Image(imagesMid),['system:time_start']);
})
);
} else {
var finalS2Col = createMedianCol(s2Collection);
}
print("Aggregated export images : ", finalS2Col);
// Years that exist in the aggregated export images
var yearsFromMedian = finalS2Col.aggregate_array("Year");
// Inserted years in the app
var yearsFromApp = ee.List.sequence(startYear, endYear)
// Years of not existing images
var difference = yearsFromApp.removeAll(yearsFromMedian);
// Convert each item in the list to a string
var stringList = difference.map(function(item) {
return ee.String(ee.Number(item).toInt().format());
});
// Join the strings with a comma
var joinedString = stringList.join(', ');
// Check if the list is not empty
var isEmpty = difference.size().eq(0);
isEmpty.evaluate(function(isListEmpty) {
if (!isListEmpty) {
print("Warning! No images in year ", joinedString.getInfo());
}
});
return finalS2Col;
};
function renewValidPixel(imgCol){
var exportCol = imgCol.map(function(image){
var valid = image.select('valid_pixels').divide(10000);
return image.addBands(valid, null, true);
});
return exportCol;
}
//------------------------- Create annual median collection ---------------------------------
// Source: "Philipp, Marius. SS21, 'Introduction to Google Earth Engine: Session 7 Trend Analysis', University Wuerzburg"
var createMedianCol = function(img){
// Define date of earliest available data
var startDate = ee.Date(img.first().get('system:time_start'));
// Define date of latest available data
var endDate = ee.Date(img.limit(1, 'system:time_start', false)
.first().get('system:time_start'));
// Convert start date year string into a number
var startAnn = ee.Number.parse(startDate.format('YYYY'));
// Convert end date year string into a number
var endAnn = ee.Number.parse(endDate.format('YYYY'));
var years = ee.List.sequence(startAnn, endAnn);
// Create aggregated images per year
var AnnualImCol = ee.ImageCollection.fromImages(
years.map(function(y) {
var currentYear = img.filter(ee.Filter.calendarRange(y, y, 'year'));
var yearSize = currentYear.size();
var count = currentYear.select('B').reduce(ee.Reducer.count()).rename('valid_pixels');
// Get the middle image of the collection for the system:time_start info
var yearSizeDiv = yearSize.divide(2);
var yearSizeDivRound = ee.Number(yearSizeDiv).ceil();
var currentYearList = currentYear.toList(yearSize);
var currentMid = currentYearList.get(0);
var originalBandNames = currentYear.first().bandNames();
return currentYear
.reduce(reducers)
.rename(originalBandNames)
.set('Year', y)
.set('No_of_images', yearSize)
.addBands(count)
.float()
.copyProperties(ee.Image(currentMid),['system:time_start']);
})
);
return AnnualImCol;
};
//------------------Mask cloud, cloud shadow, and snow--------------------------------------------------------------------//
// Source : https://gis.stackexchange.com/questions/330347/modifying-code-to-iterate-within-list-with-google-earth-engine
// Source: "Philipp, Marius. SS21, 'Introduction to Google Earth Engine: Session 6. Time Series', University Wuerzburg"
function maskL8(image) {
var cloudShadowBitMask = 1 << 3;
var cloudsBitMask = 1 << 5;
var snowBitMask = 1 << 4;
var qa = image.select('QA_PIXEL');
var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
.and(qa.bitwiseAnd(cloudsBitMask).eq(0))
.and(qa.bitwiseAnd(snowBitMask).eq(0));
return image.updateMask(mask)
.select("SR_B[0-9]*")
.copyProperties(image, ["system:time_start"]);
}
// https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_CLOUD_PROBABILITY
function maskCloudS2(img) {
var clouds = ee.Image(img.get('cloud_mask')).select('probability');
var isNotCloud = clouds.lt(maxCloudProbability);
return img.updateMask(isNotCloud);
}
// https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2_CLOUD_PROBABILITY
function maskEdges(s2Img) {
return s2Img.updateMask(
s2Img.select('B8A').mask().updateMask(s2Img.select('B9').mask()));
}
//------------------------------- Select and rename bands -----------------------------------
// Source: "Philipp, Marius. SS21, 'Introduction to Google Earth Engine: Session 6. Time Series', University Wuerzburg"
function renameBandsS2(image) {
var bands = ['B2', 'B3', 'B4', 'B5', 'B8', 'B8A', 'B11', 'B12'];
var newBands = ['B', 'G', 'R', 'RedEdge1', 'NIR', 'RedEdge4', 'SWIR1', 'SWIR2'];
return image.select(bands).rename(newBands).copyProperties(image, ["system:time_start"]);
}
function renameBandsL8(image) {
var bands = ['SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7'];
var newBands = ['B', 'G', 'R', 'NIR', 'SWIR1', 'SWIR2'];
return image.select(bands).rename(newBands).copyProperties(image, ["system:time_start"]);
}
function renameBandsL457(image) {
var bands = ['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B7'];
var newBands = ['B', 'G', 'R', 'NIR', 'SWIR1', 'SWIR2'];
return image.select(bands).rename(newBands).copyProperties(image, ["system:time_start"]);
}
//----------------------------- Scaling and harmonization ----------------------------------
//https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C02_T1_L2
function applyScaleFactorsLS(image) {
var opticalBands = image.select('B', 'G', 'R', 'NIR', 'SWIR1', 'SWIR2')
.multiply(0.0000275)
.add(-0.2)
.clamp(0, 1);
return image.addBands(opticalBands, null, true);
}
function applyScaleFactorsS2(image) {
var opticalBands = image.select('B', 'G', 'R', 'RedEdge1', 'NIR', 'RedEdge4', 'SWIR1', 'SWIR2')
.multiply(0.0001)
.clamp(0,1);
return image.addBands(opticalBands, null, true);
}
//------------------------ Define functions for Spectral indices --------------------------
function bsi(image) {
var bsiVar = image.expression(
"((RED + SWIR) - (NIR + BLUE)) / ((RED + SWIR) + (NIR + BLUE))",
{
SWIR: image.select("SWIR1"),
RED: image.select("R"),
BLUE: image.select("B"),
NIR: image.select("NIR")
});
return image
.addBands(bsiVar
.rename('BSI'))
.float();
}
function ndvi(image) {
var ndviVar = image.expression(
"(NIR - RED)/(NIR + RED)",
{
NIR: image.select("NIR"),
RED: image.select("R"),
});
return image
.addBands(ndviVar
.rename('NDVI'))
.float();
}
function evi(image) {
var eviVar = image.expression(
"2.5 * (NIR - RED) / (NIR + 6*RED - 7.5*BLUE + 1)",
{
NIR: image.select("NIR"),
RED: image.select("R"),
BLUE: image.select("B"),
});
return image
.addBands(eviVar
.rename('EVI'))
.float();
}
function savi(image) {
var saviVar = image.expression(
"((NIR - RED) / (NIR + RED + 0.5)) * 1.5",
{
NIR: image.select("NIR"),
RED: image.select("R"),
});
return image
.addBands(saviVar
.rename('SAVI'))
.float();
}
function msavi(image) {
var msaviVar = image.expression(
"(2 * NIR + 1 - ( (2 * NIR + 1) ** 2 - 8 * (NIR - RED)) ** (1/2) ) / 2",
{
NIR: image.select("NIR"),
RED: image.select("R"),
});
return image
.addBands(msaviVar
.rename('MSAVI'))
.float();
}
function ndmiLs(image) {
var ndmiVar = image.expression(
"(NIR - SWIR1) / (NIR + SWIR1)",
{
NIR: image.select("NIR"),
SWIR1: image.select("SWIR1"),
});
return image
.addBands(ndmiVar
.rename('NDMI'))
.float();
}
function ndmiS2(image) {
var ndmiVar = image.expression(
"(NIR - SWIR1) / (NIR + SWIR1)",
{
NIR: image.select("NIR"),
SWIR1: image.select("SWIR1"),
});
return image
.addBands(ndmiVar
.rename('NDMI'))
.float();
}
function nbr(image) {
var nbrVar = image.expression(
"(NIR - SWIR2) / (NIR + SWIR2)",
{
NIR: image.select("NIR"),
SWIR2: image.select("SWIR2"),
});
return image
.addBands(nbrVar
.rename('NBR'))
.float();
}
// // uncomment code below to add nbr2 to list // NBR2 (Normalized Burn Ratio 2): Burn & Fire Index.
// A modification of the NBR, useful in postfire recovery studies, highlights vegetation with high water content.
// function nbr2(image) {
// var nbr2Var = image.expression(
// "(SWIR1 - SWIR2) / (SWIR1 + SWIR2)",
// {
// SWIR1: image.select("SWIR1"),
// SWIR2: image.select("SWIR2"),
// });
// return image
// .addBands(nbr2Var
// .rename('NBR2'))
// .float();
// }
function ndwi(image) {
var ndwiVar = image.expression(
"(GREEN - NIR) / (GREEN + NIR)",
{
GREEN: image.select("G"),
NIR: image.select("NIR"),
});
return image
.addBands(ndwiVar
.rename('NDWI'))
.float();
}
function gndvi(image) {
var gndviVar = image.expression(
"(NIR - GREEN) / (NIR + GREEN)",
{
NIR: image.select("NIR"),
GREEN: image.select("G"),
});
return image
.addBands(gndviVar
.rename('GNDVI'))
.float();
}
function ndbi(image) {
var ndbiVar = image.expression(
"(SWIR1 - NIR)/(SWIR1 + NIR)",
{
SWIR1: image.select("SWIR1"),
NIR: image.select("NIR"),
});
return image
.addBands(ndbiVar
.rename('NDBI'))
.float();
}
function ndsi(image) {
var ndsiVar = image.expression(
"(GREEN - SWIR1)/(GREEN + SWIR1)",
{
GREEN: image.select("G"),
SWIR1: image.select("SWIR1"),
});
return image
.addBands(ndsiVar
.rename('NDSI'))
.float();
}
/**************************
********* STYLES *******
**************************/
var styleP = {
margin: '4px 8px', fontSize: '12px', fontWeight: '100',
backgroundColor: 'rgba(0, 0, 0, 0.0)', color: 'FFF'
};
var styleTitle = {color: 'FFF', fontSize: '22px', fontWeight: '700', backgroundColor: 'rgba(0,0,0,0.0)',
margin: '3px 4px 2px 4px'};
var styleSubtitle = {color: 'FFF', fontSize: '17px', fontWeight: '600', backgroundColor: 'rgba(0,0,0,0.0)',
margin: '3px 4px 2px 4px'};
var styleSteps = {margin: '4px 8px', fontSize: '12px', fontWeight: '500',
backgroundColor: 'rgba(0, 0, 0, 0.0)', color: 'FFF'};
var styleLabels = {stretch: 'horizontal', color: '#7F7F7F', fontSize: '13px',
fontWeight: '100', backgroundColor: 'rgba(0,0,0,0.0)'};
var styleLabelsWhite = {stretch: 'horizontal', color: 'FFF', fontSize: '13px',
fontWeight: '100', backgroundColor: 'rgba(0,0,0,0.0)'};
var styleButtons = {stretch: 'horizontal', color: '#5b5b5b', fontSize: '13px',
fontWeight: '500', backgroundColor: 'rgba(0,0,0,0.0)'};
var styleButtonPanels = {stretch: 'horizontal', position: 'bottom-left', padding: '4px',
backgroundColor: 'rgba(0,0,0,0.0)'
};