<jupyter_start><jupyter_text>Sentinel-2 * **Products used:** [s2_l2a](https://explorer.digitalearth.africa/s2_l2a)Notebook copied from https://github.com/digitalearthafrica/deafrica-sandbox-notebooks  BackgroundSentinel-2 is an Earth observation mission from the EU Copernicus Programme that systematically acquires optical imagery at high spatial resolution (up to 10 m for some bands).The mission is based on a constellation of two identical satellites in the same orbit, 180° apart for optimal coverage and data delivery.Together, they cover all Earth's land surfaces, large islands, inland and coastal waters every 3-5 days.Sentinel-2A was launched on 23 June 2015 and Sentinel-2B followed on 7 March 2017.Both of the Sentinel-2 satellites carry an innovative wide swath high-resolution multispectral imager with 13 spectral bands.For more information on the Sentinel-2 platforms and applications, check out the [European Space Agency website](http://www.esa.int/Applications/Observing_the_Earth/Copernicus/Overview4).Digital Earth Africa (DE Africa) provides [Sentinel-2, Level 2A](https://earth.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-2a-processing) surface reflectance data provided by ESA.Surface reflectance provides standardised optical datasets by using robust physical models to correct for variations in image radiance values due to atmospheric properties, as well as sun and sensor geometry.The resulting stack of surface reflectance grids are consistent over space and time, which is instrumental in identifying and quantifying environmental change.DE Africa provides one Sentinel-2 surface reflectance product:* **Sentinel-2** (i.e. `"s2_l2a"`): This product represents the 'definitive' source of high quality, analysis-ready Sentinel-2 surface reflectance data (Level 2A), and is available from 2017 to present. Sentinel-2A and Sentinel-2B satellite sensors are stored together under a single product name. Sentinel-2, Level 2A surface reflectance products have 13 spectral channels and one pixel quality band ([SCL](https://earth.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-2a/algorithm)):| Sentinel-2 bands | DE Africa band name | Band number | Central wavelength (nm) | Resolution (m) | Bandwidth (nm) || -----------------|---------------|-------------|-------------------------|----------------|----------------|| Coastal aerosol | `coastal_aerosol` | 1 | 443 | 60 | 20 || Blue | `blue` | 2 | 490 | 10 | 65 || Green | `green` | 3 | 560 | 10 | 35 || Red | `red` | 4 | 665 | 10 | 30 || Vegetation red edge | `red_edge_1` | 5 | 705 | 20 | 15 || Vegetation red edge | `red_edge_2` | 6 | 740 | 20 | 15 || Vegetation red edge | `red_edge_3` | 7 | 783 | 20 | 20 || NIR | `nir_1`, `nir` | 8 | 842 | 10 | 115 || Narrow NIR | `nir_2`,`nir_narrow` | 8A | 865 | 20 | 20 || Water vapour | `water_vapour` | 9 | 945 | 60 | 20 || SWIR | `swir_1`, `swir_16` | 11 | 1610 | 20 | 90 || SWIR | `swir_2`, `swir_22` | 12 | 2190 | 20 | 180 || SCL  | `SCL`, `qa`, `mask`    | 13 | N/A | 20| AOT  | `aerosol_optical_thickness` | N/A | N/A | 60These bands cover the visible, near-infrared and short-wave infrared wavelengths.!['Sentinel-2 spectral bands'](http://www.geosage.com/highview/figures/Sentinel2_Spectral_Bands.jpg)***  Important details**Product details:*** Product name in the datacube: `"s2_l2a"`* Surface reflectance product (Level 2A)    * Valid SR scaling range: `1 – 10,000 (0 is no-data)`* Spatial resolution: varies, see above table* [SCL](https://earth.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-2a/algorithm) used as pixel quality band* Universal Transverse Mercator (UTM) map projection. World Geodetic System (WGS) 84 datum* Stored in Cloud-Optimised GeoTIFF Format (COG)**Status:** DE Africa's Sentinel-2 data is processed to Level 2A using the [Sen2Cor](https://step.esa.int/main/third-party-plugins-2/sen2cor/) algorithm, stored as Cloud-Optimised Geotiffs, and is available over the entire African Continent. Sentinel-2A and Sentinel-2B satellite sensors are stored together under a single product name (`"s2_l2a"`). The catalogue is regularly updated to keep pace with new satellite passes.**Date-range**: 2017 to Present**Minimum loading requirements:**```data = dc.load(product='s2_l2a',               output_crs='epsg:6933',               resolution=(-20, 20),               **query)```                               **Bands:**```coastal_aerosolblue           green           redred_edge_1red_edge_2red_edge_3nir_1nir_2swir_1            swir_2water_vapourSCL        AOT```***  DescriptionThis notebook will run through loading in Sentinel-2 satellite images.Topics covered include:* Using the native `dc.load()` function to load in Sentinel-2 data* Using the `load_ard()` wrapper function to load in a cloud and pixel-quality masked time series***  Getting startedTo run this analysis, run all the cells in the notebook, starting with the "Load packages" cell.  Load packages<jupyter_code>import sys
import datacube
import os

import numpy as np
import xarray as xr

#from utils.deafrica_datahandling import load_ard
#from utils.deafrica_plotting import rgb

sys.path.insert(1, './Tools/')
from dea_tools.datahandling import load_ard
from dea_tools.plotting import rgb, display_map
from dea_tools.bandindices import calculate_indices
from dea_tools.dask import create_local_dask_cluster


client = create_local_dask_cluster(return_client=True)<jupyter_output><empty_output><jupyter_text>Connect to the datacube<jupyter_code>dc = datacube.Datacube(app='Sentinel_2')<jupyter_output><empty_output><jupyter_text>Load Sentinel-2 data from the datacubeWe will load **Sentinel-2** data using two methods.Firstly, we will use [dc.load()](../Beginners_guide/03_Loading_data.ipynb) to return a time series of satellite images.Secondly, we will load a time series using the [load_ard()](../Frequently_used_code/Using_load_ard.ipynb) function, which is a wrapper function around the `dc.load` module.This function will load all the images from Sentinel-2 and then apply a cloud/pixel-quality mask.The returned `xarray.Dataset` will contain analysis ready images with the cloudy and invalid pixels masked out.You can change any of the parameters in the `query` object below to adjust the location, time, projection, or spatial resolution of the returned datasets.To learn more about querying, refer to the Beginner's guide notebook on [loading data](../Beginners_guide/03_Loading_data.ipynb).Sentinel-2 data is stored on file with a range of different coordinate reference systems or CRS (i.e. multiple UTM zones). The different satellite bands also have different resolutions (10 m, 20 m and 60 m). Because of this, all Sentinel-2 queries need to include the following two query parameters:* `output_crs`: This sets a consistent CRS that all Sentinel-2 data will be reprojected to, regardless of the UTM zone the individual image is stored in.* `resolution`: This sets the resolution that all Sentinel-2 images will be resampled to. > **Note:** Be aware that setting `resolution` to the highest available resolution (i.e. `(-10, 10)`) will downsample the coarser resolution 20 m and 60 m bands, which may introduce unintended artefacts into your analysis.It is typically best practice to set `resolution` to match the lowest resolution band being analysed. For example, if your analysis uses both 10 m and 20 m resolution bands, set `"resolution": (-20, 20)`.<jupyter_code># Create a query object
lat, lon = 29.74200601924699, -95.01318793365394

# Giga Texas
lat, lon = 30.22208235050694, -97.61701004390453
buffer = 0.02

query = {
    'time': ('2020-07-01', '2021-12-01'),
    'x': (lon - buffer, lon + buffer),
    'y': (lat + buffer, lat - buffer),
    'output_crs': 'epsg:3081',
    'resolution':(-10,10),
}<jupyter_output><empty_output><jupyter_text>Load Sentinel-2 using `dc.load()`The **Sentinel-2** product is called:* `s2_l2a`And contains images from both Sentinel-2 sensors, S2A and S2BWe will now load in a time-series of satellite images from only Sentinel-2> **Note:** In this example, we include the `dask_chunks={}` parameter in order to "lazy-load" the data. The returned array will contain information about the data without directly loading it, which saves time in this instance. For more information on this, see the Beginner's guide notebook on [parallel processing with Dask](../Beginners_guide/06_Parallel_processing_with_dask.ipynb).<jupyter_code>#load data
ds = dc.load(product='s2_l2a',
             dask_chunks={},
             **query)

print(ds)<jupyter_output><empty_output><jupyter_text>The returned dataset contains all of the bands available for Sentinel-2. These bands are named using the datasets native band-names.  We can also specify which bands to return using band-name `aliases`, such as `red` or `nir`. We do this using the parameter `measurements`.<jupyter_code>bands = ['blue', 'green', 'red']

ds = dc.load(product='s2_l2a',
             measurements=bands,
             dask_chunks={},
             **query)

print(ds)<jupyter_output><empty_output><jupyter_text>Once the load is complete, we can then analyse or plot the Sentinel-2 data. As you can see below, clouds and regions of no-data are visible.<jupyter_code>rgb(ds, index=[1])<jupyter_output><empty_output><jupyter_text>Load Sentinel-2 using `load_ard`This function will load images from Sentinel-2 and apply a cloud/pixel-quality mask.The result is an analysis ready dataset free of cloud, cloud-shadow, and missing data.You can find more information on this function from the [Using load ard](../Frequently_used_code/Using_load_ard.ipynb) notebook.<jupyter_code>ds = load_ard(dc=dc,
              products=['s2_l2a'],
              measurements=bands,
              #min_gooddata=0.30,
              dask_chunks={},
              **query)

print(ds)
len(ds['time'])

for i in range(0,3):
    rgb(ds,bands=['red', 'green', 'blue'],index=[i])<jupyter_output><empty_output><jupyter_text>*** Additional information**License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.**Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks).**Last modified:** June 2020**Compatible datacube version:**<jupyter_code>print(datacube.__version__)<jupyter_output><empty_output><jupyter_text>TagsBrowse all available tags on the DE Africa User Guide's [Tags Index]()<jupyter_code>**Tags**: :index:`deafrica_datahandling`, :index:`deafrica_plotting`, :index:`load_ard`, :index:`rgb`, :Sentinel-2`<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11150950161348154, 'fraction_numerical': 0.03460021513087128, 'mean_word_length': 4.561814556331007, 'pattern_counts': {'":': 1, '<': 37, '<?xml version=': 0, '>': 39, 'https://': 11, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '332767', 'license': 'MIT', 'n_tokens_mistral': 3634, 'n_tokens_neox': 3252, 'n_words': 1195, 'path': 'notebooks/change_detection.ipynb', 'repo_name': 'barob1n/cube-in-a-box', 'size': '11156'}