# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# Source: [Tutorial](https://worldbank.github.io/OpenNightLights/tutorials/mod6_3_intro_to_sentinel2.html)
#
# [sentinel-2](https://sentinel.esa.int/web/sentinel/missions/sentinel-2)
#
# [(GEE) collection’s landing pages](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2) -- more details
#

# #### Intro
#
# ##### Sentinel-2 satellites
# * hi-resolution imagery provided by the MultiSpectral Instrument (MSI), useful for land use monitoring
# * * part of European Space Agency’s (ESA) Copernicus system
#
# * several image bands across the *optical* electromagnetic spectrum, useful  for classifying land use, particular that of built-up areas.
#
# * * For visualization: just RGB channels

# reminder that if you are installing libraries in a Google Colab instance you will be prompted to restart your kernal
import geemap, ee
import os

# +
ee.Initialize()

# get our admin boundary
aoi = ee.FeatureCollection("FAO/GAUL/2015/level0").filter(ee.Filter.eq('ADM0_NAME','Ireland')).geometry()

# Sentinel-2 image filtered on 2019 and on Ireland
se2 = ee.ImageCollection('COPERNICUS/S2').filterDate("2019-01-01","2019-12-31").filterBounds(aoi).median().divide(10000)

# channels
rgb = ['B4','B3','B2']

# set some thresholds
rgbViz = {"min":0.0, "max":0.3,"bands":rgb}

# +
# initialize our map
map1 = geemap.Map()
map1.centerObject(aoi, 7)
map1.addLayer(se2.clip(aoi), rgbViz, "S2")

map1.addLayerControl()
map1  # display in notebook


# -

# ![Ireland - cloud cover](./img/IRL_clouds.png)

# Issue: It appears we’ve also captured some clouds. 
#
# Solution: We will make a cloud mask to clear the image up using Sentinel-2’s QA band. We’re modeling this (in Python) from the [example used in GEE](https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S2#bands)
# * Name: `QA60`
# * * Description: Cloud Mask

def se2mask(image):
    quality_band = image.select('QA60')
    
    # using the bit mask for clouds, incl cirrus clouds
    cloudmask = 1 << 10
    cirrusmask = 1 << 11
    
    # only clear skies
    mask = quality_band.bitwiseAnd(cloudmask).eq(0) and (quality_band.bitwiseAnd(cirrusmask).eq(0))
    
    # divide by 10000 to make interpreting reflectance values easier
    return image.updateMask(mask).divide(10000)
    


# +
se2 = ee.ImageCollection('COPERNICUS/S2').filterDate(
    "2019-01-01","2019-12-31").filterBounds(aoi).filter(
    ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE",20)).map(se2mask).median()

# initialize our map
map2 = geemap.Map()
map2.centerObject(aoi, 7)
map2.addLayer(se2.clip(aoi), rgbViz, "S2")

map2.addLayerControl()
map2
# -

# ![Ireland - cloud free](./img/IRL_cloud-free.png)

StarcoderdataJupyterScriptsDedupFiltered