Repository navigation
Expand file tree
/
Copy pathindex.qmd
More file actions
800 lines (663 loc) · 22.7 KB
/
Copy pathindex.qmd
File metadata and controls
800 lines (663 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
---
title: "HLS: Your new favorite remote sensing dataset"
date: "2/24/2023"
date-modified: "10/6/2024"
image: "hls.png"
fig-cap-location: top
keywords:
- NASA
- remote sensing
- Harmonized Landsat Sentinel
- STAC
- python
- cloud-native geospatial
categories:
- python
- cloud
---
The [Harmonized Landsat Sentinel 2 (HLS) dataset](https://lpdaac.usgs.gov/data/get-started-data/collection-overview/missions/harmonized-landsat-sentinel-2-hls-overview/)
is an awesome public source for 30 meter spectral satellite imagery.
::: {.column-page layout="[[1, 1], [-0.25, 0.5, -0.25]]"}



:::
Produced by NASA, the HLS dataset combines the independently powerful Landsat
8/9 and Sentinel 2 satellite observation systems into one analysis-ready
dataset.
Some of the best features include:
* More rich time series than either Sentinel 2 or Landsat individually
* one observation every two to three days from HLS compared to one every five
days for Sentinel 2 and one every eight days for Landsat 8/9
* It is
[BRDF corrected](https://en.wikipedia.org/wiki/Bidirectional_reflectance_distribution_function),
which makes mosaics generated across orbits from different days nearly seamless
* neither of the original data sources for Landsat or Sentinel data have
this feature
* The data are accessible via NASA's
[LPCLOUD STAC](https://cmr.earthdata.nasa.gov/stac/LPCLOUD)!
* Improved cloud masking for Sentinel 2!
* The original Sentinel 2 cloud mask leaves something to be desired, but
in the HLS collection you get a more robust mask that is consistent with the
Landsat products
In this post, I am going to demonstrate some of the awesome capabilities of the
HLS data and show why you should consider using it in place of either Landsat
or Sentinel 2!
Check out the
[HLS 2.0 User Guide](https://lpdaac.usgs.gov/documents/1326/HLS_User_Guide_V2.pdf)
for more details on the process for generating the HLS data.
```{python}
# | echo: false
# | eval: false
# read some tables from the HLS User Guide
import re
import camelot
tables = camelot.read_pdf(
"https://lpdaac.usgs.gov/documents/1326/HLS_User_Guide_V2.pdf", pages="6,17"
)
band_df = tables[0].df
qa_df = tables[1].df
for df in [band_df, qa_df]:
df.columns = df.iloc[0].str.replace("\n", "")
df.drop(df.index[0], inplace=True)
for col in qa_df.keys():
qa_df[col] = [re.sub("\r?\n", "", x) for x in qa_df[col]]
band_df.to_csv("/home/henry/workspace/hrodmn.dev/posts/hls/bands.csv", index=False)
qa_df.to_csv("/home/henry/workspace/hrodmn.dev/posts/hls/qa.csv", index=False)
```
## Get organized
### authentication with Earthdata and the .netrc file
To access the HLS data from NASA, you will need to have a (free) Earthdata Login
profile.
You can create an account [here](https://urs.earthdata.nasa.gov/).
Once your account is active, you will need to add your login credentials to a
`.netrc` file in your home directory.
You can do this with a single shell command in a Unix system:
```{bash}
echo "machine urs.earthdata.nasa.gov login <USERNAME> password <PASSWORD>" > ~/.netrc
```
When GDAL reads the raster data using `curl` it will find your credentials in
this file.
### environment variables
There are a handful of environment variables that must be set in order for GDAL
to locate and read the raster files correctly.
You can choose to include these in a startup script (e.g. `~/.bashrc`) or set
them within your Python script:
```{bash}
CPL_VSIL_CURL_USE_HEAD=FALSE
GDAL_DISABLE_READDIR_ON_OPEN=YES
GDAL_HTTP_COOKIEJAR=/tmp/cookies.txt
GDAL_HTTP_COOKIEFILE=/tmp/cookies.txt
```
### imports
Here are the python packages that we need:
```{python}
import datetime
import itertools
from collections import defaultdict
import pandas as pd
import pyproj
import pystac
import pystac_client
import stackstac
import xarray as xr
from rasterio.enums import Resampling
from shapely.geometry import box
from shapely.ops import transform
```
### connect to the NASA STAC
The HLS data queried from the LPCLOUD STAC.
We can use `pystac_client` to open a connection to the STAC:
```{python}
CMR_STAC_URL = "https://cmr.earthdata.nasa.gov/stac/LPCLOUD"
catalog = pystac_client.Client.open(CMR_STAC_URL)
```
The HLS data are stored in two separate collections:
* Landsat: `HLSL30_2.0`
* Sentinel: `HLSS30_2.0`
```{python}
HLS_COLLECTION_IDS = ["HLSL30_2.0", "HLSS30_2.0"]
```
There may be good reasons to keep them separate but this difference and one
other design choice that we will discuss later make it more tedious to get up
and running with the HLS data than it should!
### area of interest
For this analysis we are going to focus on a section of the Kawishiwi River
system on the edge of the Boundary Waters Canoe Area Wilderness in Northern
Minnesota that I know as "the Little Triangle".
```{python}
# my CRS of choice for CONUS these days
CRS_STRING = "epsg:5070"
EPSG = pyproj.CRS.from_string(CRS_STRING).to_epsg()
# bounding box that surrounds the Little Triangle
AOI = box(326000, 2771000, 337000, 2778000)
# STAC items store bounding box info in epsg:4326
transformer_4326 = pyproj.Transformer.from_crs(
crs_from=CRS_STRING,
crs_to="epsg:4326",
always_xy=True,
)
bbox_4326 = transform(transformer_4326.transform, AOI).bounds
```
## Explore the data
### check out this time series!
We can query the STAC catalog for the entire time series by searching the
catalog without a `datetime` specification.
```{python}
all_items = []
for collection_id in HLS_COLLECTION_IDS:
hls_history_search = catalog.search(
collections=collection_id,
bbox=bbox_4326,
)
for page in hls_history_search.pages():
all_items.extend(page.items)
collection_history = {
collection: defaultdict(list) for collection in HLS_COLLECTION_IDS
}
for item in all_items:
year_month = pd.Timestamp(item.datetime.date()) + pd.offsets.MonthEnd()
entry = collection_history[item.collection_id][year_month]
if (date := item.datetime.date()) not in entry:
entry.append(date)
```
:::{.callout-note}
I am looping through the `pages()` because the NASA STAC connection can be flaky
sometimes and will give you 502 errors when you loop through a long list of
`items()`.
I don't know why the `pages()` method is more stable, but it seems to work
better for large queries like this.
:::
```{python}
# | code-fold: true
# | column: page
# get count of images by year/month/sensor
collection_counts = pd.DataFrame(
{
collection: {
year_month: len(dates) for year_month, dates in year_months.items()
}
for collection, year_months in collection_history.items()
}
).fillna(0)
_ = collection_counts.plot.line(
title="monthly count of days with observations by sensor"
)
```
You can see that the Landsat time series stretches back to Landsat 8's launch in
2013 and that the Sentinel 2 observations kick into gear in late 2020.
The density of observations really ramped up in 2022 when Landsat 9 came online!
:::{.callout-note}
NASA is currently working on adding the full Sentinel 2 archive (back to 2015)
to the HLS dataset.
That project is scheduled to be complete in the Fall of 2023 according to
[this EarthData forum post](https://forum.earthdata.nasa.gov/viewtopic.php?t=3912)
:::
### band labels
One thing that makes it harder to get up and running with the HLS data is that
the Sentinel and Landsat STAC items have different band IDs for the many of the
spectral bands!
This matters to us here because `stackstac` uses the STAC items' asset labels
to name the `band` dimension.
Without any modifications, some of the bands would get scrambled when combining
data from the two collections.
```{python}
# | echo: false
pd.read_csv("bands.csv")
```
To avoid this headache, we can make define a crosswalk dictionary that will make
it possible to modify the STAC item metadata so that we can safely load all of
the data without scrambling the bands.
```{python}
BAND_CROSSWALK = {
"HLSL30_2.0": {
"B01": "coastal aerosol",
"B02": "blue",
"B03": "green",
"B04": "red",
"B05": "nir narrow",
"B06": "swir 1",
"B07": "swir 2",
"B09": "cirrus",
"B10": "thermal infrared 1",
"B11": "thermal",
},
"HLSS30_2.0": {
"B01": "coastal aerosol",
"B02": "blue",
"B03": "green",
"B04": "red",
"B05": "red-edge 1",
"B06": "red-edge 2",
"B07": "red-edge 3",
"B08": "nir broad",
"B8A": "nir narrow",
"B09": "water vapor",
"B10": "cirrus",
"B11": "swir 1",
"B12": "swir 2",
},
}
# these are the ones that we are going to use
BANDS = ["red", "green", "blue", "Fmask"]
```
## Make a cloud-free mosaic
### search the STAC
Now we are going to search the STAC again but this time with a `datetime`
specification to limit our search to July 2022.
```{python}
START_DATE = "2022-07-01"
END_DATE = "2022-07-31"
stac_items = catalog.search(
collections=HLS_COLLECTION_IDS,
bbox=bbox_4326,
datetime=[START_DATE, END_DATE],
).item_collection()
```
### modify the asset labels
We can use the crosswalk to rename the STAC item asset labels to pave the way
for `stackstac` to load the data in the most convenient and straightforward way.
There are ways to do this after you load the data using
`xarray.DataArray.assign_coords`, but I find the STAC item metadata alteration
approach more intuitive.
```{python}
for item in stac_items:
for original_band, new_band in BAND_CROSSWALK.get(item.collection_id).items():
item.assets[new_band] = item.assets.pop(original_band)
```
### load into a DataArray
Use `stackstac.stack` to load the STAC items into a neatly packaged
`xarray.DataArray`:
```{python}
hls_stack_raw = stackstac.stack(
stac_items,
assets=BANDS,
bounds=AOI.bounds,
epsg=EPSG,
resolution=30,
xy_coords="center",
)
```
### cloud/shadow masking
The `Fmask` band contains all of the pixel quality information that we need to
mask out invalid pixels from the images, but it takes a little bit of work.
The quality information is stored in integer form but we can work with it using
some binary tricks!
```{python}
# | echo: false
pd.read_csv("qa.csv").fillna("")
```
We can use the 'bitwise OR' operator `|` and the 'zero fill left shift' operator
`<<` to construct an integer representation of invalid pixels.
For the cloud-free mosaic, we want to exclude any pixel that is marked (bit
value = 1) as either a cloud (bit 1), adjacent to a cloud or shadow (bit 2), or a
cloud shadow (bit 3).
```{python}
hls_mask_bitfields = [1, 2, 3] # cloud shadow, adjacent to cloud shadow, cloud
hls_bitmask = 0
for field in hls_mask_bitfields:
hls_bitmask |= 1 << field
print(hls_bitmask)
```
If we cast the result to a binary string you can see how that works:
```{python}
format(hls_bitmask, "08b")
```
When you translate the integer `14` into binary you get the ultimate invalid
pixel!
Next, we use 'bitwise AND' to identify pixels that have an invalid value in any
of the bits that we care about.
Any integer value that has the invalid value (1) in any of the specified bits
(1, 2, and 3) will return a non-zero value when compared to `14` with the `&`
operator:
For example, a pixel where all bit values are zero will return zero because none
of the bitwise 1 values are shared with our invalid mask value (14 aka
00001110):
```{python}
int("00000000", 2) & 14
```
And a pixel that is marked as adjacent to a cloud or shadow (bit 2 = 1) will
return 4 (2^2) because bit 2 has 1:
```{python}
int("00000100", 2) & 14
```
Fortunately for us, we can apply the bitwise operators on integer arrays!
We can classify all pixels as either good or bad like this:
```{python}
fmask = hls_stack_raw.sel(band="Fmask").astype("uint16")
hls_bad = fmask & hls_bitmask
```
Then we can set all invalid pixels (`hls_bad != 0`) to `NaN` like this:
```{python}
# mask pixels where any one of those bits are set
hls_masked = hls_stack_raw.where(hls_bad == 0)
```
### get the cloud-free mosaic
After we have eliminated the invalid pixels it is very easy to generate a
cloud-free mosaic for a specific time range (e.g. monthly).
For example, we can take the median value from all non-cloud/non-cloud shadow
pixels within a given month with just a few lines of code.
```{python}
# | warning: false
# | message: false
hls_cloud_free = hls_masked.resample(time="1M").median(skipna=True).compute()
```
We are only looking at a single month here, but you could pass many months worth
of STAC items to `stackstac.stack` and get a rich time series of cloud-free
imagery using the exact same method.
Plot the image and bask in the cloud-free beauty:
```{python}
# | warning: false
# | message: false
# | code-fold: true
# | column: page
# | fig-align: center
# | layout: "[-0.1, 0.8, -0.1]"
_ = (
hls_cloud_free.squeeze(dim="time")
.sel(band=["red", "green", "blue"])
.plot.imshow(
rgb="band",
robust=True,
size=6,
add_labels=False,
xticks=[],
yticks=[],
)
)
```
## Compare to Sentinel 2 L2A and Landsat Collection 2 Level-2
The Landsat Collection Level-2 and Sentinel 2 Level 2A datasets are available in
Microsoft's Planetary Computer STAC.
They are available in other STACs, too (e.g.
[Element84's Earth Search Catalog](https://stacindex.org/catalogs/earth-search)),
but the Planetary Computer catalog is really nice and the data are well-
documented and have
[examples attached](https://planetarycomputer.microsoft.com/dataset/sentinel-2-l2a#Example-Notebook)
to many of the available collections.
```{python original_sentinel}
# | code-fold: true
# | warning: false
# | message: false
import planetary_computer
planetary_computer_catalog = pystac_client.Client.open(
"https://planetarycomputer.microsoft.com/api/stac/v1",
modifier=planetary_computer.sign_inplace,
)
sentinel_stac_items = planetary_computer_catalog.search(
collections=["sentinel-2-l2a"],
bbox=bbox_4326,
datetime=[START_DATE, END_DATE],
).get_all_items()
sentinel_band_crosswalk = {
"B04": "red",
"B03": "green",
"B02": "blue",
}
for item in sentinel_stac_items:
for original_band, new_band in sentinel_band_crosswalk.items():
item.assets[new_band] = item.assets.pop(original_band)
sentinel_stack = stackstac.stack(
items=sentinel_stac_items,
assets=["red", "green", "blue", "SCL"],
epsg=EPSG,
resolution=30,
bounds=AOI.bounds,
xy_coords="center",
resampling=Resampling.bilinear,
)
# valid SCL values: 4: vegetation, 5: bare soils, 6: water, 11: snow or ice
# https://docs.digitalearthafrica.org/en/latest/data_specs/Sentinel-2_Level-2A_specs.html
valid_scl = [4, 5, 6, 11]
sentinel_cloud_free = (
sentinel_stack.where(sentinel_stack.sel(band="SCL").isin(valid_scl))
.sel(band=["red", "green", "blue"])
.resample(time="1M")
.median(skipna=True)
.compute()
)
landsat_stac_items = planetary_computer_catalog.search(
collections=["landsat-c2-l2"],
bbox=bbox_4326,
datetime=[START_DATE, END_DATE],
query={"platform": {"neq": "landsat-7"}}, # skip Landsat 7 because stripes
).get_all_items()
landsat_stack = stackstac.stack(
items=landsat_stac_items,
assets=["red", "green", "blue", "qa_pixel"],
epsg=EPSG,
resolution=30,
bounds=AOI.bounds,
xy_coords="center",
band_coords=False,
)
# following https://stackstac.readthedocs.io/en/latest/examples/gif.html#Mask-cloudy-pixels-using-the-QA-band:
# Make a bitmask---when we bitwise-and it with the data, it leaves just the 4 bits we care about
mask_bitfields = [1, 2, 3, 4] # dilated cloud, cirrus, cloud, cloud shadow
bitmask = 0
for field in mask_bitfields:
bitmask |= 1 << field
landsat_qa = landsat_stack.sel(band="qa_pixel").astype("uint16")
landsat_bad = landsat_qa & bitmask # just look at those 4 bits
landsat_good = landsat_stack.where(
landsat_bad == 0
) # mask pixels where any one of those bits are set
landsat_cloud_free = (
landsat_good.sel(band=["red", "green", "blue"])
.resample(time="1M")
.median(skipna=True)
.compute()
)
```
Both of the original datasets are atmospherially corrected and represent surface
surface reflectance, but the processed images are definitely not free of cloud-
or orbit artifacts!
One of the greatest advantages of using the HLS dataset instead of the original
sources is improved cloud masking.
The HLS data undergo an entirely different process than the Landsat Collection
Level-2 and Sentinel 2 Level 2A datasets, see below for an outline of the
processing workflow.

These images show 30 meter resolution, cloud-free mosaics for July 2022 from
each source:
```{python}
# | echo: false
# | message: false
# | warning: false
# | label: fig-mosaic-comparison
# | column: page
# | layout: [[1, 1], [-0.25, 0.5, -0.25]]
# | fig-cap:
# | - "Sentinel 2"
# | - "Landsat 8/9"
# | - "Harmonized"
for stack in [sentinel_cloud_free, landsat_cloud_free, hls_cloud_free]:
_ = (
stack.squeeze(dim="time")
.sel(band=["red", "green", "blue"])
.plot.imshow(
rgb="band",
robust=True,
size=5,
add_labels=False,
xticks=[],
yticks=[],
)
)
```
In the Sentinel 2 image you can clearly see some cloud haze scattered around
most of the image.
The Landsat image shows patchy artifacts that are probably attributable to hazy
clouds that were not masked from the original images.
Meanwhile, the HLS mosaic comes out crystal clear!
## Analyze the HLS Landsat and Sentinel collections separately
To illustrate the power of the full HLS dataset and the advantage of the
high density of collections in a short time, lets load the imagery for each
sensor separately and create a cloud-free mosaic for July 2022 for each one.
### get an array for each sensor
```{python}
items_by_collection = {
collection: pystac.ItemCollection(
[item for item in stac_items if item.collection_id == collection]
)
for collection in HLS_COLLECTION_IDS
}
stacks_by_collection = {}
# a function to flatten the time dimension
def flatten(x, dim="time"):
assert isinstance(x, xr.DataArray)
if len(x[dim].values) > len(set(x[dim].values)):
x = x.groupby(dim).map(stackstac.mosaic)
return x
for collection, collection_items in items_by_collection.items():
raw_stack = stackstac.stack(
collection_items,
assets=BANDS,
bounds=AOI.bounds,
epsg=EPSG,
resolution=30,
xy_coords="center",
)
stacks_by_collection[collection] = flatten(raw_stack, dim="time")
```
We can combine them along a new dimension called `sensor` to make it easy to
look at the images with respect to sensor and time.
```{python}
sensor_stack = xr.concat(
list(stacks_by_collection.values()),
dim=pd.Index(["Landsat", "Sentinel"], name="sensor"),
)
sensor_stack
```
Since we are going to make several plots using this array, load the data into
memory with a call to the `.compute()` method.
```{python}
sensor_stack = sensor_stack.compute()
```
The HLS data are organized by 100 km MGRS tiles, and there can be redundant
coverage by separate STAC items.
We can clean this up by flattening the data out to have one observation per
sensor per day.
```{python}
# a function to prepare the arrays for better plotting
def flatten_by_day(x):
return (
x.assign_coords(time=x.time.astype("datetime64[D]"))
.groupby("time")
.map(stackstac.mosaic)
)
flattened_by_day = xr.concat(
[
flatten_by_day(sensor_stack.sel(sensor=sensor))
for sensor in ["Landsat", "Sentinel"]
],
dim="sensor",
)
```
When we plot the images we only have one observation per day per sensor.
```{python}
# | column: page
# | warning: false
# | message: false
_ = flattened_by_day.sel(band=["red", "green", "blue"]).plot.imshow(
col="sensor",
row="time",
rgb="band",
robust=True,
size=5,
vmin=0,
vmax=800,
add_labels=False,
xticks=[],
yticks=[],
)
```
Check out the valid/invalid binary values for each sensor/date:
```{python}
# | warning: false
# | message: false
# | column: page
has_data = flattened_by_day.sel(band="red").isnull() == False
fmask = flattened_by_day.sel(band="Fmask").astype("uint16")
hls_bad = (fmask & hls_bitmask).where(has_data > 0)
_ = (
(hls_bad > 0)
.where(has_data > 0)
.plot.imshow(
col="sensor",
row="time",
size=4,
add_labels=False,
xticks=[],
yticks=[],
)
)
```
For illustration purposes, make a "combined" sensor array to add to `sensor_stack`
```{python}
landsat = (
sensor_stack.sel(sensor="Landsat")
.assign_coords(sensor="combined")
.expand_dims("sensor", 1)
)
sentinel = (
sensor_stack.sel(sensor="Sentinel")
.assign_coords(sensor="combined")
.expand_dims("sensor", 1)
)
combined_stack = landsat.combine_first(sentinel)
full_stack = xr.concat([sensor_stack, combined_stack], dim="sensor")
```
Would we have at least one valid observation for every pixel?
```{python}
# | warning: false
# | message: false
# | column: page
# is there a non-na spectral observation?
has_data = full_stack.sel(band="red") > 0
# is the pixel invalid by our Fmask criteria?
fmask = full_stack.sel(band="Fmask").astype("uint16")
is_bad = fmask & hls_bitmask
# if not invalid and has non-na value it is valid
valid = (is_bad == 0).astype("float64").where(has_data > 0)
# are there any valid pixels in the time series?
has_valid = (valid > 0).any(dim="time")
_ = has_valid.plot.imshow(
col="sensor",
size=4,
add_labels=False,
vmin=0,
vmax=1,
xticks=[],
yticks=[],
)
```
Not if we only use Landsat images, not if we use only Sentinel images, but we
nearly have full coverage if we use the combined set!
```{python}
(has_valid < 1).sum(dim=["x", "y"])
```
By combining the sensors we reduce the number of pixels with no valid
observations from hundreds down to only three!
Get cloud-free mosaic for each sensor and the combined set side-by-side.
```{python}
# | warning: false
# | message: false
# | column: page
# | layout: "[-0.1, 0.8, -0.1]"
sensor_cloud_free = full_stack.where(is_bad == 0).median(dim="time", skipna=True)
_ = sensor_cloud_free.sel(band=["red", "green", "blue"]).plot.imshow(
col="sensor",
rgb="band",
robust=True,
size=4,
vmin=0,
vmax=800,
add_labels=False,
xticks=[],
yticks=[],
)
```
This demonstrates that combining the time series of observations from each of
the sensor arrays gives you superior ingredients for cloud-free mosaic products
than using either of the sensors independently.