-
Notifications
You must be signed in to change notification settings - Fork 9
/
changeDetectionLib.py
2936 lines (2448 loc) · 110 KB
/
changeDetectionLib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Apply change detection methods usin GEE
geeViz.changeDetectionLib is the core module for setting up various change detection algorithms within GEE. Notably, it facilitates the use of LandTrendr and CCDC data preparation, application, and output formatting, compression, and decompression.
"""
"""
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 basic change detection
# Intended to work within the geeViz package
######################################################################
# Adapted from changeDetectionLib.js
from geeViz.getImagesLib import *
import sys, math, ee
from datetime import datetime
# -------------------------------------------------------------------------
# Image and array manipulation
# ------------------------------------------------------------------------
lossYearPalette = "ffffe5,fff7bc,fee391,fec44f,fe9929,ec7014,cc4c02".split(",")
lossMagPalette = "D00,F5DEB3".split(",")
gainYearPalette = "c5ee93,00a398".split(",")
gainMagPalette = "F5DEB3,006400".split(",")
changeDurationPalette = "BD1600,E2F400,0C2780".split(",")
######################################################################
# Helper to multiply image
def multBands(img, distDir, by=1):
out = img.multiply(ee.Image(distDir).multiply(by))
out = ee.Image(out.copyProperties(img, ["system:time_start"]).copyProperties(img))
return out
######################################################################
# Default run params for LandTrendr
default_lt_run_params = {
"maxSegments": 6,
"spikeThreshold": 0.9,
"vertexCountOvershoot": 3,
"preventOneYearRecovery": True,
"recoveryThreshold": 0.25,
"pvalThreshold": 0.05,
"bestModelProportion": 0.75,
"minObservationsNeeded": 6,
}
######################################################################
# Helper to multiply new baselearner format values (LandTrendr & Verdet) by the appropriate amount when importing
# Duration is the only band that does not get multiplied by 0.0001 upon import.
def LT_VT_multBands(img):
fitted = img.select(".*_fitted").multiply(0.0001)
slope = img.select(".*_slope").multiply(0.0001)
diff = img.select(".*_diff").multiply(0.0001)
mag = img.select(".*_mag").multiply(0.0001)
dur = img.select(".*_dur")
out = dur.addBands(fitted).addBands(slope).addBands(diff).addBands(mag)
out = out.copyProperties(img, ["system:time_start"]).copyProperties(img)
return out
def addToImage(img, howMuch):
out = img.add(ee.Image(howMuch))
out = ee.Image(out.copyProperties(img, ["system:time_start"]).copyProperties(img))
return out
# Used when masking out pixels that don't have sufficient data for Landtrendr and Verdet
def nullFinder(img, countMask):
m = img.mask()
# Allow areas with insufficient data to be included, but then set to a dummy value for later masking
m = m.Or(countMask.Not())
img = img.mask(m)
img = img.where(countMask.Not(), -32768)
return img
# Function to convert an image array object to collection
def arrayToTimeSeries(tsArray, yearsArray, possibleYears, bandName):
# Set up dummy image for handling null values
noDateValue = -32768
dummyImage = ee.Image(noDateValue).toArray()
# Iterate across years
def applyMasks(yr):
yr = ee.Number(yr)
# Pull out given year
yrMask = yearsArray.eq(yr)
# Mask array for that given year
masked = tsArray.arrayMask(yrMask)
# Find null pixels
l = masked.arrayLength(0)
# Fill null values and convert to regular image
masked = masked.where(l.eq(0), dummyImage).arrayGet([-1])
# Remask nulls
masked = (
masked.updateMask(masked.neq(noDateValue))
.rename([bandName])
.set("system:time_start", ee.Date.fromYMD(yr, 6, 1).millis())
)
return masked
tsC = possibleYears.map(lambda yr: applyMasks(yr))
return ee.ImageCollection(tsC)
#########################################################################################################
###### GREATEST DISTURBANCE EXTRACTION FUNCTIONS #####
#########################################################################################################
# ----- function to extract greatest disturbance based on spectral delta between vertices
def extractDisturbance(lt, distDir, params, mmu):
# select only the vertices that represents a change
vertexMask = lt.arraySlice(0, 3, 4) # get the vertex - yes(1)/no(0) dimension
vertices = lt.arrayMask(vertexMask) # convert the 0's to masked
# numberOfVertices = vertexMask.arrayReduce(ee.Reducer.sum(),[1]).arrayProject([1]).arrayFlatten([['vertexCount']])
# secondMask = numberOfVertices.gte(3)
# thirdMask = numberOfVertices.gte(4)
# Map.addLayer(numberOfVertices,{min:2,max:4},'number of vertices',false)
# construct segment start and end point years and index values
left = vertices.arraySlice(
1, 0, -1
) # slice out the vertices as the start of segments
right = vertices.arraySlice(
1, 1, None
) # slice out the vertices as the end of segments
startYear = left.arraySlice(
0, 0, 1
) # get year dimension of LT data from the segment start vertices
startVal = left.arraySlice(
0, 2, 3
) # get spectral index dimension of LT data from the segment start vertices
endYear = right.arraySlice(
0, 0, 1
) # get year dimension of LT data from the segment end vertices
endVal = right.arraySlice(
0, 2, 3
) # get spectral index dimension of LT data from the segment end vertices
dur = endYear.subtract(
startYear
) # subtract the segment start year from the segment end year to calculate the duration of segments
mag = endVal.subtract(
startVal
) # substract the segment start index value from the segment end index value to calculate the delta of segments
# concatenate segment start year, delta, duration, and starting spectral index value to an array
distImg = ee.Image.cat([startYear.add(1), mag, dur, startVal.multiply(-1)]).toArray(
0
) # make an image of segment attributes - multiply by the distDir parameter to re-orient the spectral index if it was flipped for segmentation - do it here so that the subtraction to calculate segment delta in the above line is consistent - add 1 to the detection year, because the vertex year is not the first year that change is detected, it is the following year
# sort the segments in the disturbance attribute image delta by spectral index change delta
distImgSorted = distImg.arraySort(mag.multiply(-1))
# slice out the first (greatest) delta
tempDistImg1 = distImgSorted.arraySlice(1, 0, 1).unmask(
ee.Image(ee.Array([[0], [0], [0], [0]]))
)
tempDistImg2 = distImgSorted.arraySlice(1, 1, 2).unmask(
ee.Image(ee.Array([[0], [0], [0], [0]]))
)
tempDistImg3 = distImgSorted.arraySlice(1, 2, 3).unmask(
ee.Image(ee.Array([[0], [0], [0], [0]]))
)
# make an image from the array of attributes for the greatest disturbance
finalDistImg1 = tempDistImg1.arrayProject([0]).arrayFlatten(
[["yod", "mag", "dur", "preval"]]
)
finalDistImg2 = tempDistImg2.arrayProject([0]).arrayFlatten(
[["yod", "mag", "dur", "preval"]]
)
finalDistImg3 = tempDistImg3.arrayProject([0]).arrayFlatten(
[["yod", "mag", "dur", "preval"]]
)
# filter out disturbances based on user settings
def filterDisturbances(finalDistImg):
# threshold = ee.Image(finalDistImg.select(['dur'])) # get the disturbance band out to apply duration dynamic disturbance magnitude threshold
# .multiply((params.tree_loss20 - params.tree_loss1) / 19.0) # ...
# .add(params.tree_loss1) # ...interpolate the magnitude threshold over years between a 1-year mag thresh and a 20-year mag thresh
# .lte(finalDistImg.select(['mag'])) # ...is disturbance less then equal to the interpolated, duration dynamic disturbance magnitude threshold
# .and(finalDistImg.select(['mag']).gt(0)) # and is greater than 0
# .and(finalDistImg.select(['preval']).gt(params.pre_val))
longTermDisturbance = finalDistImg.select(["dur"]).gte(15)
longTermThreshold = (
finalDistImg.select(["mag"])
.gte(params["tree_loss20"])
.And(longTermDisturbance)
)
threshold = finalDistImg.select(["mag"]).gte(params["tree_loss1"])
return finalDistImg.updateMask(threshold.Or(longTermThreshold))
finalDistImg1 = filterDisturbances(finalDistImg1)
finalDistImg2 = filterDisturbances(finalDistImg2)
finalDistImg3 = filterDisturbances(finalDistImg3)
def applyMMU(finalDistImg):
# patchify based on disturbances having the same year of detection
# count the number of pixel in a candidate patch
mmuPatches = (
finalDistImg.select(["yod.*"])
.int16()
.connectedPixelCount(mmu, True)
.gte(mmu)
) # are the the number of pixels per candidate patch greater than user-defined minimum mapping unit?
return finalDistImg.updateMask(
mmuPatches
) # mask the pixels/patches that are less than minimum mapping unit
# patchify the remaining disturbance pixels using a minimum mapping unit
if mmu > 1:
print("Applying mmu:" + str(mmu) + " to LANDTRENDR heuristic outputs")
finalDistImg1 = applyMMU(finalDistImg1)
finalDistImg2 = applyMMU(finalDistImg2)
finalDistImg3 = applyMMU(finalDistImg3)
return finalDistImg1.addBands(finalDistImg2).addBands(
finalDistImg3
) # return the filtered greatest disturbance attribute image
# -------------------------------------------------------------------------
# LandTrendr Code
# ------------------------------------------------------------------------
# Landtrendr code taken from users/emaprlab/public
###### UNPACKING LT-GEE OUTPUT STRUCTURE FUNCTIONS #####
# ----- FUNCTION TO EXTRACT VERTICES FROM LT RESULTS AND STACK BANDS -----
def getLTvertStack(LTresult, run_params):
emptyArray = (
[]
) # make empty array to hold another array whose length will vary depending on maxSegments parameter
vertLabels = (
[]
) # make empty array to hold band names whose length will vary depending on maxSegments parameter
# iString # initialize variable to hold vertex number
# loop through the maximum number of vertices in segmentation and fill empty arrays:
for i in range(1, run_params["maxSegments"] + 2):
vertLabels.append(
"vert_" + str(i)
) # define vertex number as string, make a band name for given vertex
emptyArray.append(0) # fill in emptyArray
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,
]
)
)
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
vmask = LTresult.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
# Line by line comments taken from call below
# .arrayMask 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()...from the vertOnly data subset slice out the vert year row, raw spectral row, and fitted spectral row
# .addBands() # ...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() # ...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()...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()...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
ltVertStack = (
LTresult.arrayMask(vmask)
.arraySlice(0, 0, 3)
.addBands(zeros)
.toArray(1)
.arraySlice(1, 0, run_params["maxSegments"] + 1)
.arrayFlatten(lbls, "")
)
return ltVertStack # return the stack
# Adapted version for converting sorted array to image
def getLTStack(LTresult, maxVertices, bandNames):
nBands = len(bandNames)
emptyArray = (
[]
) # make empty array to hold another array whose length will vary depending on maxSegments parameter
vertLabels = (
[]
) # make empty array to hold band names whose length will vary depending on maxSegments parameter
for i in range(
1, maxVertices + 1
): # loop through the maximum number of vertices in segmentation and fill empty arrays
vertLabels.append(str(i)) # make a band name for given vertex
emptyArray.append(-32768) # fill in emptyArray
# Set up empty array list
emptyArrayList = []
for i in range(1, nBands + 1):
emptyArrayList.append(emptyArray)
zeros = ee.Image(
ee.Array(emptyArrayList)
) # make an image to fill holes in result 'LandTrendr' array where vertices found is not equal to maxSegments parameter plus 1
lbls = [
bandNames,
vertLabels,
] # labels for 2 dimensions of the array that will be cast to each other in the final step of creating the vertice output
# 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
ltVertStack = (
LTresult.addBands(zeros)
.toArray(1)
.arraySlice(1, 0, maxVertices)
.arrayFlatten(lbls, "")
)
# Line by line comments taken from call above
# LTresult: # 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.
# .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, maxVertices): # ...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.updateMask(ltVertStack.neq(-32768))
############################################################################################################
# Function to remove non vertex info from raw image array format from LandTrendr.
# E.g. if an output is [1985,1990,2020],[500,450,320],[500,510,320],[1,0,1], the output will be [1985,2020],[500,320]
# This is the equivalent to the vert stack functions by keeps outputs in image array format
def rawLTToVertices(rawLT, indexName=None, multBy=10000, vertexNoData=-32768):
if indexName != None:
try:
distDir = changeDirDict[indexName]
except:
distDir = -1
else:
distDir = -1
ltArray = rawLT.select(["LandTrendr"])
rmse = rawLT.select(["rmse"]).multiply(multBy)
vertices = ltArray.arraySlice(0, 3, 4)
ltArray = ltArray.arrayMask(vertices)
minObservationsNeededMask = (
ltArray.arraySlice(0, 1, 2)
.arraySlice(1, 0, 1)
.neq(vertexNoData)
.arrayProject([0])
.arrayFlatten([["test"]])
)
ltArray = ltArray.arrayMask(ee.Image(ee.Array([[1], [0], [1], [0]])))
l = ltArray.arrayLength(1)
multImg = ee.Image(ee.Array([[1], [distDir * multBy]])).arrayRepeat(1, l)
ltArray = ltArray.multiply(multImg)
return ltArray.addBands(rmse).updateMask(minObservationsNeededMask)
############################################################################################################
# Function to wrap landtrendr processing
def landtrendrWrapper(
processedComposites,
startYear,
endYear,
indexName,
distDir,
run_params,
distParams,
mmu,
):
# startYear = 1984#ee.Date(ee.Image(processedComposites.first()).get('system:time_start')).get('year').getInfo()
# endYear = 2017#ee.Date(ee.Image(processedComposites.sort('system:time_start',false).first()).get('system:time_start')).get('year').getInfo()
noDataValue = 32768
if distDir == 1:
noDataValue = -1.0 * noDataValue
# ----- RUN LANDTRENDR -----
ltCollection = processedComposites.select(indexName).map(
lambda img: ee.Image(multBands(img, distDir, 1))
) # .unmask(noDataValue)
# Map.addLayer(ltCollection,{},'ltCollection',false)
run_params["timeSeries"] = (
ltCollection # add LT collection to the segmentation run parameter object
)
lt = ee.Algorithms.TemporalSegmentation.LandTrendr(
**run_params
) # run LandTrendr spectral temporal segmentation algorithm
#########################################################################################################
###### RUN THE GREATEST DISTURBANCE EXTRACT FUNCTION #####
#########################################################################################################
# run the dist extract function
distImg = extractDisturbance(lt.select("LandTrendr"), distDir, distParams, mmu)
distImgBandNames = distImg.bandNames()
distImgBandNames = distImgBandNames.map(
lambda bn: ee.String(indexName).cat("_").cat(bn)
)
distImg = distImg.rename(distImgBandNames)
# Convert to collection
rawLT = lt.select([0])
ltYear = rawLT.arraySlice(0, 0, 1).arrayProject([1])
ltFitted = rawLT.arraySlice(0, 2, 3).arrayProject([1])
if distDir == -1:
ltFitted = ltFitted.multiply(-1)
fittedCollection = arrayToTimeSeries(
ltFitted, ltYear, ee.List.sequence(startYear, endYear), "LT_Fitted_" + indexName
)
# Convert to single image
vertStack = getLTvertStack(rawLT, run_params)
return [lt, distImg, fittedCollection, vertStack]
#########################################################################################################
#########################################################################################################
# Function to join raw time series with fitted time series from LANDTRENDR
# Takes the rawTs as an imageCollection, lt is the first band of the output from LANDTRENDR, and the distDir
# is the direction of change for a loss in vegeation for the chosen band/index
def getRawAndFittedLT(rawTs, lt, startYear, endYear, indexName="Band", distDir=-1):
# Pop off years and fitted values
ltYear = lt.arraySlice(0, 0, 1).arrayProject([1])
ltFitted = lt.arraySlice(0, 2, 3).arrayProject([1])
# Flip fitted values if needed
if distDir == -1:
ltFitted = ltFitted.multiply(-1)
# Convert array to an imageCollection
fittedCollection = arrayToTimeSeries(
ltFitted, ltYear, ee.List.sequence(startYear, endYear), "LT_Fitted_" + indexName
)
# Join raw time series with fitted
joinedTS = joinCollections(rawTs, fittedCollection)
return joinedTS
#########################################################################################################
# 2023 rework to run LT in its most simple form
# Gets rid of handling :
# Insufficient obs counts, no data handling,
# Exporting of band stack format (assumes image array format for output)
# Function to mask out the non vertex and original values
# Simplified version of rawLTToVertices
def simpleRawLTToVertices(rawLT):
# Pull off rmse
rmse = rawLT.select(["rmse"])
# Mask out non vertex values to use less storage space
ltArray = rawLT.select(["LandTrendr"])
vertices = ltArray.arraySlice(0, 3, 4)
ltArray = ltArray.arrayMask(vertices)
# Mask out all but the year and vertex fited values (get rid of the raw and vertex rows)
return ltArray.arrayMask(ee.Image(ee.Array([[1], [0], [1], [0]]))).addBands(rmse)
###########################################################
# Function to multiply the LandTrendr RMSE and vertex array
# Assumes LTMaskNonVertices has already been run
def multLT(rawLT, multBy):
# Pull off rmse
rmse = rawLT.select(["rmse"]).multiply(multBy).abs()
# Ensure only the LandTrendr array output
ltArray = rawLT.select(["LandTrendr"])
# Form an image to multiply by
l = ltArray.arrayLength(1)
multImg = ee.Image(ee.Array([[1], [multBy]])).arrayRepeat(1, l)
return ltArray.multiply(multImg).addBands(rmse)
###########################################################
# Function to simplify LandTrendr output for exporting
def LTExportPrep(rawLT, multBy=10000):
rawLT = simpleRawLTToVertices(rawLT)
rawLT = multLT(rawLT, multBy)
return rawLT
###########################################################
# New function 11/23 to simplify running of LandTrendr
# and prepping outputs for export
def runLANDTRENDR(ts, bandName, run_params=None):
# Get single band time series and set its direction so that a loss in veg/moisture is going up
ts = ts.select([bandName])
try:
distDir = changeDirDict[bandName]
except:
distDir = -1
ts = ts.map(lambda img: multBands(img, 1, distDir))
# Set up run params
if run_params == None:
run_params = default_lt_run_params
run_params["timeSeries"] = ts
# Run LANDTRENDR
rawLT = ee.Algorithms.TemporalSegmentation.LandTrendr(**run_params)
# Get vertex-only fitted values and multiply the fitted values
return (
LTExportPrep(rawLT, distDir).set("band", bandName).set("run_params", run_params)
)
###########################################################
# Pulled from simpleLANDTRENDR below to take the lossGain dictionary and prep it for export
def LTLossGainExportPrep(lossGainDict, indexName="Bn", multBy=10000):
lossStack = lossGainDict["lossStack"]
gainStack = lossGainDict["gainStack"]
# Convert to byte/int16 if possible to save space
lossThematic = (
lossStack.select([".*_yr_.*"])
.int16()
.addBands(lossStack.select([".*_dur_.*"]).byte())
)
lossContinuous = lossStack.select([".*_mag_.*", ".*_slope_.*"]).multiply(multBy)
if abs(multBy) == 10000:
lossContinuous = lossContinuous.int16()
lossStack = lossThematic.addBands(lossContinuous)
gainThematic = (
gainStack.select([".*_yr_.*"])
.int16()
.addBands(gainStack.select([".*_dur_.*"]).byte())
)
gainContinuous = gainStack.select([".*_mag_.*", ".*_slope_.*"]).multiply(multBy)
if abs(multBy) == 10000:
gainContinuous = gainContinuous.int16()
gainStack = gainThematic.addBands(gainContinuous)
outStack = lossStack.addBands(gainStack)
# Add indexName to bandnames
bns = outStack.bandNames()
outBns = bns.map(lambda bn: ee.String(indexName).cat("_LT_").cat(bn))
return outStack.rename(outBns)
###########################################################
# Pulled from simpleLANDTRENDR below to take prepped (must run LTLossGainExportPrep first) lossGain stack and view it
def addLossGainToMap(
lossGainStack,
startYear,
endYear,
lossMagMin=-8000,
lossMagMax=-2000,
gainMagMin=1000,
gainMagMax=8000,
indexName=None,
howManyToPull=None,
):
if indexName == None or howManyToPull == None:
bns = lossGainStack.bandNames().getInfo()
indexName = bns[0].split("_")[0]
howManyToPull = list(set([int(bn.split("_")[-1]) for bn in bns]))
else:
howManyToPull = list(range(1,howManyToPull + 1))
# Set up viz params
vizParamsLossYear = {"min": startYear, "max": endYear, "palette": lossYearPalette}
vizParamsLossMag = {"min": lossMagMin, "max": lossMagMax, "palette": lossMagPalette}
vizParamsGainYear = {"min": startYear, "max": endYear, "palette": gainYearPalette}
vizParamsGainMag = {"min": gainMagMin, "max": gainMagMax, "palette": gainMagPalette}
vizParamsDuration = {
"min": 1,
"legendLabelLeftAfter": "year",
"legendLabelRightAfter": "years",
"max": 5,
"palette": changeDurationPalette,
}
for i in howManyToPull:
lossStackI = lossGainStack.select([".*_loss_.*_" + str(i)])
gainStackI = lossGainStack.select([".*_gain_.*_" + str(i)])
# print(lossStackI.select(['loss_yr.*']).getInfo())
showLossYear = False
if i == 1:
showLossYear = True
Map.addLayer(
lossStackI.select([".*_loss_yr.*"]),
vizParamsLossYear,
str(i) + " " + indexName + " Loss Year",
showLossYear,
)
Map.addLayer(
lossStackI.select([".*_loss_mag.*"]),
vizParamsLossMag,
str(i) + " " + indexName + " Loss Magnitude",
False,
)
Map.addLayer(
lossStackI.select([".*_loss_dur.*"]),
vizParamsDuration,
str(i) + " " + indexName + " Loss Duration",
False,
)
Map.addLayer(
gainStackI.select([".*_gain_yr.*"]),
vizParamsGainYear,
str(i) + " " + indexName + " Gain Year",
False,
)
Map.addLayer(
gainStackI.select([".*_gain_mag.*"]),
vizParamsGainMag,
str(i) + " " + indexName + " Gain Magnitude",
False,
)
Map.addLayer(
gainStackI.select([".*_gain_dur.*"]),
vizParamsDuration,
str(i) + " " + indexName + " Gain Duration",
False,
)
#########################################################################################################
# Function for running LT, thresholding the segments for both loss and gain, sort them, and convert them to an image stack
# July 2019 LSC: replaced some parts of workflow with functions in changeDetectionLib
def simpleLANDTRENDR(
ts,
startYear,
endYear,
indexName="NBR",
run_params=None,
lossMagThresh=-0.15,
lossSlopeThresh=-0.1,
gainMagThresh=0.1,
gainSlopeThresh=0.1,
slowLossDurationThresh=3,
chooseWhichLoss="largest",
chooseWhichGain="largest",
addToMap=True,
howManyToPull=2,
multBy=10000,
):
"""
Takes annual time series input data, properly sets it up for LandTrendr, runs LandTrendr, and provides both a compressed vertex-only format output as well as a basic change detection output.
"""
if run_params == None:
run_params = default_lt_run_params
ts = ts.select(indexName)
lt = runLANDTRENDR(ts, indexName, run_params)
try:
distDir = changeDirDict[indexName]
except:
distDir = -1
ltTS = simpleLTFit(
lt,
startYear,
endYear,
indexName=indexName,
arrayMode=True,
maxSegs=run_params["maxSegments"],
)
joinedTS = joinCollections(ts, ltTS.select([".*_LT_fitted"]))
# Flip the output back around if needed to do change detection
ltRawPositiveForChange = multLT(lt, distDir)
# Take the LT output and detect change
lossGainDict = convertToLossGain(
ltRawPositiveForChange,
"arrayLandTrendr",
lossMagThresh,
lossSlopeThresh,
gainMagThresh,
gainSlopeThresh,
slowLossDurationThresh,
chooseWhichLoss,
chooseWhichGain,
howManyToPull,
)
# Prep loss gain dictionary into multi-band image ready for exporting
lossGainStack = LTLossGainExportPrep(lossGainDict, indexName, multBy)
# Add the change outputs to the map if specified to do so
if addToMap:
Map.addLayer(joinedTS, {"opacity": 0}, "Raw and Fitted Time Series", True)
addLossGainToMap(
lossGainStack,
startYear,
endYear,
(lossMagThresh - 0.7) * multBy,
lossMagThresh * multBy,
gainMagThresh * multBy,
(gainMagThresh + 0.7) * multBy,
indexName,
howManyToPull,
)
return [multLT(lt, multBy), lossGainStack]
#########################################################################################################
#########################################################################################################
# Function to prep data following our workflows. Will have to run Landtrendr and convert to stack after.
def prepTimeSeriesForLandTrendr(ts, indexName, run_params):
maxSegments = ee.Number(run_params["maxSegments"])
# Get single band time series and set its direction so that a loss in veg is going up
ts = ts.select([indexName])
distDir = changeDirDict[indexName]
tsT = ts.map(lambda img: multBands(img, 1, distDir))
# Find areas with insufficient data to run LANDTRENDR
countMask = tsT.count().unmask().gte(run_params["minObservationsNeeded"])
# Mask areas identified by countMask
tsT = tsT.map(lambda img: nullFinder(img, countMask))
run_params["timeSeries"] = tsT
countMask = countMask.rename("insufficientDataMask")
prepDict = {"run_params": run_params, "countMask": countMask}
return prepDict
# This function outputs Landtrendr as a vertical stack and adds properties about the run.
def LANDTRENDRVertStack(composites, indexName, run_params, startYear, endYear):
creationDate = datetime.strftime(datetime.now(), "%Y%m%d")
composites = composites.filter(ee.Filter.calendarRange(startYear, endYear, "year"))
# Prep Time Series and put into run parameters
prepDict = prepTimeSeriesForLandTrendr(composites, indexName, run_params)
run_params = prepDict["run_params"]
countMask = prepDict["countMask"]
# Run LANDTRENDR
rawLt = ee.Algorithms.TemporalSegmentation.LandTrendr(**run_params)
# Map.addLayer(rawLt,{},'raw lt {}-{}'.format(startYear,endYear))
# Convert to image stack
lt = rawLt.select([0])
ltStack = ee.Image(getLTvertStack(lt, run_params)).updateMask(countMask)
ltStack = ltStack.select("yrs.*").addBands(ltStack.select("fit.*"))
rmse = rawLt.select([1]).rename("rmse")
ltStack = ltStack.addBands(rmse)
# Undo distdir change done in prepTimeSeriesForLandtrendr()
ltStack = applyDistDir_vertStack(ltStack, changeDirDict[indexName], "landtrendr")
# Set Properties
ltStack = ltStack.set(
{
"startYear": startYear,
"endYear": endYear,
"band": indexName,
"creationDate": creationDate,
"maxSegments": run_params["maxSegments"],
"spikeThreshold": run_params["spikeThreshold"],
"vertexCountOvershoot": run_params["vertexCountOvershoot"],
"recoveryThreshold": run_params["recoveryThreshold"],
"pvalThreshold": run_params["pvalThreshold"],
"bestModelProportion": run_params["bestModelProportion"],
"minObservationsNeeded": run_params["minObservationsNeeded"],
}
)
return ee.Image(ltStack)
#############################################/
# Function for running LANDTRENDR and converting output to annual image collection
# with the fitted value, duration, magnitude, slope, and diff for the segment for each given year
def LANDTRENDRFitMagSlopeDiffCollection(ts, indexName, run_params):
startYear = ee.Date(ts.first().get("system:time_start")).get("year")
endYear = ee.Date(
ts.sort("system:time_start", False).first().get("system:time_start")
).get("year")
# Run LandTrendr and convert to VertStack format
ltStack = ee.Image(
LANDTRENDRVertStack(ts, indexName, run_params, startYear, endYear)
)
ltStack = ee.Image(LT_VT_vertStack_multBands(ltStack, "landtrendr", 10000))
# Convert to durFitMagSlope format
durFitMagSlope = convertStack_To_DurFitMagSlope(ltStack, "LT")
return durFitMagSlope
# ----------------------------------------------------------------------------------------------------
# Functions for both Verdet and Landtrendr
# ----------------------------------------------------------------------------------------------------
# Helper to multiply new baselearner format values (LandTrendr & Verdet) by the appropriate amount when importing
# Duration is the only band that does not get multiplied by 0.0001 upon import.
# img = landtrendr or verdet image in fitMagDurSlope format
# multBy = 10000 (to prep for export) or 0.0001 (after import)
def LT_VT_multBands(img, multBy):
fitted = img.select(".*_fitted").multiply(multBy)
slope = img.select(".*_slope").multiply(multBy)
diff = img.select(".*_diff").multiply(multBy)
mag = img.select(".*_mag").multiply(multBy)
dur = img.select(".*_dur")
out = dur.addBands(fitted).addBands(slope).addBands(diff).addBands(mag)
out = out.copyProperties(img, ["system:time_start"]).copyProperties(img)
return out
# Function to apply the Direction of a decrease in photosynthetic vegetation to Landtrendr or Verdet vertStack format
# img = vertStack image for one band, e.g. "NBR"
# verdet_or_landtrendr = 'verdet' or 'landtrendr'
# distDir = from getImagesLib.changeDirDict
def applyDistDir_vertStack(stack, distDir, verdet_or_landtrendr):
years = stack.select("yrs.*")
fitted = stack.select("fit.*").multiply(distDir)
out = years.addBands(fitted)
if verdet_or_landtrendr == "landtrendr":
rmse = stack.select("rmse")
out = out.addBands(rmse)
out = out.copyProperties(stack, ["system:time_start"]).copyProperties(stack)
return out
# Helper to multiply vertStack bands by the appropriate amount before exporting (multBy = 10000)
# or after importing (multBy = 0.0001)
# img = vertStack image for one band, e.g. "NBR"
# verdet_or_landtrendr = 'verdet' or 'landtrendr'
# multBy = 10000 or 0.0001
def LT_VT_vertStack_multBands(img, verdet_or_landtrendr, multBy):
years = img.select("yrs.*")
fitted = img.select("fit.*").multiply(multBy)
out = years.addBands(fitted)
if verdet_or_landtrendr == "landtrendr":
rmse = img.select("rmse").multiply(multBy)
out = out.addBands(rmse)
out = out.copyProperties(img, ["system:time_start"]).copyProperties(img)
return out
# Simplified method to convert LANDTRENDR stack to annual collection of
# Duration, fitted, magnitude, slope, and diff
# Improved handling of start year delay found in older method
def simpleLTFit(
ltStack, startYear, endYear, indexName="bn", arrayMode=True, maxSegs=6, multBy=1
):
indexName = ee.String(indexName)
# Set up output band names
outBns = [
indexName.cat("_LT_dur"),
indexName.cat("_LT_fitted"),
indexName.cat("_LT_mag"),
indexName.cat("_LT_slope"),
indexName.cat("_LT_diff"),
]
# Separate years and fitted values of vertices
if arrayMode:
ltStack = ltStack.select([0])
zeros = ee.Image(ee.Array([0]).repeat(0, maxSegs + 2))
yrBns = ["yrs_{}".format(i) for i in range(1, maxSegs + 2)]
fitBns = ["fit_{}".format(i) for i in range(1, maxSegs + 2)]
yrs = (
ltStack.arraySlice(0, 0, 1)
.arrayProject([1])
.arrayCat(zeros, 0)
.arraySlice(0, 0, maxSegs + 1)
.arrayFlatten([yrBns])
.selfMask()
)
fit = (
ltStack.arraySlice(0, 1, 2)
.arrayProject([1])
.arrayCat(zeros, 0)
.arraySlice(0, 0, maxSegs + 1)
.arrayFlatten([fitBns])
.updateMask(yrs.mask())
)
else:
yrs = ltStack.select("yrs_.*").selfMask()
fit = ltStack.select("fit_.*").updateMask(yrs.mask())
fit = fit.multiply(multBy)
# Find the first and last vertex years
isStartYear = yrs.reduce(ee.Reducer.firstNonNull())
isEndYear = yrs.reduce(ee.Reducer.lastNonNull())
blankMask = yrs.gte(100000)
# Iterate across each year to find the values for that year
def getYearValues(yr):
yr = ee.Number(yr)
# Find the segment the year belongs to
# Handle whether the year is the same as the first vertex year
startYrMask = blankMask
startYrMask = startYrMask.where(isStartYear.eq(yr), yrs.lte(yr))
startYrMask = startYrMask.where(isStartYear.lt(yr), yrs.lt(yr))
# Handle whether the year is the same as the last vertex year
endYrMask = blankMask
endYrMask = endYrMask.where(isStartYear.eq(yr), yrs.gt(yr))
endYrMask = endYrMask.where(isStartYear.lt(yr), yrs.gte(yr))
# Get fitted values for the vertices segment the year is within
fitStart = fit.updateMask(startYrMask).reduce(ee.Reducer.lastNonNull())
fitEnd = fit.updateMask(endYrMask).reduce(ee.Reducer.firstNonNull())
# Get start and end year for the vertices segment the year is within
yearStart = yrs.updateMask(startYrMask).reduce(ee.Reducer.lastNonNull())
yearEnd = yrs.updateMask(endYrMask).reduce(ee.Reducer.firstNonNull())
# Get the difference and duration of the segment
segDiff = fitEnd.subtract(fitStart)
segDur = yearEnd.subtract(yearStart)
# Get the varius annual derivatives
tDiff = ee.Image(yr).subtract(yearStart)
segSlope = segDiff.divide(segDur)
fitDiff = segSlope.multiply(tDiff)
fitted = fitStart.add(fitDiff)
formatted = (
ee.Image.cat([segDur, fitted, segDiff, segSlope, fitDiff])
.rename(outBns)
.set("system:time_start", ee.Date.fromYMD(yr, 6, 1).millis())
)
return formatted
out = ee.ImageCollection(
ee.List.sequence(startYear, endYear).map(lambda yr: getYearValues(yr))
)
return out
# Wrapper function to iterate across multiple LT band/index values
def batchSimpleLTFit(
ltStacks,
startYear,
endYear,
indexNames=None,
bandPropertyName="band",
arrayMode=True,
maxSegs=6,
multBy=1,
mosaicReducer=ee.Reducer.lastNonNull(),
):
# Get band/index names if not provided
if indexNames == None:
indexNames = ltStacks.aggregate_histogram(bandPropertyName).keys().getInfo()
# Iterate across each band/index and get the fitted, mag, slope, etc
lt_fit = None
for bn in indexNames:
ltt = ltStacks.filter(ee.Filter.eq(bandPropertyName, bn))
bns = ltt.first().bandNames()
ltt = ltt.reduce(mosaicReducer).rename(bns)