-
Notifications
You must be signed in to change notification settings - Fork 65
/
LandTrendr.js
1741 lines (1455 loc) · 72.1 KB
/
LandTrendr.js
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
/**
* @license
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Justin Braaten (Google)
* @author Zhiqiang Yang (USDA Forest Service)
* @author Robert Kennedy (Oregon State University)
* MODIFIED 1/2022 Ben Roberts-Pierel (Oregon State University)
*
* @description This file contains functions for working with the LandTrendr
* change detection algorithm in Google Earth Engine. For information on
* LandTrendr and usage of functions in this file see
* https://github.com/eMapR/LT-GEE. Please post issues to
* https://github.com/eMapR/LT-GEE/issues.
*/
// #############################################################################
// ### VERSION ###
// #############################################################################
exports.version = '0.2.0';
//print a warning to the user that this version is now using collection 2
print('IMPORTANT! Please be advised:');
print('- This version of the LandTrendr.js modules')
print(' uses Landsat Collection 2 data');
print('- This version (0.2.0) does NOT use the Roy et al. coefficients');
//########################################################################################################
//##### ANNUAL SR TIME SERIES COLLECTION BUILDING FUNCTIONS #####
//########################################################################################################
//------ FILTER A COLLECTION FUNCTION -----
var filterCollection = function(year, startDay, endDay, sensor, aoi){
return ee.ImageCollection('LANDSAT/'+ sensor + '/C02/T1_L2')
.filterBounds(aoi)
.filterDate(year+'-'+startDay, year+'-'+endDay);
};
//------ BUILD A COLLECTION FOR A GIVEN SENSOR AND YEAR -----
var buildSensorYearCollection = function(year, startDay, endDay, sensor, aoi, exclude){
var startMonth = parseInt(startDay.substring(0, 2));
var endMonth = parseInt(endDay.substring(0, 2));
var srCollection;
if(startMonth > endMonth){
var oldYear = (parseInt(year)-1).toString();
var newYear = year;
var oldYearStartDay = startDay;
var oldYearEndDay = '12-31';
var newYearStartDay = '01-01';
var newYearEndDay = endDay;
var oldYearCollection = filterCollection(oldYear, oldYearStartDay, oldYearEndDay, sensor, aoi);
var newYearCollection = filterCollection(newYear, newYearStartDay, newYearEndDay, sensor, aoi);
srCollection = ee.ImageCollection(oldYearCollection.merge(newYearCollection));
} else {
srCollection = filterCollection(year, startDay, endDay, sensor, aoi);
}
srCollection = removeImages(srCollection, exclude)
return srCollection;
};
exports.buildSensorYearCollection = buildSensorYearCollection
//------ RETRIEVE A SENSOR SR COLLECTION FUNCTION -----
//scaling values source: https://www.usgs.gov/faqs/how-do-i-use-scale-factor-landsat-level-2-science-products
//define a function to apply Collection 2 scaling coefficients
var scaleLTdata = function(img){
return ((img.multiply(0.0000275)).add(-0.2)).multiply(10000).toUint16();
};
var getSRcollection = function(year, startDay, endDay, sensor, aoi, maskThese, exclude) {
// make sure that mask labels are correct
maskThese = (typeof maskThese !== 'undefined') ? maskThese : ['cloud','shadow','snow','water'];
//var maskOptions = ['cloud', 'shadow', 'snow', 'water'];
var maskOptions = ['cloud', 'shadow', 'snow', 'water', 'waterplus','nonforest']; // add new water and forest mask here Peter Clary 5/20/2020
for(var i in maskThese){
maskThese[i] = maskThese[i].toLowerCase();
var test = maskOptions.indexOf(maskThese[i]);
if(test == -1){
print('error: '+maskThese[i]+' is not included in the list maskable features. Please see ___ for list of maskable features to include in the maskThese parameter');
return 'error';
}
}
// get a landsat collection for given year, day range, and sensor
var srCollection = buildSensorYearCollection(year, startDay, endDay, sensor, aoi, exclude);
// apply the harmonization function to LC08 (if LC08), subset bands, unmask, and resample
srCollection = srCollection.map(function(img) {
var dat = ee.Image(
ee.Algorithms.If(
(sensor == 'LC08') || (sensor == 'LC09'), // condition - if image is OLI
scaleLTdata(img.select(['SR_B2','SR_B3','SR_B4','SR_B5','SR_B6','SR_B7'],['B1', 'B2', 'B3', 'B4', 'B5', 'B7'])).unmask(),
//NOTE based on analysis of the effects of Roy coefficients for various places around the world
//we have opted to NOT include their use in this version of these modules
scaleLTdata(img.select(['SR_B1','SR_B2','SR_B3','SR_B4','SR_B5','SR_B7'],['B1', 'B2', 'B3', 'B4', 'B5', 'B7'])) // false - else select out the reflectance bands from the non-OLI image
.unmask() // ...unmask any previously masked pixels
//.resample('bicubic') // ...resample by bicubic
.set('system:time_start', img.get('system:time_start')) // ...set the output system:time_start metadata to the input image time_start otherwise it is null
)
);
// makes a global forest mask
var forCol = ee.ImageCollection("COPERNICUS/Landcover/100m/Proba-V/Global"); //PETER ADD
var imgFor = forCol.toBands(); //PETER ADD
var forestimage = imgFor.select('2015_forest_type') //PETER ADD
// Computes the forest mask into a binary using an expression.
var selectedForests = forestimage.expression( //PETER ADD
'Band >= 0 ? 1 : 0', { //PETER ADD
'Band': forestimage //PETER ADD
}).clip(aoi); //PETER ADD
//makes a global water mask
var MappedWater = ee.Image("JRC/GSW1_1/GlobalSurfaceWater"); //PETER ADD
// calculates water persistence 0 to 100 //PETER ADD
var MappedWaterBinary = MappedWater.expression( //PETER ADD
'band > 99 ? 0 : 1 ', { //PETER ADD
'band': MappedWater.select('recurrence') //PETER ADD
}).clip(aoi); //PETER ADD
var mask = ee.Image(1);
if(maskThese.length !== 0){
var qa = img.select('QA_PIXEL');
for(var i in maskThese){
if(maskThese[i] == 'water'){mask = qa.bitwiseAnd(1<<7).eq(0).multiply(mask)}
if(maskThese[i] == 'shadow'){mask = qa.bitwiseAnd(1<<4).eq(0).multiply(mask)}
if(maskThese[i] == 'snow'){mask = qa.bitwiseAnd(1<<5).eq(0).multiply(mask)}
if(maskThese[i] == 'cloud'){mask = qa.bitwiseAnd(1<<3).eq(0).multiply(mask)}
// added masked options for the UI
if(maskThese[i] == 'waterplus'){mask = mask.mask(MappedWaterBinary)} //PETER ADD
if(maskThese[i] == 'nonforest'){mask = mask.mask(selectedForests)} // PETER ADD
}
return dat.mask(mask); //apply the mask - 0's in mask will be excluded from computation and set to opacity=0 in display
} else{
return dat;
}
});
return srCollection; // return the prepared collection
};
exports.getSRcollection = getSRcollection;
//------ FUNCTION TO COMBINE LT05, LE07, LC08 and LC09 COLLECTIONS -----
var getCombinedSRcollectionOrig = function(year, startDay, endDay, aoi, maskThese) {
var lt5 = getSRcollection(year, startDay, endDay, 'LT05', aoi, maskThese); // get TM collection for a given year, date range, and area
var le7 = getSRcollection(year, startDay, endDay, 'LE07', aoi, maskThese); // get ETM+ collection for a given year, date range, and area
var lc8 = getSRcollection(year, startDay, endDay, 'LC08', aoi, maskThese); // get OLI collection for a given year, date range, and area
var lc9 = getSRcollection(year, startDay, endDay, 'LC09', aoi, maskThese); // get OLI collection for a given year, date range, and area
var mergedCollection = ee.ImageCollection(lt5.merge(le7).merge(lc8).merge(lc9)); // merge the individual sensor collections into one imageCollection object
return mergedCollection; // return the Imagecollection
};
var getCombinedSRcollection = function(year, startDay, endDay, aoi, maskThese, exclude) {
exclude = (typeof exclude !== 'undefined') ? exclude : {}; // default to not exclude any images
var lt5 = getSRcollection(year, startDay, endDay, 'LT05', aoi, maskThese, exclude); // get TM collection for a given year, date range, and area
var le7 = getSRcollection(year, startDay, endDay, 'LE07', aoi, maskThese, exclude); // get ETM+ collection for a given year, date range, and area
var lc8 = getSRcollection(year, startDay, endDay, 'LC08', aoi, maskThese, exclude); // get OLI collection for a given year, date range, and area
var lc9 = getSRcollection(year, startDay, endDay, 'LC09', aoi, maskThese, exclude); // get OLI collection for a given year, date range, and area
var mergedCollection = ee.ImageCollection(lt5.merge(le7).merge(lc8).merge(lc9)); // merge the individual sensor collections into one imageCollection object
//mergedCollection = removeImages(mergedCollection, exclude);
return mergedCollection; // return the Imagecollection
};
exports.getCombinedSRcollection = getCombinedSRcollection;
//------ FUNCTION TO REDUCE COLLECTION TO SINGLE IMAGE PER YEAR BY MEDOID -----
/*
LT expects only a single image per year in a time series, there are lost of ways to
do best available pixel compositing - we have found that a mediod composite requires little logic
is robust, and fast
Medoids are representative objects of a data set or a cluster with a data set whose average
dissimilarity to all the objects in the cluster is minimal. Medoids are similar in concept to
means or centroids, but medoids are always members of the data set.
*/
// make a medoid composite with equal weight among indices
var medoidMosaic = function(inCollection, dummyCollection) {
// fill in missing years with the dummy collection
// ** braaten edit 2023-05-02: toList and If are resource intensive, simply
// ** merging the inCollection and dummyCollection should achieve the goal
// ** of have at least one image for the median operation.
var imageCount = inCollection.toList(1).length(); // get the number of images
var finalCollection = ee.ImageCollection(ee.Algorithms.If(imageCount.gt(0), inCollection, dummyCollection)); // if the number of images in this year is 0, then use the dummy collection, otherwise use the SR collection
// var finalCollection = inCollection.merge(dummyCollection);
// calculate median across images in collection per band
var median = finalCollection.median(); // calculate the median of the annual image collection - returns a single 6 band image - the collection median per band
// calculate the different between the median and the observation per image per band
var difFromMedian = finalCollection.map(function(img) {
var diff = ee.Image(img).subtract(median).pow(ee.Image.constant(2)); // get the difference between each image/band and the corresponding band median and take to power of 2 to make negatives positive and make greater differences weight more
return diff.reduce('sum').addBands(img); // per image in collection, sum the powered difference across the bands - set this as the first band add the SR bands to it - now a 7 band image collection
});
// get the medoid by selecting the image pixel with the smallest difference between median and observation per band
return ee.ImageCollection(difFromMedian).reduce(ee.Reducer.min(7)).select([1,2,3,4,5,6], ['B1','B2','B3','B4','B5','B7']); // find the powered difference that is the least - what image object is the closest to the median of teh collection - and then subset the SR bands and name them - leave behind the powered difference band
};
//------ FUNCTION TO APPLY MEDOID COMPOSITING FUNCTION TO A COLLECTION -------------------------------------------
var buildMosaic = function(year, startDay, endDay, aoi, dummyCollection, maskThese, exclude) { // create a temp variable to hold the upcoming annual mosiac
exclude = (typeof exclude !== 'undefined') ? exclude : {}; // default to not exclude any images
var collection = getCombinedSRcollection(year, startDay, endDay, aoi, maskThese, exclude); // get the SR collection
var img = medoidMosaic(collection, dummyCollection) // apply the medoidMosaic function to reduce the collection to single image per year by medoid
.set('system:time_start', (new Date(year,8,1)).valueOf()); // add the year to each medoid image - the data is hard-coded Aug 1st
return ee.Image(img).toUint16(); // return as image object
};
//------ FUNCTION TO BUILD ANNUAL MOSAIC COLLECTION ------------------------------
var buildSRcollection = function(startYear, endYear, startDay, endDay, aoi, maskThese, exclude) {
exclude = (typeof exclude !== 'undefined') ? exclude : {}; // default to not exclude any images
var dummyCollection = ee.ImageCollection([ee.Image([0,0,0,0,0,0]).mask(ee.Image(0))]); // make an image collection from an image with 6 bands all set to 0 and then make them masked values
var imgs = []; // create empty array to fill
for (var i = startYear; i <= endYear; i++) { // for each year from hard defined start to end build medoid composite and then add to empty img array
var tmp = buildMosaic(i, startDay, endDay, aoi, dummyCollection, maskThese, exclude); // build the medoid mosaic for a given year
imgs = imgs.concat(tmp.set('composite_year',i).set('system:time_start', (new Date(i,8,1)).valueOf())); // concatenate the annual image medoid to the collection (img) and set the date of the image - hard coded to the year that is being worked on for Aug 1st
}
return ee.ImageCollection(imgs); // return the array img array as an image collection
};
exports.buildSRcollection = buildSRcollection;
//------ FUNCTION TO RETURN A LIST OF IMAGES THAT GO INTO ANNUAL SR COMPOSITE COLLECTION ------------------------------
function getImgID(img){return ee.String(ee.Image(img).get('system:id'));}
function getImgIndex(img){return ee.String(ee.Image(img).get('system:index'));}
var getCollectionIDlist = function(startYear, endYear, startDay, endDay, aoi, exclude) {
exclude = (typeof exclude !== 'undefined') ? exclude : {}; // default to not exclude any images
var first = true;
for (var i = startYear; i <= endYear; i++){
var lt5 = buildSensorYearCollection(i, startDay, endDay, 'LT05', aoi, exclude);
var le7 = buildSensorYearCollection(i, startDay, endDay, 'LE07', aoi, exclude);
var lc8 = buildSensorYearCollection(i, startDay, endDay, 'LC08', aoi, exclude);
var lc9 = buildSensorYearCollection(i, startDay, endDay, 'LC09', aoi, exclude)
var tmp = ee.ImageCollection(lt5.merge(le7).merge(lc8).merge(lc9));
if(first === true){
var all = tmp;
first = false;
} else{
all = all.merge(tmp);
}
}
return ee.Dictionary({
'idList':all.toList(all.size().add(1)).map(getImgID),
'collection':all
});
};
exports.getCollectionIDlist = getCollectionIDlist;
//------ FUNCTION TO COUNT NUMBER OF UNMASKED PIXELS IN AN INTRA ANNUAL COLLECTION ------------------------------
var countClearViewPixels = function(intraAnnualSRcollection){
var binary = intraAnnualSRcollection.map(function(img){
return img.select(0)
.multiply(0)
.add(1)
.unmask(0);
});
return binary.sum();
};
exports.countClearViewPixels = countClearViewPixels;
//------ FUNCTION TO BUILD ANNAUL COLLECTION OF NUMBER OF UNMASKED PIXELS AVAILABLE TO BUILD COMPOSITE ------------------------------
var buildClearPixelCountCollection = function(startYear, endYear, startDay, endDay, aoi, maskThese) {
var dummyCollection = ee.ImageCollection([ee.Image([0,0,0,0,0,0]).mask(ee.Image(0))]);
var imgs = [];
for (var i = startYear; i <= endYear; i++) {
var collection = getCombinedSRcollection(i, startDay, endDay, aoi, maskThese, maskThese);
var imageCount = collection.toList(1).length();
var finalCollection = ee.ImageCollection(ee.Algorithms.If(imageCount.gt(0), collection, dummyCollection));
var notMaskCount = countClearViewPixels(finalCollection);
imgs = imgs.concat(notMaskCount.set('system:time_start', (new Date(i,8,1)).valueOf()));
}
return ee.ImageCollection(imgs);
};
exports.buildClearPixelCountCollection = buildClearPixelCountCollection;
var removeImages = function(collection, exclude){
// ["LANDSAT/LC08/C01/T1_SR/LC08_046028_20170815"](system:id) or [LC08_046028_20170815](system:index)
// could not get (system:id) to work though, so getting via string split and slice
//print('removeImages',exclude)
if('exclude' in exclude){
//print('in exclude')
exclude = exclude.exclude;
if('imgIds' in exclude){
//print('in imgIds')
var excludeList = exclude.imgIds;
for(var i=0; i<excludeList.length; i++){
//print('img blah blah')
collection = collection.filter(ee.Filter.neq('system:index', excludeList[i].split('/').slice(-1).toString())); //system:id
}
}
if('slcOff' in exclude){
//print('in slcOff')
if(exclude.slcOff === true){
//print('slcOff is true')
//'SATELLITE' changed to SPACECRAFT_ID and 'SENSING_TIME' to 'SCENE_CENTER_TIME' in collection 2
collection = collection.filter(ee.Filter.neq('SPACECRAFT_ID', 'LANDSAT_7'));
//collection = collection.filter(ee.Filter.and(ee.Filter.eq('SPACECRAFT_ID', 'LANDSAT_7'), ee.Filter.gt('SCENE_CENTER_TIME', '22:07:34.8203690Z')).not());
//print(collection)
}
}
}
return collection;
};
exports.removeImages = removeImages;
//########################################################################################################
//##### UNPACKING LT-GEE OUTPUT STRUCTURE FUNCTIONS #####
//########################################################################################################
// ----- FUNCTION TO EXTRACT VERTICES FROM LT RESULTS AND STACK BANDS -----
var getLTvertStack = function(lt, runParams) {
lt = lt.select('LandTrendr');
var emptyArray = []; // make empty array to hold another array whose length will vary depending on maxSegments parameter
var vertLabels = []; // make empty array to hold band names whose length will vary depending on maxSegments parameter
for(var i=1;i<=runParams.maxSegments+1;i++){ // loop through the maximum number of vertices in segmentation and fill empty arrays // define vertex number as string
vertLabels.push("vert_"+i.toString()); // make a band name for given vertex
emptyArray.push(0); // fill in emptyArray
}
var zeros = ee.Image(ee.Array([emptyArray, // make an image to fill holes in result 'LandTrendr' array where vertices found is not equal to maxSegments parameter plus 1
emptyArray,
emptyArray]));
var lbls = [['yrs_','src_','fit_'], vertLabels,]; // labels for 2 dimensions of the array that will be cast to each other in the final step of creating the vertice output
var vmask = lt.arraySlice(0,3,4); // slices out the 4th row of a 4 row x N col (N = number of years in annual stack) matrix, which identifies vertices - contains only 0s and 1s, where 1 is a vertex (referring to spectral-temporal segmentation) year and 0 is not
var ltVertStack = lt.arrayMask(vmask) // uses the sliced out isVert row as a mask to only include vertice in this data - after this a pixel will only contain as many "bands" are there are vertices for that pixel - min of 2 to max of 7.
.arraySlice(0, 0, 3) // ...from the vertOnly data subset slice out the vert year row, raw spectral row, and fitted spectral row
.addBands(zeros) // ...adds the 3 row x 7 col 'zeros' matrix as a band to the vertOnly array - this is an intermediate step to the goal of filling in the vertOnly data so that there are 7 vertice slots represented in the data - right now there is a mix of lengths from 2 to 7
.toArray(1) // ...concatenates the 3 row x 7 col 'zeros' matrix band to the vertOnly data so that there are at least 7 vertice slots represented - in most cases there are now > 7 slots filled but those will be truncated in the next step
.arraySlice(1, 0, runParams.maxSegments+1) // ...before this line runs the array has 3 rows and between 9 and 14 cols depending on how many vertices were found during segmentation for a given pixel. this step truncates the cols at 7 (the max verts allowed) so we are left with a 3 row X 7 col array
.arrayFlatten(lbls, ''); // ...this takes the 2-d array and makes it 1-d by stacking the unique sets of rows and cols into bands. there will be 7 bands (vertices) for vertYear, followed by 7 bands (vertices) for rawVert, followed by 7 bands (vertices) for fittedVert, according to the 'lbls' list
return ltVertStack; // return the stack
};
exports.getLTvertStack = getLTvertStack;
// #######################################################################################
// ###### INDEX CALCULATION FUNCTIONS ####################################################
// #######################################################################################
// TASSELLED CAP
var tcTransform = function(img){
var b = ee.Image(img).select(["B1", "B2", "B3", "B4", "B5", "B7"]); // select the image bands
var brt_coeffs = ee.Image.constant([0.2043, 0.4158, 0.5524, 0.5741, 0.3124, 0.2303]); // set brt coeffs - make an image object from a list of values - each of list element represents a band
var grn_coeffs = ee.Image.constant([-0.1603, -0.2819, -0.4934, 0.7940, -0.0002, -0.1446]); // set grn coeffs - make an image object from a list of values - each of list element represents a band
var wet_coeffs = ee.Image.constant([0.0315, 0.2021, 0.3102, 0.1594, -0.6806, -0.6109]); // set wet coeffs - make an image object from a list of values - each of list element represents a band
var sum = ee.Reducer.sum(); // create a sum reducer to be applyed in the next steps of summing the TC-coef-weighted bands
var brightness = b.multiply(brt_coeffs).reduce(sum); // multiply the image bands by the brt coef and then sum the bands
var greenness = b.multiply(grn_coeffs).reduce(sum); // multiply the image bands by the grn coef and then sum the bands
var wetness = b.multiply(wet_coeffs).reduce(sum); // multiply the image bands by the wet coef and then sum the bands
var angle = (greenness.divide(brightness)).atan().multiply(180/Math.PI).multiply(100);
var tc = brightness.addBands(greenness)
.addBands(wetness)
.addBands(angle)
.select([0,1,2,3], ['TCB','TCG','TCW','TCA']) //stack TCG and TCW behind TCB with .addBands, use select() to name the bands
.set('system:time_start', img.get('system:time_start'));
return tc;
};
exports.tcTransform = tcTransform
// NBR
var nbrTransform = function(img) {
var nbr = img.normalizedDifference(['B4', 'B7']) // calculate normalized difference of B4 and B7. orig was flipped: ['B7', 'B4']
.multiply(1000) // scale results by 1000
.select([0], ['NBR']) // name the band
.set('system:time_start', img.get('system:time_start'));
return nbr;
};
// NBR
var nbr2Transform = function(img) {
var nbr2 = img.normalizedDifference(['B5', 'B7']) // calculate normalized difference of B4 and B7. orig was flipped: ['B7', 'B4']
.multiply(1000) // scale results by 1000
.select([0], ['NBR2']) // name the band
.set('system:time_start', img.get('system:time_start'));
return nbr2;
};
//Ben added
// NDFI - from CODED utility (original: users/bullocke/coded:coded/miscUtilities)
var ndfiTransform = function(img) {
// pre-defined endmembers
var params = ee.Dictionary({
'cfThreshold': 0.01, // CLOUD THRESHOLD
'soil': [2000, 3000, 3400, 5800, 6000, 5800],
'gv': [500, 900, 400, 6100, 3000, 1000],
'npv': [1400, 1700, 2200, 3000, 5500, 3000],
'shade': [0, 0, 0, 0, 0, 0],
'cloud': [9000, 9600, 8000, 7800, 7200, 6500]
});
/* Utility function for calculating spectral indices */
var gv = params.get('gv');
var shade = params.get('shade');
var npv = params.get('npv');
var soil = params.get('soil');
var cloud = params.get('cloud');
//var cfThreshold = ee.Image.constant(params.get('cfThreshold'))
/* Do spectral unmixing on a single image */
var unmixImage = ee.Image(img).unmix([gv, shade, npv, soil, cloud], true,true)
.rename(['band_0', 'band_1', 'band_2','band_3','band_4']);
var newImage = ee.Image(img).addBands(unmixImage);
//var mask = newImage.select('band_4').lt(cfThreshold)
var ndfi = unmixImage.expression(
'((GV / (1 - SHADE)) - (NPV + SOIL)) / ((GV / (1 - SHADE)) + NPV + SOIL)', {
'GV': unmixImage.select('band_0'),
'SHADE': unmixImage.select('band_1'),
'NPV': unmixImage.select('band_2'),
'SOIL': unmixImage.select('band_3')
});
var ndvi = ee.Image(img).normalizedDifference(['B4','B3']).rename('NDVI')
var evi = ee.Image(img).expression(
'float(2.5*(((B4/10000) - (B3/10000)) / ((B4/10000) + (6 * (B3/10000)) - (7.5 * (B1/10000)) + 1)))',
{
'B4': ee.Image(img).select(['B4']),
'B3': ee.Image(img).select(['B3']),
'B1': ee.Image(img).select(['B1'])
}).rename('EVI');
var toExp = newImage
.addBands([ndfi.rename(['NDFI']), ndvi, evi])
.select(['band_0','band_1','band_2','band_3','NDFI','NDVI','EVI','B1','B2','B3','B4','B5'])
.rename(['GV','Shade','NPV','Soil','NDFI','NDVI','EVI','Blue','Green','Red','NIR','SWIR1']);
//.updateMask(mask)
toExp = toExp.select(['NDFI'])
.multiply(1000)
.set('system:time_start', img.get('system:time_start'));
return toExp;
};
// NDVI
var ndviTransform = function(img){
var ndvi = img.normalizedDifference(['B4', 'B3']) // calculate normalized dif between band 4 and band 3 (B4-B3/B4_B3)
.multiply(1000) // scale results by 1000
.select([0], ['NDVI']) // name the band
.set('system:time_start', img.get('system:time_start'));
return ndvi;
};
// NDSI
var ndsiTransform = function(img){
var ndsi = img.normalizedDifference(['B2', 'B5']) // calculate normalized dif between band 4 and band 3 (B4-B3/B4_B3)
.multiply(1000) // scale results by 1000
.select([0], ['NDSI']) // name the band
.set('system:time_start', img.get('system:time_start'));
return ndsi;
};
// NDMI
var ndmiTransform = function(img) {
var ndmi = img.normalizedDifference(['B4', 'B5']) // calculate normalized difference of B4 and B7. orig was flipped: ['B7', 'B4']
.multiply(1000) // scale results by 1000
.select([0], ['NDMI']) // name the band
.set('system:time_start', img.get('system:time_start'));
return ndmi;
};
// EVI
var eviTransform = function(img) {
var evi = img.expression(
'2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
'NIR': img.select('B4'),
'RED': img.select('B3'),
'BLUE': img.select('B1')
})
.multiply(1000) // scale results by 1000
.select([0], ['EVI']) // name the band
.set('system:time_start', img.get('system:time_start'));
return evi;
};
// SIPI
var sipiTransform = function(img) {
var sipi = img.expression(
'(NIR - RED) / (NIR - BLUE)', {
'NIR': img.select('B4'),
'RED': img.select('B3'),
'BLUE': img.select('B1')
})
.multiply(1000) // scale results by 1000
.select([0], ['SIPI']) // name the band
.set('system:time_start', img.get('system:time_start'));
return sipi;
};
// CALCULATE A GIVEN INDEX
var calcIndex = function(img, index, flip){
// make sure index string in upper case
index = index.toUpperCase();
// figure out if we need to calc tc
var tcList = ['TCB', 'TCG', 'TCW', 'TCA'];
var doTC = tcList.indexOf(index);
if(doTC >= 0){
var tc = tcTransform(img);
}
// need to flip some indices if this is intended for segmentation
var indexFlip = 1;
if(flip == 1){
indexFlip = -1;
}
// need to cast raw bands to float to make sure that we don't get errors regarding incompatible bands
// ...derivations are already float because of division or multiplying by decimal
var indexImg;
switch (index){
case 'B1':
indexImg = img.select(['B1']).float();//.multiply(indexFlip);
break;
case 'B2':
indexImg = img.select(['B2']).float();//.multiply(indexFlip);
break;
case 'B3':
indexImg = img.select(['B3']).float();//.multiply(indexFlip);
break;
case 'B4':
indexImg = img.select(['B4']).multiply(indexFlip).float();
break;
case 'B5':
indexImg = img.select(['B5']).float();//.multiply(indexFlip);
break;
case 'B7':
indexImg = img.select(['B7']).float();//.multiply(indexFlip);
break;
case 'NBR':
indexImg = nbrTransform(img).multiply(indexFlip);
break;
case 'NBR2':
indexImg = nbr2Transform(img).multiply(indexFlip);
break;
case 'NDMI':
indexImg = ndmiTransform(img).multiply(indexFlip);
break;
case 'NDVI':
indexImg = ndviTransform(img).multiply(indexFlip);
break;
case 'NDSI':
indexImg = ndsiTransform(img).multiply(indexFlip);
break;
case 'EVI':
indexImg = eviTransform(img).multiply(indexFlip);
break;
case 'SIPI':
indexImg = sipiTransform(img).multiply(indexFlip);
break;
case 'TCB':
indexImg = tc.select(['TCB'])//.multiply(indexFlip);
break;
case 'TCG':
indexImg = tc.select(['TCG']).multiply(indexFlip);
break;
case 'TCW':
indexImg = tc.select(['TCW']).multiply(indexFlip);
break;
case 'TCA':
indexImg = tc.select(['TCA']).multiply(indexFlip);
break;
case 'NDFI':
indexImg = ndfiTransform(img).multiply(indexFlip);
break;
default:
print('The index you provided is not supported');
}
return indexImg.set('system:time_start', img.get('system:time_start'));
};
exports.calcIndex = calcIndex;
// MAKE AN LT STACK
//var makeLTstack = function(img){
// var allStack = calcIndex(img, index, 1); // calc index for segmentation
// var ftvimg;
// for(var ftv in ftvList){
// ftvimg = calcIndex(img, ftvList[ftv], 0) // calc index for FTV
// .select([ftvList[ftv]],['ftv_'+ftvList[ftv].toLowerCase()]);
//
// allStack = allStack.addBands(ftvimg)
// .set('system:time_start', img.get('system:time_start'));
// }
//
// return allStack;
//};
// arrange collection as an annual stack
// TODO: would be nice to name the bands with the original band name and the year
var TScollectionToStack = function(collection, startYear, endYear){
var collectionArray = collection.toArrayPerBand();
var nBands = ee.Image(collection.first()).bandNames().getInfo().length;//;
var bandNames = getYearBandNames(startYear, endYear);
var allStack = ee.Image();
for (var i = 0; i < nBands; i++){
var bandTS = collectionArray.select([i]).arrayFlatten([bandNames]);
allStack = ee.Image.cat([allStack, bandTS]);
}
return allStack.slice(1,null);
};
exports.TScollectionToStack = TScollectionToStack;
var standardize = function(collection){
var mean = collection.reduce(ee.Reducer.mean());
var stdDev = collection.reduce(ee.Reducer.stdDev());
var meanAdj = collection.map(function(img){
return img.subtract(mean).set('system:time_start', img.get('system:time_start'));
});
return meanAdj.map(function(img){
return img.divide(stdDev).set('system:time_start', img.get('system:time_start'));
});
};
// STANDARDIZE TASSELED CAP BRIGHTNESS GREENNESS WETNESS AND REDUCE THE COLLECTION
var makeTCcomposite = function(annualSRcollection, reducer){
var TCcomposite = annualSRcollection.map(function(img){
var tcb = calcIndex(img, 'TCB', 1);//.unmask(0);
var tcg = calcIndex(img, 'TCG', 1);//.unmask(0);
var tcw = calcIndex(img, 'TCW', 1);//.unmask(0);
return tcb.addBands(tcg)
.addBands(tcw)
.set('system:time_start', img.get('system:time_start'));
});
var tcb = TCcomposite.select(['TCB']);
var tcg = TCcomposite.select(['TCG']);
var tcw = TCcomposite.select(['TCW']);
// standardize the TC bands
var tcbStandard = standardize(tcb);
var tcgStandard = standardize(tcg);
var tcwStandard = standardize(tcw);
// combine the standardized TC band collections into a single collection
var tcStandard = tcbStandard.combine(tcgStandard).combine(tcwStandard);
TCcomposite = tcStandard.map(function(img){
var imgCollection = ee.ImageCollection.fromImages(
[
img.select(['TCB'],['Z']),
img.select(['TCG'],['Z']),
img.select(['TCW'],['Z'])
]
);
var reducedImg;
switch(reducer){
case 'mean':
reducedImg = imgCollection.mean();
break;
case 'max':
reducedImg = imgCollection.max();
break;
case 'sum':
reducedImg = imgCollection.sum();
break;
default:
print('The reducer you provided is not supported');
}
return reducedImg.multiply(1000).set('system:time_start', img.get('system:time_start'));
});
return TCcomposite;
};
// STANDARDIZE B5, TCB, TCG, NBR AND REDUCE THE COLLECTION
var makeEnsemblecomposite = function(annualSRcollection, reducer){
// make a collection of the ensemble indices stacked as bands
var stack = annualSRcollection.map(function(img){
var b5 = calcIndex(img, 'B5', 1);
var b7 = calcIndex(img, 'B7', 1);
var tcw = calcIndex(img, 'TCW', 1);
var tca = calcIndex(img, 'TCA', 1);
var ndmi = calcIndex(img, 'NDMI', 1);
var nbr = calcIndex(img, 'NBR', 1);
return b5.addBands(b7)
.addBands(tcw)
.addBands(tca)
.addBands(ndmi)
.addBands(nbr)
.set('system:time_start', img.get('system:time_start'));
});
// make subset collections of each index
var b5 = stack.select('B5');
var b7 = stack.select('B7');
var tcw = stack.select('TCW');
var tca = stack.select('TCA');
var ndmi = stack.select('NDMI');
var nbr = stack.select('NBR');
// standardize each index to mean 0 stdev 1
var b5Standard = standardize(b5);
var b7Standard = standardize(b7);
var tcwStandard = standardize(tcw);
var tcaStandard = standardize(tca);
var ndmiStandard = standardize(ndmi);
var nbrStandard = standardize(nbr);
// combine the standardized band collections into a single collection
var standard = b5Standard.combine(b7Standard).combine(tcwStandard).combine(tcaStandard)
.combine(ndmiStandard).combine(nbrStandard);
// reduce the collection to a single value
var composite = standard.map(function(img){
var imgCollection = ee.ImageCollection.fromImages(
[
img.select(['B5'],['Z']),
img.select(['B7'],['Z']),
img.select(['TCW'],['Z']),
img.select(['TCA'],['Z']),
img.select(['NDMI'],['Z']),
img.select(['NBR'],['Z']),
]
);
var reducedImg;
switch(reducer){
case 'mean':
reducedImg = imgCollection.mean();
break;
case 'max':
reducedImg = imgCollection.max();
break;
case 'sum':
reducedImg = imgCollection.sum();
break;
default:
print('The reducer you provided is not supported');
}
return reducedImg.multiply(1000).set('system:time_start', img.get('system:time_start'));
});
return composite;
};
makeEnsemblecomposite.exports = makeEnsemblecomposite;
// STANDARDIZE B5, TCB, TCG, NBR AND REDUCE THE COLLECTION
var makeEnsemblecomposite1 = function(annualSRcollection, reducer){
// make a collection of the ensemble indices stacked as bands
var TCcomposite = annualSRcollection.map(function(img){
var b5 = calcIndex(img, 'B5', 1);
var tcb = calcIndex(img, 'TCB', 1);
var tcg = calcIndex(img, 'TCG', 1);
var nbr = calcIndex(img, 'NBR', 1);
return b5.addBands(tcb)
.addBands(tcg)
.addBands(nbr)
.set('system:time_start', img.get('system:time_start'));
});
// make subset collections of each index
var b5 = TCcomposite.select('B5');
var tcb = TCcomposite.select('TCB');
var tcg = TCcomposite.select('TCG');
var nbr = TCcomposite.select('NBR');
// standardize each index - get z-score
var b5Standard = standardize(b5);
var tcbStandard = standardize(tcb);
var tcgStandard = standardize(tcg);
var nbrStandard = standardize(nbr);
// combine the standardized TC band collections into a single collection
var tcStandard = b5Standard.combine(tcbStandard).combine(tcgStandard).combine(nbrStandard);
// reduce the collection to a single value
TCcomposite = tcStandard.map(function(img){
var imgCollection = ee.ImageCollection.fromImages(
[
img.select(['B5'],['Z']),//.pow(ee.Image(1)).multiply(img.select('B5').gte(0).where(img.select('B5').lt(0),-1)),
img.select(['TCB'],['Z']),//.pow(ee.Image(1.5)).multiply(img.select('TCB').gte(0).where(img.select('TCB').lt(0),-1)),
img.select(['TCG'],['Z']),//.pow(ee.Image(1.5)).multiply(img.select('TCG').gte(0).where(img.select('TCG').lt(0),-1)),
img.select(['NBR'],['Z'])//.pow(ee.Image(1.5)).multiply(img.select('NBR').gte(0).where(img.select('NBR').lt(0),-1))
]
);
var reducedImg;
switch(reducer){
case 'mean':
reducedImg = imgCollection.mean();
break;
case 'max':
reducedImg = imgCollection.max();
break;
case 'sum':
reducedImg = imgCollection.sum();
break;
default:
print('The reducer you provided is not supported');
}
return reducedImg.multiply(1000).set('system:time_start', img.get('system:time_start'));
});
return TCcomposite;
};
// STANDARDIZE A INDEX INDEX - all disturbances are up
var standardizeIndex = function(collection, index){
var zCollection = collection.map(function(img){
return calcIndex(img, index, 1);
});
zCollection = standardize(zCollection);
zCollection = zCollection.map(function(img){
return img.multiply(1000).set('system:time_start', img.get('system:time_start'));
});
return zCollection;
};
// BUILD AN LT COLLECTION
var buildLTcollection = function(collection, index, ftvList){
//print(ftvList)
var LTcollection;
switch(index){
// tasseled cap composite
case 'TCC':
LTcollection = makeTCcomposite(collection, 'mean');
break;
case 'TCM':
LTcollection = makeTCcomposite(collection, 'max');
break;
case 'TCS':
LTcollection = makeTCcomposite(collection, 'sum');
break;
// 6-band composite - Based on Figure 3 of the linked paper: https://larse.forestry.oregonstate.edu/sites/larse/files/pub_pdfs/Cohen_et_al_2018.pdf
case 'ENC':
LTcollection = makeEnsemblecomposite(collection, 'mean');
break;
case 'ENM':
LTcollection = makeEnsemblecomposite(collection, 'max');
break;
case 'ENS':
LTcollection = makeEnsemblecomposite(collection, 'sum');
break;
// 6-band composite - Based on Table 5 of the linked paper: https://larse.forestry.oregonstate.edu/sites/larse/files/pub_pdfs/Cohen_et_al_2018.pdf
case 'ENC1':
LTcollection = makeEnsemblecomposite1(collection, 'mean');
break;
case 'ENM1':
LTcollection = makeEnsemblecomposite1(collection, 'max');
break;
case 'ENS1':
LTcollection = makeEnsemblecomposite1(collection, 'sum');
break;
// standardized versions of indices: mean 0 stdDev 1
case 'B5z':
LTcollection = standardizeIndex(collection, 'B5');
break;
case 'B7z':
LTcollection = standardizeIndex(collection, 'B7');
break;
case 'TCWz':
LTcollection = standardizeIndex(collection, 'TCW');
break;
case 'TCAz':
LTcollection = standardizeIndex(collection, 'TCA');
break;
case 'NDMIz':
LTcollection = standardizeIndex(collection, 'NDMI');
break;
case 'NBRz':
LTcollection = standardizeIndex(collection, 'NBR');
break;
default:
//print('default')
//print(ftvList)
LTcollection = collection.map(function(img){
var allStack = calcIndex(img, index, 1);
var ftvimg;
for(var ftv in ftvList){
ftvimg = calcIndex(img, ftvList[ftv], 0)
.select([ftvList[ftv]],['ftv_'+ftvList[ftv].toLowerCase()]);
allStack = allStack.addBands(ftvimg)
.set('system:time_start', img.get('system:time_start'));
}
return allStack;
});
}
//print(LTcollection)
return LTcollection;
};
exports.buildLTcollection = buildLTcollection;
// THIS BUILDS AN ANNUAL-SR-TRANSFORMED COLLECTION FOR USE BY TIMESYNC-LEGACY
var buildTSindexCollection = function(collection, ftvList){
return collection.map(function(img){
var allStack = ee.Image();
var ftvimg;
for(var ftv in ftvList){
ftvimg = calcIndex(img, ftvList[ftv], 0)
.select([ftvList[ftv]],['ftv_'+ftvList[ftv].toLowerCase()])
.unmask(0);
allStack = allStack.addBands(ftvimg)
.set('system:time_start', img.get('system:time_start'));
}
return allStack.slice(1,null);
});
};
// TRANSFORM AN ANNUAL SR COLLECTION TO AN ANNUAL COLLECTION OF SELECTED INDICES OR BANDS
var transformSRcollection = function(srCollection, bandList){
return srCollection.map(function(img){
var allStack = calcIndex(img, bandList[0], 0);
for(var band=1; band < bandList.length; band++){
var bandImg = calcIndex(img, bandList[band], 0);
allStack = allStack.addBands(bandImg);
}
return allStack.set('system:time_start', img.get('system:time_start'));
});
};
exports.transformSRcollection = transformSRcollection;
exports.runLT = function(startYear, endYear, startDay, endDay, aoi, index, ftvList, runParams, maskThese, exclude){
maskThese = (typeof maskThese !== 'undefined') ? maskThese : ['cloud','shadow','snow'];
exclude = (typeof exclude !== 'undefined') ? exclude : {}; // default to not exclude any images
var annualSRcollection = buildSRcollection(startYear, endYear, startDay, endDay, aoi, maskThese, exclude); // Peter here, I think this collects surface reflectance images
var annualLTcollection = buildLTcollection(annualSRcollection, index, ftvList);
runParams.timeSeries = annualLTcollection;
return ee.Algorithms.TemporalSegmentation.LandTrendr(runParams);
};
// TODO: update the ftv parameter in the guide
var getFittedData = function(lt, startYear, endYear, index, ftv){
var bandNames = getYearBandNames(startYear, endYear);
var search;
if(ftv === true){
// Make all band names uppercase - make case insensitive.
var ltBands = lt.bandNames().map(function(name) {