-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetImagesLib.js
More file actions
6064 lines (5575 loc) · 194 KB
/
getImagesLib.js
File metadata and controls
6064 lines (5575 loc) · 194 KB
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
/*
Copyright 2024 Ian Housman, Leah Campbell, Josh Heyer
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.
Script to help with change detection
This is a close mirror of the Python script:
https://github.com/gee-community/geeViz/blob/master/getImagesLib.py
*/
////////////////////////////////////////////////////////////////////////////////
//Module for getting Landsat, Sentinel 2 and MODIS images/composites
var exports = {};
var getImagesLib = exports;
// Define visualization parameters
var vizParamsFalse = {
min: 0.1,
max: [0.5, 0.6, 0.6],
bands: "swir2,nir,red",
gamma: 1.6,
};
var vizParamsFalse10k = {
min: 0.1 * 10000,
max: [0.5 * 10000, 0.6 * 10000, 0.6 * 10000],
bands: "swir2,nir,red",
gamma: 1.6,
};
var vizParamsTrue = {
min: 0,
max: [0.2, 0.2, 0.2],
bands: "red,green,blue",
};
var vizParamsTrue10k = {
min: 0,
max: [0.2 * 10000, 0.2 * 10000, 0.2 * 10000],
bands: "red,green,blue",
};
var common_projections = {};
common_projections["NLCD_CONUS"] = {
crs: 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["latitude_of_center",23],PARAMETER["longitude_of_center",-96],PARAMETER["standard_parallel_1",29.5],PARAMETER["standard_parallel_2",45.5],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',
transform: [30, 0, -2361915.0, 0, -30, 3177735.0],
};
common_projections["NLCD_AK"] = {
crs: 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",55],PARAMETER["standard_parallel_2",65],PARAMETER["latitude_of_center",50],PARAMETER["longitude_of_center",-154],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1]]',
transform: [30, 0, -48915.0, 0, -30, 1319415.0],
};
common_projections["NLCD_HI"] = {
crs: 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Longitude", EAST], AXIS["Latitude", NORTH], AUTHORITY["EPSG","4326"]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["central_meridian", -157.0],PARAMETER["latitude_of_origin", 3.0],PARAMETER["standard_parallel_1", 8.0],PARAMETER["false_easting", 0.0],PARAMETER["false_northing", 0.0],PARAMETER["standard_parallel_2", 18.0],UNIT["m", 1.0],AXIS["x", EAST],AXIS["y", NORTH]]',
transform: [30, 0, -342585, 0, -30, 2127135],
};
//Direction of a decrease in photosynthetic vegetation- add any that are missing
var changeDirDict = {
blue: 1,
green: 1,
red: 1,
nir: -1,
swir1: 1,
swir2: 1,
temp: 1,
NDVI: -1,
NBR: -1,
NDMI: -1,
NDSI: 1,
brightness: 1,
greenness: -1,
wetness: -1,
fourth: -1,
fifth: 1,
sixth: -1,
ND_blue_green: -1,
ND_blue_red: -1,
ND_blue_nir: 1,
ND_blue_swir1: -1,
ND_blue_swir2: -1,
ND_green_red: -1,
ND_green_nir: 1,
ND_green_swir1: -1,
ND_green_swir2: -1,
ND_red_swir1: -1,
ND_red_swir2: -1,
ND_nir_red: -1,
ND_nir_swir1: -1,
ND_nir_swir2: -1,
ND_swir1_swir2: -1,
R_swir1_nir: 1,
R_red_swir1: -1,
EVI: -1,
SAVI: -1,
IBI: 1,
tcAngleBG: -1,
tcAngleGW: -1,
tcAngleBW: -1,
tcDistBG: 1,
tcDistGW: 1,
tcDistBW: 1,
NIRv: -1,
NDCI: -1,
NDGI: -1,
};
//Precomputed cloudscore offsets and TDOM stats
//These have been pre-computed for all CONUS for Landsat and Setinel 2 (separately)
//and are appropriate to use for any time period within the growing season
// These have been calculated separately for AK and HI, so we mosaic them all together
//The cloudScore offset is generally some lower percentile of cloudScores on a pixel-wise basis
//The TDOM stats are the mean and standard deviations of the two bands used in TDOM
//By default, TDOM uses the nir and swir1 bands
var preComputedCloudScoreOffset = ee
.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/cloudScore")
.mosaic();
//var preComputedCloudScoreOffsetAK = ee.ImageCollection('projects/lcms-tcc-shared/assets/CS-TDOM-Stats/Alaska/cloudScore_stats').mosaic();
//var preComputedCloudScoreOffsetHI = ee.ImageCollection('projects/lcms-tcc-shared/assets/CS-TDOM-Stats/Hawaii/cloudScore').mosaic();
// mosaic all together
//var preComputedCloudScoreOffset = ee.ImageCollection.fromImages([preComputedCloudScoreOffset,
// preComputedCloudScoreOffsetAK,
// preComputedCloudScoreOffsetHI]).mosaic();
var preComputedTDOMStats = ee
.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/TDOM")
.mosaic()
.divide(10000);
//var preComputedTDOMStatsAK = ee.ImageCollection('projects/lcms-tcc-shared/assets/CS-TDOM-Stats/Alaska/TDOM_stats').mosaic().divide(10000);
//var preComputedTDOMStatsHI = ee.ImageCollection('projects/lcms-tcc-shared/assets/CS-TDOM-Stats/Hawaii/TDOM').mosaic().divide(10000);
// mosaic all together
//var preComputedTDOMStats = ee.ImageCollection.fromImages([preComputedTDOMStats,
// preComputedTDOMStatsAK,
// preComputedTDOMStatsHI]).mosaic();
exports.preComputedCloudScoreOffset = preComputedCloudScoreOffset;
exports.preComputedTDOMStats = preComputedTDOMStats;
exports.getPrecomputedCloudScoreOffsets = function (cloudScorePctl) {
return {
landsat: preComputedCloudScoreOffset.select([
"Landsat_CloudScore_p" + cloudScorePctl.toString(),
]),
sentinel2: preComputedCloudScoreOffset.select([
"Sentinel2_CloudScore_p" + cloudScorePctl.toString(),
]),
};
};
exports.getPrecomputedTDOMStats = function (cloudScorePctl) {
return {
landsat: {
mean: preComputedTDOMStats.select([
"Landsat_nir_mean",
"Landsat_swir1_mean",
]),
stdDev: preComputedTDOMStats.select([
"Landsat_nir_stdDev",
"Landsat_swir1_stdDev",
]),
},
sentinel2: {
mean: preComputedTDOMStats.select([
"Sentinel2_nir_mean",
"Sentinel2_swir1_mean",
]),
stdDev: preComputedTDOMStats.select([
"Sentinel2_nir_stdDev",
"Sentinel2_swir1_stdDev",
]),
},
};
};
exports.getPrecomputedTDOMStatsAK = function (cloudScorePctl) {
return {
landsat: {
mean: preComputedTDOMStatsAK.select([
"Landsat_nir_mean",
"Landsat_swir1_mean",
]),
stdDev: preComputedTDOMStatsAK.select([
"Landsat_nir_stdDev",
"Landsat_swir1_stdDev",
]),
},
sentinel2: {
mean: preComputedTDOMStatsAK.select([
"Sentinel2_nir_mean",
"Sentinel2_swir1_mean",
]),
stdDev: preComputedTDOMStatsAK.select([
"Sentinel2_nir_stdDev",
"Sentinel2_swir1_stdDev",
]),
},
};
};
exports.getPrecomputedTDOMStatsHI = function (cloudScorePctl) {
return {
// TDOM stats not calculated for landsat for HI
//'landsat': {
// 'mean':preComputedTDOMStatsHI.select(['Landsat_nir_mean','Landsat_swir1_mean']),
// 'stdDev':preComputedTDOMStatsHI.select(['Landsat_nir_stdDev','Landsat_swir1_stdDev'])
// },
sentinel2: {
mean: preComputedTDOMStatsHI.select([
"Sentinel2_nir_mean",
"Sentinel2_swir1_mean",
]),
stdDev: preComputedTDOMStatsHI.select([
"Sentinel2_nir_stdDev",
"Sentinel2_swir1_stdDev",
]),
},
};
};
////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////
//Function to prep arguments into standardized object regardless of format parameters are provided in
//args are the default arguments keyword for the function
//defaultArgs is an object containing each key and default value needed for the function
//Leave any defaultArg as null if it is needed but a default is not provided
function prepArgumentsObject(args, defaultArgs) {
var argList = [].slice.call(args);
var outArgs = {};
// print('Default args:',defaultArgs);
//See if first argument is an ee object instead of a vanilla js object
var firstArgumentIsEEObj = false;
var argsAreObject = false;
try {
var t = argList[0].serialize();
firstArgumentIsEEObj = true;
} catch (err) {}
if (
typeof argList[0] === "object" &&
argList.length === 1 &&
!firstArgumentIsEEObj
) {
argsAreObject = true;
outArgs = argList[0];
}
//Iterate through each expected argument to create the obj with all parameters
Object.keys(defaultArgs).forEach(function (key, i) {
var value;
if (argsAreObject) {
value = argList[0][key];
} else {
value = argList[i];
}
//Fill in default value if non is provided or it is null
if (value === undefined || value === null) {
value = defaultArgs[key];
}
// console.log(value)
outArgs[key] = value;
});
// //Merge any remaining variables that were provided
// if(argsAreObject){
// }
// print('Out args:',outArgs);
return outArgs;
}
//////////////////////////////////////////////////
// Function to copy an object so values are not updated in both objects
function copyObj(obj) {
var out = {};
Object.keys(obj).map(function (k) {
out[k] = obj[k];
});
return out;
}
function reverseObj(obj) {
var out = {};
Object.keys(obj).map(function (k) {
let v = obj[k];
out[v] = k;
});
return out;
}
///////////////////////////////////////////////////////////////////
//Function to compute range list on client side
function range(start, stop, step) {
start = parseInt(start);
stop = parseInt(stop);
if (typeof stop == "undefined") {
// one param defined
stop = start;
start = 0;
}
if (typeof step == "undefined") {
step = 1;
}
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
return [];
}
var result = [];
for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
result.push(i);
}
return result;
}
//////////////////////////////////////////////////
// Function to find the ee object type
var eeObjectTypes = {
Image: ee.Image,
ImageCollection: ee.ImageCollection,
Geometry: ee.Geometry,
Feature: ee.Feature,
FeatureCollection: ee.FeatureCollection,
Array: ee.Array,
List: ee.List,
String: ee.String,
Date: ee.Date,
DateRange: ee.DateRange,
Dictionary: ee.Dictionary,
Filter: ee.Filter,
Join: ee.Join,
Kernel: ee.Kernel,
Number: ee.Number,
Projection: ee.Projection,
Reducer: ee.Reducer,
};
function getObjType(obj, message) {
let t;
Object.keys(eeObjectTypes).map(function (k) {
if (obj instanceof eeObjectTypes[k]) {
t = k;
}
});
// console.log(`Obj type: ${t} ${message}`);
return t;
}
//////////////////////////////////////////////////
// Function to get promie for useful eeObject properties
function eeObjInfo(
eeObj,
objType,
addTime,
timeFormat,
timePropNameIn,
timePropNameOut
) {
objType = objType || getObjType(eeObj, "info");
addTime = addTime || false; //addTime !== undefined && addTime !== null ? addTime : objType == "ImageCollection" || objType === "Image" ? true : false;
timeFormat = timeFormat || "YYYY";
timePropNameIn = timePropNameIn || "system:time_start";
timePropNameOut =
timePropNameOut ||
objType == "ImageCollection" ||
objType === "FeatureCollection"
? "dates"
: "date";
eeObj = objType === "Geometry" ? ee.Feature(eeObj) : eeObj;
var size;
var props = ee.Dictionary();
var bandNames;
// var allProps;
// console.log(objType);
if (objType.indexOf("Collection") > -1) {
// allProps = eeObj.toDictionary();
size = eeObj.size();
if (objType === "ImageCollection") {
bandNames = ee.Image(ee.ImageCollection(eeObj).first()).bandNames();
props = ee.Image(ee.ImageCollection(eeObj).first()).toDictionary();
}
if (addTime) {
eeObj = eeObj.map(function (img) {
return img.set(
timePropNameOut,
ee.Date(img.get(timePropNameIn)).format(timeFormat)
);
});
var dates = eeObj.aggregate_histogram(timePropNameOut).keys();
}
} else {
if (objType === "Image") {
bandNames = ee.Image(eeObj).bandNames();
props = ee.Image(eeObj).toDictionary();
}
if (addTime) {
var dates = ee.Date(eeObj.get(timePropNameIn)).format(timeFormat);
}
}
props = props.set("layerType", objType);
props = bandNames !== undefined ? props.set("bandNames", bandNames) : props;
props = size !== undefined ? props.set("size", size) : props;
if (addTime) {
props = props.set(timePropNameOut, dates);
}
// props = props.getInfo();
// props.layerType = objType;
return props;
}
//////////////////////////////////////////////////
// Companion function to see if an object is on the server or client
function eeObjServerSide(obj) {
return getObjType(obj, "is server side") !== undefined;
}
//////////////////////////////////////////////////
//Function to set null value for export or conversion to arrays
//See default args below
//Must provide image and noDataValue - there are no defaults
//Example usage: setNoData(anEEImage,-32768) or setNoData({'image':anEEImage,'noDataValue':-32768})
function setNoData() {
var defaultArgs = {
image: null,
noDataValue: null,
};
var args = prepArgumentsObject(arguments, defaultArgs);
return args.image.unmask(args.noDataValue, false).set(args);
}
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//Functions to perform basic clump and elim
//See default args below
//Must provide image
//mmu is an optional parameter with default of 4 pixels
//Example usage: sieve(anEEImage,4) or sieve({'image':anEEImage,'mmu':4})
function sieve() {
var defaultArgs = {
image: null,
mmu: 4,
};
var args = prepArgumentsObject(arguments, defaultArgs);
var connected = args.image.connectedPixelCount(args.mmu + 20);
// Map.addLayer(connected,{'min':1,'max':args.mmu},'connected');
var elim = connected.gt(args.mmu);
var mode = args.image.focal_mode(args.mmu / 2, "circle");
mode = mode.mask(args.image.mask());
var filled = args.image.where(elim.not(), mode);
return filled.set(args);
}
//Written by Yang Z.
//------ L8 to L7 HARMONIZATION FUNCTION -----
// slope and intercept citation: Roy, D.P., Kovalskyy, V., Zhang, H.K., Vermote, E.F., Yan, L., Kumar, S.S, Egorov, A., 2016, Characterization of Landsat-7 to Landsat-8 reflective wavelength and normalized difference vegetation index continuity, Remote Sensing of Environment, 185, 57-70.(http://dx.doi.org/10.1016/j.rse.2015.12.024); Table 2 - reduced major axis (RMA) regression coefficients
var harmonizationRoy = function (oli) {
var slopes = ee.Image.constant([
0.9785, 0.9542, 0.9825, 1.0073, 1.0171, 0.9949,
]); // create an image of slopes per band for L8 TO L7 regression line - David Roy
var itcp = ee.Image.constant([
-0.0095, -0.0016, -0.0022, -0.0021, -0.003, 0.0029,
]);
var bns = oli.bandNames();
var includeBns = ["blue", "green", "red", "nir", "swir1", "swir2"];
var otherBns = bns.removeAll(includeBns);
// create an image of y-intercepts per band for L8 TO L7 regression line - David Roy
var y = oli
.select(includeBns)
.float() // select OLI bands 2-7 and rename them to match L7 band names
// .resample('bicubic') // ...resample the L8 bands using bicubic
.subtract(itcp)
.divide(slopes) // ...multiply the y-intercept bands by 10000 to match the scale of the L7 bands then apply the line equation - subtract the intercept and divide by the slope
.set("system:time_start", oli.get("system:time_start")); // ...set the output system:time_start metadata to the input image time_start otherwise it is null
y = y.addBands(oli.select(otherBns)).select(bns);
return y.float(); // return the image as short to match the type of the other data
};
/////////////////////////////////////////////////////////////////////////
//Code to implement OLI/ETM/MSI regression
//Chastain et al 2018 coefficients
//Empirical cross sensor comparison of Sentinel-2A and 2B MSI, Landsat-8 OLI, and Landsat-7 ETM+ top of atmosphere spectral characteristics over the conterminous United States
//https://www.sciencedirect.com/science/article/pii/S0034425718305212#t0020
//Left out 8a coefficients since all sensors need to be cross- corrected with bands common to all sensors
//Dependent and Independent variables can be switched since Major Axis (Model 2) linear regression was used
var chastainBandNames = ["blue", "green", "red", "nir", "swir1", "swir2"];
//From Table 4
//msi = oli*slope+intercept
//oli = (msi-intercept)/slope
var msiOLISlopes = [1.0946, 1.0043, 1.0524, 0.8954, 1.0049, 1.0002];
var msiOLIIntercepts = [-0.0107, 0.0026, -0.0015, 0.0033, 0.0065, 0.0046];
//From Table 5
//msi = etm*slope+intercept
//etm = (msi-intercept)/slope
var msiETMSlopes = [1.10601, 0.99091, 1.05681, 1.0045, 1.03611, 1.04011];
var msiETMIntercepts = [-0.0139, 0.00411, -0.0024, -0.0076, 0.00411, 0.00861];
//From Table 6
//oli = etm*slope+intercept
//etm = (oli-intercept)/slope
var oliETMSlopes = [1.03501, 1.00921, 1.01991, 1.14061, 1.04351, 1.05271];
var oliETMIntercepts = [-0.0055, -0.0008, -0.0021, -0.0163, -0.0045, 0.00261];
//Construct dictionary to handle all pairwise combos
var chastainCoeffDict = {
MSI_OLI: [msiOLISlopes, msiOLIIntercepts, 1],
MSI_ETM: [msiETMSlopes, msiETMIntercepts, 1],
OLI_ETM: [oliETMSlopes, oliETMIntercepts, 1],
OLI_MSI: [msiOLISlopes, msiOLIIntercepts, 0],
ETM_MSI: [msiETMSlopes, msiETMIntercepts, 0],
ETM_OLI: [oliETMSlopes, oliETMIntercepts, 0],
};
//Function to apply model in one direction
function dir0Regression(img, slopes, intercepts) {
var bns = img.bandNames();
var nonCorrectBands = bns.removeAll(chastainBandNames);
var nonCorrectedBands = img.select(nonCorrectBands);
var corrected = img
.select(chastainBandNames)
.multiply(slopes)
.add(intercepts);
var out = corrected.addBands(nonCorrectedBands).select(bns);
return out;
}
//Applying the model in the opposite direction
function dir1Regression(img, slopes, intercepts) {
var bns = img.bandNames();
var nonCorrectBands = bns.removeAll(chastainBandNames);
var nonCorrectedBands = img.select(nonCorrectBands);
var corrected = img
.select(chastainBandNames)
.subtract(intercepts)
.divide(slopes);
var out = corrected.addBands(nonCorrectedBands).select(bns);
return out;
}
//Function to correct one sensor to another
//Sensor options are 'ETM','OLI', and 'MSI'
//Any pairwise combo can be provided
//See default args below
//Must provide image, fromSensor, and toSensor
//There are no default parameters
//mmu is an optional parameter with default of 4 pixels
//Example usage: harmonizationChastain(anEEImage,'MSI','ETM) or sieve({'image':anEEImage,'fromSensor':'MSI','toSensor':'ETM'})
function harmonizationChastain() {
var defaultArgs = {
image: null,
fromSensor: null,
toSensor: null,
};
var args = prepArgumentsObject(arguments, defaultArgs);
args.fromSensor = args.fromSensor.toUpperCase();
args.toSensor = args.toSensor.toUpperCase();
//Get the model for the given from and to sensor
args.comboKey = args.fromSensor + "_" + args.toSensor;
args.coeffList = chastainCoeffDict[args.comboKey];
var slopes = args.coeffList[0];
var intercepts = args.coeffList[1];
var direction = ee.Number(args.coeffList[2]);
//Apply the model in the respective direction
var out = ee.Algorithms.If(
direction.eq(0),
dir0Regression(args.image, slopes, intercepts),
dir1Regression(args.image, slopes, intercepts)
);
out = ee
.Image(out)
.copyProperties(args.image)
.copyProperties(args.image, ["system:time_start"]);
out = out.set(args);
return ee.Image(out);
}
///////////////////////////////////////////////////////////
//Function to create a multiband image from a collection
//Has been replaced by imageCollection.toBands()
function collectionToImage(collection) {
var stack = ee.Image(
collection.iterate(function (img, prev) {
return ee.Image(prev).addBands(img);
}, ee.Image(1))
);
stack = stack.select(
ee.List.sequence(1, stack.bandNames().size().subtract(1))
);
return stack;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
//Function to find the date for a given composite computed from a given set of images
//Will work on composites computed with methods that include different dates across different bands
//such as the median. For something like a medoid, only a single bands needs passed through
//A known bug is that if the same value occurs twice, it will choose only a single date
function compositeDates(images, composite, bandNames) {
if (bandNames === null || bandNames === undefined) {
bandNames = ee.Image(images.first()).bandNames();
} else {
images = images.select(bandNames);
composite = composite.select(bandNames);
}
var bns = ee
.Image(images.first())
.bandNames()
.map(function (bn) {
return ee.String(bn).cat("_diff");
});
//Function to get the abs diff from a given composite *-1
function getDiff(img, composite) {
var out = img.subtract(composite).abs().multiply(-1).rename(bns);
return img.addBands(out);
}
//Find the diff and add a date band
images = images.map(function (img) {
return getDiff(img, composite);
});
images = images.map(addDateBand);
//Iterate across each band and find the corresponding date to the composite
var out = bandNames.map(function (bn) {
bn = ee.String(bn);
var t = images
.select([bn, bn.cat("_diff"), "year"])
.qualityMosaic(bn.cat("_diff"));
return t.select(["year"]).rename(["YYYYDD"]);
});
//Convert to an image and rename
out = collectionToImage(ee.ImageCollection(out));
// var outBns = bandNames.map(function(bn){return ee.String(bn).cat('YYYYDD')});
// out = out.rename(outBns);
return out;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
//Function to handle empty collections that will cause subsequent processes to fail
//If the collection is empty, will fill it with an empty image
function fillEmptyCollections(inCollection, dummyImage) {
var dummyCollection = ee.ImageCollection([dummyImage.mask(ee.Image(0))]);
var imageCount = inCollection.toList(1).length();
return ee.ImageCollection(
ee.Algorithms.If(imageCount.gt(0), inCollection, dummyCollection)
);
}
//////////////////////////////////////////////////////////////////////////
//Add sensor band function
// Add band tracking which satellite the pixel came from
function addSensorBand(img, whichProgram, toaOrSR) {
var sensorDict = ee.Dictionary({
LANDSAT_4: 4,
LANDSAT_5: 5,
LANDSAT_7: 7,
LANDSAT_8: 8,
LANDSAT_9: 9,
"Sentinel-2A": 21,
"Sentinel-2B": 22,
"Sentinel-2C": 23,
});
var sensorPropDict = ee.Dictionary({
C1_landsat: { TOA: "SPACECRAFT_ID", SR: "SATELLITE" },
C2_landsat: { TOA: "SPACECRAFT_ID", SR: "SPACECRAFT_ID" },
sentinel2: { TOA: "SPACECRAFT_NAME", SR: "SPACECRAFT_NAME" },
});
toaOrSR = toaOrSR.toUpperCase();
var sensorProp = ee.Dictionary(sensorPropDict.get(whichProgram)).get(toaOrSR);
var sensorName = img.get(sensorProp);
img = img
.addBands(
ee.Image.constant(sensorDict.get(sensorName)).rename(["sensor"]).byte()
)
.set("sensor", sensorName);
return img;
}
/////////////////////////////////////////////////////////////////
//Adds the float year with julian proportion to image
function addDateBand(img, maskTime) {
if (maskTime === null || maskTime === undefined) {
maskTime = false;
}
var d = ee.Date(img.get("system:time_start"));
var y = d.get("year");
d = y.add(d.getFraction("year"));
// d=d.getFraction('year')
var db = ee.Image.constant(d).rename(["year"]).float();
if (maskTime) {
db = db.updateMask(img.select([0]).mask());
}
return img.addBands(db);
}
function addYearFractionBand(img) {
var d = ee.Date(img.get("system:time_start"));
var y = d.get("year");
// d = y.add(d.getFraction('year'));
d = d.getFraction("year");
var db = ee.Image.constant(d).rename(["year"]).float();
db = db; //.updateMask(img.select([0]).mask())
return img.addBands(db);
}
function addYearYearFractionBand(img) {
var d = ee.Date(img.get("system:time_start"));
var y = d.get("year");
// d = y.add(d.getFraction('year'));
d = d.getFraction("year");
var db = ee.Image.constant(y)
.add(ee.Image.constant(d))
.rename(["year"])
.float();
db = db; //.updateMask(img.select([0]).mask())
return img.addBands(db);
}
function addYearBand(img) {
var d = ee.Date(img.get("system:time_start"));
var y = d.get("year");
var db = ee.Image.constant(y).rename(["year"]).float();
db = db; //.updateMask(img.select([0]).mask())
return img.addBands(db).float();
}
function addJulianDayBand(img) {
var d = ee.Date(img.get("system:time_start"));
var julian = ee.Image(ee.Number.parse(d.format("DD"))).rename(["julianDay"]);
return img.addBands(julian).float();
}
function addYearJulianDayBand(img) {
var d = ee.Date(img.get("system:time_start"));
var yj = ee.Image(ee.Number.parse(d.format("YYDD"))).rename(["yearJulian"]);
return img.addBands(yj).float();
}
function addFullYearJulianDayBand(img) {
var d = ee.Date(img.get("system:time_start"));
var julian = ee.Number(d.getRelative("day", "year")).add(1).format("%03d");
var y = ee.String(d.get("year"));
var yj = (yj = ee
.Image(ee.Number.parse(d.format("YYYYDD")))
.rename(["yearJulian"])
.int64());
return img.addBands(yj).float();
}
function offsetImageDate(img, n, unit) {
var date = ee.Date(img.get("system:time_start"));
date = date.advance(n, unit);
// date = ee.Date.fromYMD(100,date.get('month'),date.get('day'))
return img.set("system:time_start", date.millis());
}
////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
var fringeCountThreshold = 279; //Define number of non null observations for pixel to not be classified as a fringe
///////////////////////////////////////////////////
//Kernel used for defringing
var k = ee.Kernel.fixed(41, 41, [
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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function defringeLandsat(img) {
//Find any pixel without sufficient non null pixels (fringes)
var m = img.mask().reduce(ee.Reducer.min());
//Apply kernel
var sum = m.reduceNeighborhood(ee.Reducer.sum(), k, "kernel");
// Map.addLayer(img,vizParams,'with fringes')
// Map.addLayer(sum,{'min':20,'max':241},'sum41',false)
//Mask pixels w/o sufficient obs
sum = sum.gte(fringeCountThreshold);
img = img.mask(sum);
// Map.addLayer(img,vizParams,'defringed')
return img;
}
//////////////////////////////////////////////////////
//Function to find unique values of a field in a collection
function uniqueValues(collection, field) {
var values = ee
.Dictionary(
collection
.reduceColumns(ee.Reducer.frequencyHistogram(), [field])
.get("histogram")
)
.keys();
return values;
}
///////////////////////////////////////////////////////
//Function to simplify data into daily mosaics
//This procedure must be used for proper processing of S2 imagery
function dailyMosaics(imgs) {
//Simplify date to exclude time of day
imgs = imgs.map(function (img) {
var d = ee.String(img.date().format("YYYY-MM-dd"));
var orbit = ee.Number(img.get("SENSING_ORBIT_NUMBER")).int16().format();
return img.set({ "date-orbit": d.cat(ee.String("_")).cat(orbit), date: d });
});
//Find the unique days
var dayOrbits = ee.Dictionary(imgs.aggregate_histogram("date-orbit")).keys();
print("Day-Orbits:", dayOrbits);
function getMosaic(d) {
var date = ee.Date(ee.String(d).split("_").get(0));
var orbit = ee.Number.parse(ee.String(d).split("_").get(1));
var t = imgs
.filterDate(date, date.advance(1, "day"))
.filter(ee.Filter.eq("SENSING_ORBIT_NUMBER", orbit));
var f = ee.Image(t.first());
t = t.mosaic();
t = t.set("system:time_start", date.millis());
t = t.copyProperties(f);
return t;
}
imgs = dayOrbits.map(getMosaic);
imgs = ee.ImageCollection.fromImages(imgs);
print("N s2 mosaics:", imgs.size());
return imgs;
}
///////////////////////////////////////////////////////
// Sentinel 1 processing
// Adapted from: https://code.earthengine.google.com/39a3ad5ac59cd8af14e3dbd78436d2b5
// Author: Warren Scott