-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mosaic.py
1521 lines (1156 loc) · 81.3 KB
/
Mosaic.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
######################################################################################################
# Description: The code in this file was initially created with JavaScript and then was converted to
# to Python in April 2021. Modifications were also made after the code conversion.
#
######################################################################################################
import ee
ee.Initialize()
import math
import Image as Img
import ImgMask as IM
import ImgSet as IS
import eoTileGrids as eoTG
import eoAuxData as eoAD
import eoParams
#veg_NDVI_thresh = 0.4
######################################################################################################
# Description: This function creates a map with all the pixels having an identical time score for a
# given image. Time score is calculated based on the date gap between the acquisition
# date of the given image and a reference date (midDate parameter), which normally is
# the middle date of a time period (e.g., a peak growing season).
#
# Revision history: 2020-Dec-22 Lixin Sun Initial creation
#
######################################################################################################
def get_time_score(image, midDate, ssr_code):
'''Return a time score image corresponding to a given image
Args:
image (ee.Image): A given ee.Image object to be generated a time score image.
midData (ee.Date): The centre date of a time period for a mosaic generation.
ssr_code (int): The sensor type code;
TWinSize(int): The size of a composite time window. '''
#==================================================================================================
# Calculate the date difference betwen the given image and a reference date
# Note that 86400000 is milliseconds per day
#==================================================================================================
millis_per_day = 86400000
img_date = ee.Date(image.date()) # Get the Unix date of the given image
img_year = img_date.get('year') # Get the year integer of the given image
DOY_1st = ee.Date.fromYMD(img_year, 1, 1).millis().divide(millis_per_day) # the unix date of the 1st DOY
mid_date = ee.Date(midDate).update(img_year) # Corrected midDate
img_date = img_date.millis().divide(millis_per_day).subtract(DOY_1st)
refer_date = mid_date.millis().divide(millis_per_day).subtract(DOY_1st)
date_diff = img_date.subtract(refer_date)
#==================================================================================================
# Calculatr time score according to sensor type
#==================================================================================================
ssr_code = int(ssr_code)
STD = 12 if ssr_code > Img.MAX_LS_CODE else 16
one_img = ee.Image.constant(1)
factor = ee.Image(date_diff).divide(ee.Image.constant(STD)).pow(ee.Image.constant(2))
return one_img.divide((ee.Image.constant(0.5).multiply(factor)).exp())
#############################################################################################################
# Description: This function returns a reference mosaic image that will be used in HybridTIC
#
# Revision history: 2023-Nov-24 Lixin Sun Initial creation
#
#############################################################################################################
def period_refer_mosaic(maskedImgColl, SsrData):
'''Args:
maskedImgColl(ee.ImageCollection): A given image collection with mask applied to each image;
SsrData(dictionary): A given dictionary containing some meta data about a sensor.'''
#==========================================================================================================
# Convert the value range to between 0 and 100 and then create a median mosaic image
#==========================================================================================================
ready_ImgColl = maskedImgColl.map(lambda img: Img.apply_gain_offset(img, SsrData, 100, False))
refer_median = ready_ImgColl.median()
#print('<period_refer_mosaic> The bands in median mosaic:', refer_median.bandNames().getInfo())
#==========================================================================================================
# Extract required separate bands and calculate NDVI and modeled blue band image
#==========================================================================================================
blu = refer_median.select(SsrData['BLU'])
red = refer_median.select(SsrData['RED'])
nir = refer_median.select(SsrData['NIR'])
sw2 = refer_median.select(SsrData['SW2'])
NDVI = nir.subtract(red).divide(nir.add(red))
model_blu = sw2.multiply(0.25)
#==========================================================================================================
# Correct the blue band values of median mosaic for the pixels with NDVI values larger than 0.3
#==========================================================================================================
replace_cond = model_blu.lt(blu).And(NDVI.gt(0.3)).And(sw2.gt(blu))
corrected_blu = blu.where(replace_cond, model_blu)
#print('<period_refer_mosaic> The band namd of modeled blue:', corrected_blu.bandNames().getInfo())
return refer_median.addBands(srcImg=corrected_blu, overwrite = True)
#############################################################################################################
# Description: This function returns a reference mosaic image that will be used in HybridTIC
#
# Revision history: 2023-Nov-24 Lixin Sun Initial creation
#
#############################################################################################################
def get_refer_mosaic(masked_ImgColl, SsrData, Start, Stop):
'''Args:
masked_ImgColl(ee.ImageCollection): A given image collection with maske appliedto each image;
SsrData(dictionary): A given dictionary containing some meta data about a sensor;
Start(string): A string represents the starting date of a compositing period;
Stop(string): A string represents the ending date of a compositing period.'''
#==========================================================================================================
# Generate a reference mosaic for entire period specified
#==========================================================================================================
whole_period_refer = period_refer_mosaic(masked_ImgColl, SsrData)
WinSize = IS.time_window_size(Start, Stop).getInfo()
if WinSize < 1000:
return ee.Image(whole_period_refer)
else:
#--------------------------------------------------------------------------------------------------------
# When a compositing period is longer than one month, the 'refer_mosaic' created above is for whole
# compositing period. So a monthly referance mosaic needs to be created.
#--------------------------------------------------------------------------------------------------------
midDate = IS.period_centre(Start, Stop) # Determine the central date of a time window
month_start, month_stop = IS.time_range(midDate, 31) # Determine the start and stop dates of a month
month_ImgColl = masked_ImgColl.filterDate(month_start, month_stop) # get a subset of image collection
#--------------------------------------------------------------------------------------------------------
# Correct the blue band values of monthly mosaic for the pixels with NDVI values larger than 0.3
#--------------------------------------------------------------------------------------------------------
month_refer = period_refer_mosaic(month_ImgColl, SsrData)
month_refer = month_refer.unmask(whole_period_refer)
blu = month_refer.select(SsrData['BLU'])
red = month_refer.select(SsrData['RED'])
nir = month_refer.select(SsrData['NIR'])
sw2 = month_refer.select(SsrData['SW2'])
NDVI = nir.subtract(red).divide(nir.add(red))
model_blu = sw2.multiply(0.3)
replace_cond = model_blu.lt(blu).And(NDVI.gt(0.3))
corrected_blu = blu.where(replace_cond, model_blu)
#--------------------------------------------------------------------------------------------------------
# Replace the blue reference band with corrected one 'corrected_blu'
#--------------------------------------------------------------------------------------------------------
return ee.Image(month_refer.addBands(srcImg=corrected_blu, overwrite = True))
######################################################################################################
# Description: This function returns a HOT score map
#
# Revision history: 2023-Oct-22 Lixin Sun Initial creation
#
######################################################################################################
def get_HOT_score(blu, red):
HOT = blu.subtract(red.multiply(0.5).add(0.8))
one_img = ee.Image.constant(1)
return one_img.divide(one_img.add((HOT.add(0.075).multiply(50)).exp()))
######################################################################################################
# Description: This function returns a HOT score map
#
# Revision history: 2023-Oct-22 Lixin Sun Initial creation
#
######################################################################################################
def get_CCover_score(Img, SsrData):
coverage = ee.Number(Img.get(SsrData['CLOUD'])).divide(100)
return ee.Image.constant(ee.Number(1).subtract(coverage))
######################################################################################################
# Description: This function attaches a NIR-to-blue ratio score map to a given single image
#
# Revision history: 2021-Jun-10 Lixin Sun Initial creation
#
######################################################################################################
def get_maxNBR_score(blu, red, nir, sw1, sw2):
model_blu = (sw2.multiply(0.25)).max(red.multiply(0.5).add(0.8)).max(blu)
return ee.Image(nir.divide(model_blu))
######################################################################################################
# Description: This function creates a score image for a given ee.Image object.
#
# Note: The value ranges of all the input spectral bands must be within [0, 100]
# (1) Using NLCD distance as penalty does not work well
#
# Revision history: 2023-Aug-25 Lixin Sun Initial creation
#
######################################################################################################
def get_spec_score(blu, grn, red, nir, sw1, sw2, refer_blu, refer_nir, water_map):
#==================================================================================================
# Calculate scores assuming all the pixels are water
#==================================================================================================
max_SV = blu.max(grn).max(0.01)
max_SW = sw1.max(sw2).max(0.01)
max_IR = max_SW.max(nir).max(0.01)
water_score = max_SV.divide(max_IR)
water_score = water_score.where(refer_blu.lt(blu), water_score.multiply(-1))
#==================================================================================================
# Calculate scores assuming all the pixels are land
#==================================================================================================
blu_pen = blu.subtract(refer_blu).abs().exp()
nir_pen = nir.subtract(refer_nir).abs()
STD_blu = sw2.multiply(0.25).max(red.multiply(0.5).add(0.8)).max(blu)
land_score = ee.Image(nir.divide(STD_blu.add(blu_pen).add(nir_pen)))
#==================================================================================================
# Replace the land scores with water scores for detecting dynamic water
#==================================================================================================
#zero_img = nir.multiply(0)
#water_mask = zero_img.where(water_map.eq(0).Or(water_map.eq(2)), ee.Image.constant(1))
return land_score.where(water_map.eq(2).Or(water_map.eq(0).And(max_SV.gt(max_IR)).And(max_SW.lt(3.0))), water_score)
######################################################################################################
# Description: This function attaches a MaxNBR score map to a given image
#
# Revision history: 2023-Dec-08 Lixin Sun Initial creation
#
######################################################################################################
def attach_MaxNBR_score(maskedImg, SsrData):
'''This function attaches a MaxNBR score map to a given image
Args:
maskedImg(ee.Image): A given ee.Image object with cloud/shadow mask applied;
SsrData(Dictionary): A sensor info dictionary.'''
#==================================================================================================
# Rescale the given image to value range between 0 and 100
#==================================================================================================
max_ref = 100
readyImg = Img.apply_gain_offset(maskedImg, SsrData, max_ref, False)
#==================================================================================================
# Get separate band images
#==================================================================================================
blu = readyImg.select(SsrData['BLU'])
red = readyImg.select(SsrData['RED'])
nir = readyImg.select(SsrData['NIR'])
sw1 = readyImg.select(SsrData['SW1'])
sw2 = readyImg.select(SsrData['SW2'])
#==================================================================================================
# Calculate maxNBR map
#==================================================================================================
score = ee.Image(get_maxNBR_score(blu, red, nir, sw1, sw2))
return maskedImg.addBands(score.rename([Img.pix_score]))
######################################################################################################
# Description: This function attaches a MaxNDVI score map to a given image
#
# Revision history: 2023-Dec-08 Lixin Sun Initial creation
#
######################################################################################################
def attach_MaxNDVI_score(maskedImg, SsrData):
'''This function attaches a MaxNDVI score map to a given image
Args:
maskedImg(ee.Image): A given ee.Image object with cloud/shadow mask applied;
SsrData(Dictionary): A sensor info dictionary.'''
#==================================================================================================
# Rescale the given image to value range between 0 and 100
#==================================================================================================
max_ref = 100
readyImg = Img.apply_gain_offset(maskedImg, SsrData, max_ref, False)
#==================================================================================================
# Get separate band images
#==================================================================================================
red = readyImg.select(SsrData['RED'])
nir = readyImg.select(SsrData['NIR'])
#==================================================================================================
# Calculate maxNDVI score map
#==================================================================================================
score = ee.Image(nir.subtract(red).divide(nir.add(red)))
return maskedImg.addBands(score.rename([Img.pix_score]))
######################################################################################################
# Description: This function attaches a score map that is calculated based on NLCD algorithm
#
# Revision history: 2023-Jun-10 Lixin Sun Initial creation
#
######################################################################################################
def attach_NLCD_score(maskedImg, SsrData, ready_median_mosaic):
'''This function attaches a score map that is calculated based on NLCD algorithm
Args:
maskedImg(ee.Image): A given single image scene;
SsrData(Dictionary): A sensor info dictionary;
ready_median_mosaic(ee.Image): A median-based mosaic image with values rescaled. '''
#==================================================================================================
# Rescale the given single image and then calculate distance between image and median
#==================================================================================================
max_ref = 100
readyImg = Img.apply_gain_offset(maskedImg, SsrData, max_ref, False).select(SsrData['OUT_BANDS'])
#==================================================================================================
# Calculate the difference between the pixels in the single image and their corresponding median
#==================================================================================================
diffImg = readyImg.subtract(ready_median_mosaic).pow(2).reduce(ee.Reducer.sum()).sqrt()
score = ee.Image.constant(1).divide(diffImg.add(0.001))
return maskedImg.addBands(score.rename([Img.pix_score]))
######################################################################################################
# Description: This function attaches a score map to a given image
#
# Note: (1) This function assumes the value range of the given image is between 0 and 100
# (2) The value range of "median_blue" is already in between 0 and 100
#
# Revision history: 2020-Dec-22 Lixin Sun Initial creation
#
######################################################################################################
def attach_Hybrid_score(maskedImg, midDate, SsrData, ready_refer_mosaic, water_map):
'''Attach a score image to a given image.
Args:
maskedImg(ee.Image): A given ee.Image object with mask applied;
midDate(ee.Date): The centre date of a compositing time period;
SsrData(Dictionary): A Dictionary containing metadata associated with a sensor and data unit;
ready_refer_mosaic(ee.Image): A given reference image that has been rescaled and masked;
water_map(ee.Image): A given permanent water and permanent land map.'''
#==================================================================================================
# Rescale the pixel values to range between 0 and 100
#==================================================================================================
max_ref = 100
readyImg = Img.apply_gain_offset(maskedImg, SsrData, max_ref, False)
#==================================================================================================
# Select blue and NIR bands from the given reference mosaic with rescaled SR values
#==================================================================================================
refer_blu = ready_refer_mosaic.select(SsrData['BLU'])
refer_nir = ready_refer_mosaic.select(SsrData['NIR'])
#dist_img = scaled_img.subtract(refer_mosaic).pow(2).reduce(ee.Reducer.sum()).sqrt()
#==================================================================================================
# Calculate spectral score for all targets, including vegetated, non-vegetated and water
#==================================================================================================
blu = readyImg.select(SsrData['BLU'])
grn = readyImg.select(SsrData['GRN'])
red = readyImg.select(SsrData['RED'])
nir = readyImg.select(SsrData['NIR'])
sw1 = readyImg.select(SsrData['SW1'])
sw2 = readyImg.select(SsrData['SW2'])
#land_score = ee.Image(get_land_score(blu, grn, red, nir, sw1, sw2, MedBlue, MedNIR))
spec_score = ee.Image(get_spec_score(blu, grn, red, nir, sw1, sw2, refer_blu, refer_nir, water_map))
#return maskedImg.addBands(spec_score.rename([Img.pix_score]))
#==================================================================================================
# Calculate could coverage score
#==================================================================================================
cloud_cover = ee.Number(maskedImg.get(SsrData['CLOUD'])).divide(100)
asset_size = ee.Number(maskedImg.get('system:asset_size')).divide(1800000000)
cover_score = ee.Image.constant(ee.Number(1).subtract(cloud_cover))
cover_score = cover_score.where(cover_score.lt(0.7), ee.Image.constant(0)).multiply(asset_size)
#==================================================================================================
# Calculate time score
#==================================================================================================
ssr_code = SsrData['SSR_CODE']
time_score = ee.Image(get_time_score(maskedImg, midDate, ssr_code))
#==================================================================================================
# Calculate total score
#==================================================================================================
total_score = spec_score.multiply((cover_score).add(time_score))
#total_score = cover_score.add(time_score)
return maskedImg.addBands(total_score.rename([Img.pix_score]))
######################################################################################################
# Description: This function attaches a score, acquisition date and some specified bands to each image
# of a collection.
#
# Revision history: 2021-Jun-10 Lixin Sun Initial creation
# 2021-Aug-17 Lixin Sun Fixed the bug after "if addGeometry == True:" statement.
# 2020-Aug-10 Lixin Sun Changed 'addGeometry' parameter to 'ExtraBandCode', so
# that various different bands can be attached to each
# scored image.
######################################################################################################
def score_collection(masked_img_coll, SsrData, midDate, ExtraBandCode, CS_plus, rescaled_refer_mosaic):
'''Attaches a score, acquisition date and some specified bands to each image of a collection.
Args:
masked_img_coll(ee.ImageCollection): A given image collection with mask applied to each image;
SsrData(Dictionary): A Dictionary containing metadata associated with a sensor and data unit;
midDate(ee.Date): The centre date of a comositing time period;
ExtraBandCode(int): The integer code representing band type to be added additionally;
CS_plus(Boolean): A flag indicating if to apply CloudScore+ mask;
rescaled_refer_mosaic(ee.Image): A given rescaled reference image.'''
#print('<score_collection> band names of 1st image = ', collection.first().bandNames().getInfo())
#print('<score_collection> the given collection = ', collection.size().getInfo())
#==================================================================================================
# Obtain a global permanent water and land map
# 0,1 and 2 in the map represent temporary water, permanent land and permanent water, respectively
#==================================================================================================
water_map = eoAD.get_water_land_map(90).unmask()
#==================================================================================================
# Attach a score and an acquisition date bands to each image in the image collection
#==================================================================================================
scored_ImgColl = masked_img_coll.map(lambda img: attach_Hybrid_score(img, midDate, SsrData, rescaled_refer_mosaic, water_map)) \
.map(lambda img: Img.attach_Date(img))
#==================================================================================================
# Attach an additional bands as necessary to each image in the image collection
#==================================================================================================
extra_code = int(ExtraBandCode)
if extra_code == Img.EXTRA_ANGLE:
scored_ImgColl = scored_ImgColl.map(lambda image: Img.attach_AngleBands(image, SsrData))
elif extra_code == Img.EXTRA_NDVI:
scored_ImgColl = scored_ImgColl.map(lambda image: Img.attach_NDVIBand(image, SsrData))
# Return scored image collection
#print('<score_collection> numb of images = ', scored_ImgColl.size().getInfo())
#print('<score_collection> band names of 1st scored image = ', scored_ImgColl.first().bandNames().getInfo())
return scored_ImgColl
######################################################################################################
# Description: This function creates a mosaic image from a given image collection based on MaxNBR.
#
# Revision history: 2020-Dec-22 Lixin Sun Initial creation
#
######################################################################################################
def coll_MaxNBR_mosaic(maskedImgColl, SsrData):
'''Create a mosaic image from a given image collection based on MaxNBR.
Args:
inMaskedImgColl(ee.ImageCollection): A given image collection with cloud/shadow masks applied;
SsrData(Dictionary): A Dictionary containing metadata associated with a sensor and data unit.
'''
#==================================================================================================
# Create a scored image collection (attach a score image for each image in the given collection)
#==================================================================================================
scored_ImgColl = maskedImgColl.map(lambda img: attach_MaxNBR_score(img, SsrData))
#==================================================================================================
# Create and return a mosaic based on associated score maps
#==================================================================================================
return scored_ImgColl.qualityMosaic(Img.pix_score) #.set('system:time_start', midDate.millis())
######################################################################################################
# Description: This function creates a mosaic image from a given image collection based on MaxNDVI.
#
# Note: This MaxNDVI-based TIC method cannot be used as an independent method since it uses
# rescaled values for all spectral bands.
#
# Revision history: 2020-Dec-22 Lixin Sun Initial creation
#
######################################################################################################
def coll_MaxNDVI_mosaic(maskedImgColl, SsrData):
'''Create a mosaic image from a given image collection based on MaxNDVI.
Args:
maskedImgColl(ee.ImageCollection): A given image collection with cloud/shadow masks applied;
SsrData(Dictionary): A sensor info dictionary. '''
#==================================================================================================
# Create a scored image collection (attach a score image for each image in the given collection)
#==================================================================================================
scored_ImgColl = maskedImgColl.map(lambda img: attach_MaxNDVI_score(img, SsrData))
#==================================================================================================
# Create and return a mosaic based on associated score maps
#==================================================================================================
return scored_ImgColl.qualityMosaic(Img.pix_score) #.set('system:time_start', midDate.millis())
######################################################################################################
# Description: This function creates a mosaic image based on a given image collection.
#
# Revision history: 2020-Dec-22 Lixin Sun Initial creation
#
######################################################################################################
def coll_Hybrid_mosaic(inImgColl, SsrData, StartD, StopD, ExtraBandCode, CS_plus):
'''Create a mosaic image based on a given image collection.
Args:
inImgColl(ee.ImageCollection): A given image collection;
SsrData(Dictionary): A Dictionary containing metadata associated with a sensor and data unit;
StartD(ee.Date): The beginning date of a compositing time period;
StopD(ee.Date): The ending date of a compositing time period;
ExtraBandCode(int): The integer code representing the band type to be added additionally;
CS_plus(Boolean): A flag indicating if to apply CloudScore+ mask to image collection.'''
#==================================================================================================
# Create a historical median mosaic image
#==================================================================================================
'''
med_start, med_stop = IS.time_range(midDate, 31) # Determine the start and stop dates of a month
if ssr_code < Img.MAX_LS_CODE:
hist_median = median_refer_LS_SR(SsrData['GEE_NAME'], Region, med_start, med_stop, 2019, 2023)
elif ssr_code >= Img.MAX_LS_CODE and ssr_code < Img.MOD_sensor:
hist_median = median_refer_S2_SR(SsrData['GEE_NAME'], Region, med_start, med_stop, 2019, 2023)
else:
hist_median = median_refer_HLS_SR(SsrData['GEE_NAME'], Region, med_start, med_stop, 2019, 2023)
#print('<coll_mosaic> Bands in historical median image:', hist_median.bandNames().getInfo())
hist_median = hist_median.select([SsrData['BLU'], SsrData['GRN'], SsrData['RED'], SsrData['NIR'],SsrData['SW1'], SsrData['SW2']]) \
.rename(['blue', 'green', 'red', 'nir', 'swir1', 'swir2'])
median_SR_refer = get_refer_mosaic(masked_ImgColl, SsrData, Start, Stop)
median = median_SR_refer.unmask(hist_median)
median = Img.apply_gain_offset(median, SsrData, 100, False)
'''
#==================================================================================================
# Apply default (OR CloudScore) masks to each image in the given collection
#==================================================================================================
masked_ImgColl = IS.mask_collection(inImgColl, SsrData, CS_plus)
#print('<coll_mosaic> Bands in the first masked image:', masked_ImgColl.first().bandNames().getInfo())
#==================================================================================================
# Create a reference mosaic image
#==================================================================================================
refer_mosaic = get_refer_mosaic(masked_ImgColl, SsrData, StartD, StopD)
#print('<coll_mosaic> Bands in refer median image:', refer_mosaic.bandNames().getInfo())
#==================================================================================================
# Create a scored image collection (attach a score image for each image in the given collection)
#==================================================================================================
midDate = IS.period_centre(StartD, StopD) # Determine the central date of a time window
scored_collection = score_collection(masked_ImgColl, SsrData, midDate, ExtraBandCode, CS_plus, refer_mosaic)
#==================================================================================================
# Create and return a mosaic based on associated score maps
#==================================================================================================
return scored_collection.qualityMosaic(Img.pix_score) #.set('system:time_start', midDate.millis())
#############################################################################################################
# Description: This function creates a median reference mosaic using historical Landsat-8 images acquired
# within specified time window and spatial region.
#
# Revision history: 2023-Dec-02 Lixin Sun initial creation
#
#############################################################################################################
def median_refer_HLS_SR(CollName, inRegion, StartData, StopData, StartYear, StopYear):
def one_year_median(inYear):
start = ee.Date(StartData).update(inYear)
stop = ee.Date(StopData).update(inYear)
img_coll = ee.ImageCollection(CollName).filterBounds(inRegion).filterDate(start, stop)
masked_coll = img_coll.map(lambda img: img.updateMask(IM.HLS_ClearMask(img).Not()))
return masked_coll.median()
median_coll = ee.List.sequence(StartYear, StopYear).map(lambda x: one_year_median(x))
median = ee.ImageCollection(median_coll).median()
#print(median.bandNames().getInfo())
return median
#############################################################################################################
# Description: Creates a mosaic image specially for vegetation parameter extraction with LEAF tool.
#
# Note: (1) The major difference between a mosaic image for LEAF tool and that for general purpose
# is the attachment of three imaging geometrical angle bands.
# (2) For Landsat and Sentinel-2 data, the Value range of returned mosaic will depend on which
# algorithm will be apllied for extracting biophysical parameetrs. If SL2P is applied,
# then the value range must be within [0, 1], if RF model is applied, then just keep
# original value range.
#
# Revision history: 2021-May-19 Lixin Sun Initial creation
# 2022-Jan-14 Lixin Sun Modified so that every value in "fun_Param_dict" dictionary
# is a single value.
# 2023-Sep-07 Lixin Sun Added the third input parameetr to indicate if SL2P algorithm
# will be applied.
#############################################################################################################
def LEAF_Mosaic(inSsrData, region, inStart, inStop, SL2P_algo):
'''Creates a mosaic image specially for vegetation parameter extraction with LEAF tool.
Args:
inSsrData(Dictionary): a dictionary containing various info about a sensor;
region(ee.Geometry): the spatial region of a mosaic image;
inStart(string or ee.Date): The start date of a time period;
inStop(string or ee.Date): The stop date of a time period;
SL2P_algo(Boolean): a flag indicating if SL2P algorithm will be applied.'''
#==========================================================================================================
# Create a mosaic image including imaging geometry angles required by vegetation parameter extraction.
# Note: (1) the mosaic pixel value range required by SL2P algorithm must be within [0, 1]. If Random Forest
# model is used for Landsat data, then original value range is OK.
# (2) Generating pixel masks using CloudScore could sometimes cause problem. So the last parameter
# for "HomoPeriodMosaic" function should be "False" for now (Feb. 10, 2024)
#==========================================================================================================
ssr_code = inSsrData['SSR_CODE']
year = ee.Date(inStart).get('year').getInfo()
mosaic = HomoPeriodMosaic(inSsrData, region, year, -1, inStart, inStop, Img.EXTRA_ANGLE, False)
if (ssr_code < Img.MAX_LS_CODE and SL2P_algo == True) or (ssr_code >= Img.MAX_LS_CODE and ssr_code < Img.MOD_sensor):
# The value range for applying SL2P algorithm must be within 0 and 1
mosaic = Img.apply_gain_offset(mosaic, inSsrData, 1, False)
return mosaic
######################################################################################################
# Description: This function merges two mosaics created from the images acquired with different
# Landsat sensors.
#
# Note: When merging a Sentinel-2 mosaic with a Landsat mosaic, the Sentinel-2 mosaic must be
# used as the base mosaic and the Landsat mosaic is used to fill the gaps in base mosaic.
#
# Revision history: 2022-May-02 Lixin Sun Initial creation
# 2022-Oct-20 Lixin Sun Modified so that this function is not only applicable for
# merging two Landsat mosaics, but also for merging a
# Sentinel-2 mosaic with a Landsat mosaic.
######################################################################################################
def MergeMosaics(MosaicBase, MosaicBkUp, SensorBase, SensorBkUp, ScroeThresh):
'''Merge the mosaics created from the images acquired with different Landsat sensors.
Args:
MosaicBase(ee.Image): The mosaic that will be used as a base/main one;
MosaicBkUp(ee.Image): The mosaic that will be used to fill the gaps in the base mosaic;
SensorBase(Dictionary): The sensor info dictionary of the base/main mosaic;
SensorBkUp(Dictionary): The sensor info dictionary of the 2nd mosaic to fill the gaps in base mosaic;\
ScroeThresh(float): A given score threshold.'''
#===================================================================================================
# Refresh the masks for both given mosaic images
#===================================================================================================
mosaic_base = ee.Image(MosaicBase)
mosaic_bkup = ee.Image(MosaicBkUp)
#===================================================================================================
# Fill the gaps in base mosaic with the valid pixels in the 2nd mosaic
#===================================================================================================
ssr_code_base = SensorBase['SSR_CODE']
ssr_code_bkup = SensorBkUp['SSR_CODE']
if (ssr_code_base > Img.MAX_LS_CODE and ssr_code_bkup < Img.MAX_LS_CODE) or \
(ssr_code_base < Img.MAX_LS_CODE and ssr_code_bkup > Img.MAX_LS_CODE):
#In the case of the base and backup mosaics are acquired from Sentinel-2 and Landsat
bands_more = [Img.pix_score, Img.pix_date, Img.mosaic_ssr_code]
bands_base = SensorBase['SIX_BANDS'] + bands_more
bands_bkup = SensorBkUp['SIX_BANDS'] + bands_more
bands_final = Img.STD_6_BANDS + bands_more
#print('<MergeMosaics> Bands_base:', bands_base)
#print('<MergeMosaics> Bands_bkup:', bands_bkup)
#print('<MergeMosaics> Bands_final:', bands_final)
mosaic_base = mosaic_base.select(bands_base).rename(bands_final) #.selfMask()
mosaic_bkup = mosaic_bkup.select(bands_bkup).rename(bands_final) #.selfMask()
#print('\n\n<MergeMosaics> Bands in base mosaic = ', mosaic_base.bandNames().getInfo())
#rint('<MergeMosaics> Bands in 2nd mosaic = ', mosaic_bkup.bandNames().getInfo())
#===================================================================================================
# Fill the gaps in base mosaic with the pixels from backup mosaic
#===================================================================================================
mosaic_base = mosaic_base.unmask(mosaic_bkup)
#===================================================================================================
# Overwrite the pixels in base mosaic with the better pixels from backup mosaic
#===================================================================================================
base_score = mosaic_base.select([Img.pix_score])
bkup_score = mosaic_bkup.select([Img.pix_score]).subtract(float(ScroeThresh))
return ee.Image(mosaic_base.where(bkup_score.gt(base_score), mosaic_bkup))
###################################################################################################
# Description: This function creates a mosaic image for a predefined region using the images
# acquired by nominal identical sensors, such as Landsat 8/9 and Sentinel-2 A/B, over
# a time period.
#
# Revision history: 2021-Jun-02 Lixin Sun Initial creation
# 2021-Oct-05 Lixin Sun Added an output option
###################################################################################################
def HomoPeriodMosaic(SsrData, Region, TargetY, NbYs, StartD, StopD, ExtraBandCode, CS_plus):
'''Creates a mosaic image for a region using the images acquired during a period of time.
Args:
SsrData(Dictionary): A Dictionary containing metadata associated with a sensor and data unit;
Region(ee.Geometry): The spatial polygon of a ROI;
TargetY(int): A targeted year (must be an integer);
NbYs(int): The number of years
StartD(ee.Date or string): The start Date (e.g., '2020-06-01');
StopD(ee.Date or string): The stop date (e.g., '2020-06-30');
ExtraBandCode(int): A integr code representing band type be attached additionally;
CS_plus(Boolean): A flag indicating if to apply CloudScore+ mask.'''
# Cast some input parameters
nb_years = int(NbYs)
ssr_code = SsrData['SSR_CODE']
#==========================================================================================================
# Get a mosaic image corresponding to a given time window in a targeted year
#==========================================================================================================
start = ee.Date(StartD).update(TargetY)
stop = ee.Date(StopD).update(TargetY)
# Generate an image collection and then apply masks to each image in the collection
ImgColl_target = IS.getCollection(SsrData, Region, start, stop, ExtraBandCode)
#masked_ImgColl_target = IS.mask_collection(ImgColl_target, SsrData, CS_plus)
mosaic_target = coll_Hybrid_mosaic(ImgColl_target, SsrData, start, stop, ExtraBandCode, CS_plus)
#print('bands in mosaic = ', mosaic_target.bandNames().getInfo())
if nb_years <= 1:
ssr_code_img = mosaic_target.select([0]).multiply(0).add(ssr_code).rename([Img.mosaic_ssr_code])
return mosaic_target.addBands(ssr_code_img)
elif nb_years == 2:
# Create a mosaic image for the year before the target
PrevYear = TargetY - 1
start = start.update(PrevYear)
stop = stop.update(PrevYear)
# Prepare an image collection and then apply masks to each image in the collection
ImgColl_before = IS.getCollection(SsrData, Region, start, stop, ExtraBandCode)
#masked_ImgColl_before = IS.mask_collection(ImgColl_before, SsrData, CS_plus)
mosaic_before = coll_Hybrid_mosaic(ImgColl_before, SsrData, start, stop, ExtraBandCode, CS_plus)
# Merge the two mosaic images into one and return it
mosaic = MergeMosaics(mosaic_target, mosaic_before, SsrData, SsrData, 3.0)
return mosaic.addBands(ssr_code_img)
else:
# Create mosaic image for the year after the target
AfterYear = TargetY + 1
start = start.update(AfterYear)
stop = stop.update(AfterYear)
# Prepare an image collection and then apply masks to each image in the collection
ImgColl_after = IS.getCollection(SsrData, Region, start, stop, ExtraBandCode)
#masked_ImgColl_after = IS.mask_collection(ImgColl_after, SsrData, CS_plus)
mosaic_after = coll_Hybrid_mosaic(ImgColl_after, SsrData, start, stop, ExtraBandCode, CS_plus)
mosaic = MergeMosaics(mosaic_target, mosaic_after, SsrData, SsrData, 3.0)
# Create mosaic image for the year before the target
PrevYear = TargetY - 1
start = start.update(PrevYear)
stop = stop.update(PrevYear)
# Prepare an image collection and then apply masks to each image in the collection
ImgColl_before = IS.getCollection(SsrData, Region, start, stop, ExtraBandCode)
#masked_ImgColl_before = IS.mask_collection(ImgColl_before, SsrData, CS_plus)
mosaic_before = coll_Hybrid_mosaic(ImgColl_before, SsrData, start, stop, ExtraBandCode, CS_plus)
mosaic = MergeMosaics(mosaic, mosaic_before, SsrData, SsrData, 3.0)
return mosaic.addBands(ssr_code_img)
###################################################################################################
# Description: This function returns a primary or secondary landsat sensor code based on a given
# year.
#
# Note: Landsat data for Canada north is not available before 2004.
#
# Revision history: 2023-Mar-08 Lixin Sun Initial creation
#
###################################################################################################
def LS_code_from_year(Year, prim_2nd_code):
'''Returns a primary or secondary landsat sensor code based on a given year.
Args:
Year(int): A specified target year (must be a regular integer);
prim_2nd_code: An integer indicating the returned Landsat sensor code is for primary or secondary
1 => primary; 2 => secondary.'''
year = int(Year)
if prim_2nd_code == 1:
return 5 if year < 2013 else 8
else:
return 7 if year < 2022 else 9
###################################################################################################
# Description: This function returns a primary or secondary landsat sensor meta dictionary based on
# a given year.
#
# Revision history: 2023-Mar-08 Lixin Sun Initial creation
#
###################################################################################################
def LS_Dict_from_year(Year, Unit, prim_2nd_code):
'''Returns a primary or secondary landsat sensor code based on a given year.
Args:
Year(int): A specified target year (must be a regular integer);
Unit(int): An integer representing data unit (1 => TOA or 2 => surface reflectance);
prim_2nd_code: An integer indicating the returned Landsat sensor code is for primary or secondary
1 => primary; 2 => secondary.'''
year = int(Year)
unit = int(Unit)
ssr_code = LS_code_from_year(year, prim_2nd_code)
unit_str = '_SR' if unit > 1 else '_TOA'
ssr_str = 'L' + str(ssr_code) + unit_str
return Img.SSR_META_DICT[ssr_str]
###################################################################################################
# Description: This function creates a mosaic image for a specified region using all the LANDSAT
# images acquired during a period of time.
#
# Revision history: 2022-May-02 Lixin Sun Initial creation
#
###################################################################################################
def LSMix_PeriodMosaic(SsrData, Region, Year, StartDate, StopDate, ExtraBandCode, CS_plus):
'''Creates a mosaic image for a region using the images acquired during a period of time.
Args:
DataUnit(int): Data unit code integer. 1 and 2 represent TOA and surface reflectance, respectively;
Region(ee.Geometry): The spatial polygon of a ROI;
Year(int): A specified target year (must be a regular integer);
Startdate(ee.Date or string): The start date string (e.g., '2020-06-01') or ee.Date object;
StopDate(ee.Date or string): The end date string (e.g., '2020-06-30') or ee.Date object;
ExtraBandCode(int): A integer code representing band type to be attached additionaly;
CS_plus(Boolean): A flag indicating if to apply CloudScore+ mask.'''
#================================================================================================
# Determine a proper time period based on a given target year and an initial period
#================================================================================================
year = int(Year)
start = ee.Date(StartDate).update(Year)
stop = ee.Date(StopDate).update(Year)
unit = SsrData['DATA_UNIT']
#================================================================================================
# Create a base Landsat mosaic image
#================================================================================================
ssr_main = LS_Dict_from_year(Year, unit, 1)
mosaic_main = coll_Hybrid_mosaic(ssr_main, Region, start, stop, ExtraBandCode, CS_plus)
#print('\n\n<LSMix_PeriodMosaic> bands in main mosaic = ', mosaic_main.bandNames().getInfo())
#================================================================================================
# Create a secondary Landsat mosaic image
#================================================================================================
ssr_2nd = LS_Dict_from_year(Year, unit, 2)
mosaic_2nd = coll_Hybrid_mosaic(ssr_2nd, Region, start, stop, ExtraBandCode, CS_plus)
#print('\n\n<LSMix_PeriodMosaic> sensor info of the 2nd sensor = ', ssr_2nd)
#print('\n<LSMix_PeriodMosaic> size of 2nd img coll = ', img_coll_2nd.size().getInfo())
#================================================================================================
# Deal with the case when Landsat 7 needs to be merged with Landsat 8 data
#================================================================================================
ssr_main_code = LS_code_from_year(year, 1)
ssr_2nd_code = LS_code_from_year(year, 2)
print('\n\n<LSMix_PeriodMosaic> sensor code1 and code2 for year = ', ssr_main_code, ssr_2nd_code, year)
if ssr_main_code == Img.LS8_sensor and ssr_2nd_code == Img.LS7_sensor:
temp_ls7_mosaic = mosaic_2nd.select(['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B7']) \
.rename(['SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7'])
ls7_mosaic = mosaic_2nd.select(['SR_B1']).addBands(temp_ls7_mosaic)
# Add rest other bands
if ExtraBandCode == Img.EXTRA_ANGLE:
mosaic_main = mosaic_main.select(['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7', 'cosVZA', 'cosSZA', 'cosRAA', Img.pix_score, Img.pix_date])
rest_bands = ['cosVZA', 'cosSZA', 'cosRAA', Img.pix_score, Img.pix_date]
elif ExtraBandCode == Img.EXTRA_NDVI:
mosaic_main = mosaic_main.select(['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7', Img.pix_date, Img.PARAM_NDVI, Img.pix_score])
rest_bands = [Img.pix_date, Img.PARAM_NDVI, Img.pix_score]
else:
mosaic_main = mosaic_main.select(['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B6', 'SR_B7', Img.pix_date, Img.pix_score])
rest_bands = [Img.pix_date, Img.pix_score]
ls7_mosaic = ls7_mosaic.addBands(mosaic_2nd.select(rest_bands))
test_ls7_mosaic = ls7_mosaic.focal_mean(1, 'circle', 'pixels', 2)
mosaic_2nd = ls7_mosaic.unmask(test_ls7_mosaic)
# Added this line so that, when the 2nd image collection is empty (LS7 does not image in northen Canada),
# program still work properly.
mosaic_2nd = ee.Algorithms.If(img_coll_2nd.size().gt(0), mosaic_2nd, mosaic_main)
mosaic_2nd = ee.Image(mosaic_2nd)
#================================================================================================
# Attach sensor codes to base and backup mosaic, respectively
#================================================================================================
ssr_code_base_img = ee.Image.constant(ssr_main_code).rename([Img.mosaic_ssr_code]).updateMask(mosaic_main.mask().select(0))
ssr_code_2nd_img = ee.Image.constant(ssr_2nd_code).rename([Img.mosaic_ssr_code]).updateMask(mosaic_2nd.mask().select(0))
mosaic_main = mosaic_main.addBands(ssr_code_base_img)
mosaic_2nd = mosaic_2nd.addBands(ssr_code_2nd_img)
return MergeMosaics(mosaic_main, mosaic_2nd, ssr_main, ssr_2nd, 2.0)
###################################################################################################
# Description: This function extracts FOUR (VZA, VAA, SZA and SAA) geometry angle bands from a
# Landsat TOA reflectance image and then attach them to a Landsat surface reflectance
# image.
#
# Note: This function is specifically developed for LEAF production with Landsat images.