Processing Sentinel-5P data on air pollution using Jupyter Notebook on Creodias

Nitrogen dioxide (NO₂) is an air pollutant that forms when fuel burns in vehicle engines and power plants. Breathing air with high levels of NO₂ can irritate the airways and worsen asthma symptoms.

The Sentinel-5P satellite circles Earth about every 101 minutes. On each orbit, its Tropospheric Monitoring Instrument (TROPOMI) scans the atmosphere over a different strip of Earth’s surface. The study area in this example covers all 380 Polish counties (powiaty). An overpass occurs when the strip crosses any part of that area. Most places come into view about once a day, though clouds can leave gaps in the NO₂ measurements.

For each location, TROPOMI estimates the amount of NO₂ in the column of air from the ground to the top of the troposphere. The article and its downloadable notebook use these measurements in two parts.

  • In Part 1, you find the Sentinel-5P observations over Poland in March 2023 and calculate the monthly mean for each grid cell. You save the result in mean_no2_2023_03.nc. This file uses NetCDF (Network Common Data Form), a scientific data format that stores the NO₂ values together with their units and the latitude and longitude of each cell.

  • In Part 2, you open that NetCDF file and export the grid as a GeoTIFF. You then use the county boundaries from Prerequisite No. 4 to calculate a mean NO₂ value for each county from the grid cells inside it.

Prerequisites

No. 1 Access to Horizon

Sign in to Horizon with your Creodias hosting account at https://horizon.cloudferro.com/auth/login/?next=/.

No. 2 Access to Sentinel-5P files in EODATA

When creating your Linux virtual machine (VM) in Horizon, choose a flavor in your region with at least 8 GB of RAM. Conda can run out of memory on a 4 GB VM while selecting packages for Part 2.

Choose a standard Ubuntu image and attach the VM to the eodata network. The tested Ubuntu image already mounts the archive at /eodata. You can use Jupyter from your desktop browser while the notebook runs on the VM.

The catalogue returns paths under /eodata. Mounting the remote archive at that path lets the notebook read the selected satellite files on demand. HARP is a software toolkit for processing atmospheric measurements. The notebook uses its Python interface (import harp) to open those files, filter the NO₂ measurements and calculate a monthly mean for each grid cell.

To create the VM, see How to create a Linux VM and access it from Linux command line on Creodias. If your VM image needs a manual mount, see How to mount eodata using s3fs in Linux on Creodias.

Running the notebook on your desktop

To run both parts on a Linux desktop, activate Remote Transfer for EODATA and obtain an S3 access key and secret key for that service. External transfers are billed. For activation and credentials, see Remote transfer for EODATA on Creodias.

Use either s3fs or Goofys to mount the eodata bucket at /eodata. Configure the tool with the external S3 endpoint and your Remote Transfer keys. The s3fs guide above uses the mount point this notebook expects. If you follow How to mount EODATA as a filesystem using Goofys in Linux on Creodias, use /eodata in place of the guide’s ~/eo.

To run just Part 2 on your desktop, run Part 1 on the VM first. Copy mean_no2_2023_03.nc, Sentinel5.ipynb and poland_pow.zip into one folder on your desktop. Open the notebook there with the Sentinel-5P (districts) kernel and start at Part 2. It reads the local files.

No. 3 Jupyter Notebook and Conda

You run the processing and display the maps in Jupyter. On a fresh Ubuntu VM, the setup below installs both Conda and Jupyter Notebook. You can also use an existing Jupyter installation. The VM needs internet access to download the software, query the catalogue and load the OpenStreetMap background.

To run JupyterHub on a Kubernetes cluster, see Installing JupyterHub on Magnum Kubernetes Cluster in Creodias .

Miniforge supplies the conda command. Conda installs HARP for Part 1 and the raster and vector libraries for Part 2 in separate Python environments. Each can then use the NumPy version its packages require.

No. 4 Polish county boundaries for Part 2

Download the Polish county boundaries (poland_pow.zip, 30 MiB). The ZIP contains the boundaries of all 380 counties in the study area. During setup you will place it beside the notebook on the VM. Leave it zipped for Part 2.

County boundary files, source and how to recreate the ZIP

Each record contains the outline of one county as a polygon or multipolygon. Cities with county status have their own records. The notebook averages the valid NO₂ values from grid cells whose centers fall inside each outline. It uses two attributes to identify each result by county name (JPT_NAZWA_) and four-digit administrative code (JPT_KOD_JE).

The five files in the ZIP share the name poland_pow. The .shp file holds the outlines, .shx indexes them and .dbf holds the attributes. The .prj file identifies the coordinate system (EPSG:2180) and .cpg specifies UTF-8 for Polish names.

The boundaries come from Poland’s National Register of Boundaries (GUGiK). GIS Support downloaded this snapshot on 22 December 2022. The satellite observations are from March 2023.

To recreate the supplied file, download the original Powiaty ZIP from GIS Support. Extract the five files with the extensions listed above, rename their common basename from powiaty to poland_pow, and zip those five files together as poland_pow.zip. Their contents are identical to the originals.

Prepare the notebook environment

In a terminal on the machine running the Jupyter kernel, check that you can read the Sentinel-5P collection.

ls /eodata/Sentinel-5P

Look for the TROPOMI folder in the output. Its L2__NO2___ subfolder contains the nitrogen dioxide products used in Part 1.

Terminal listing AUX and TROPOMI under /eodata/Sentinel-5P, then the product folders inside TROPOMI, including L2__NO2___.

If the directory is missing or you get a permission error, check the EODATA mount and your read access before continuing.

Install Miniforge on a fresh Ubuntu VM

In the VM terminal, run the following commands as your regular user. They download the Linux installer for the VM’s processor, install Miniforge in your home directory and make conda available in the current Bash session. If conda --version already prints a version, skip to the next step.

cd "$HOME"
curl -fL --retry 2 -o Miniforge3.sh \
  "https://github.com/conda-forge/miniforge/releases/download/26.9.4-2/Miniforge3-Linux-$(uname -m).sh" &&
  bash Miniforge3.sh -b -p "$HOME/miniforge3"
source "$HOME/miniforge3/etc/profile.d/conda.sh"
conda --version

With this installer, the last command prints conda 26.9.4.

Miniforge reports installation finished and the version check prints conda 26.9.4.

In a new Bash session, run source "$HOME/miniforge3/etc/profile.d/conda.sh" to use this installation again.

Create the two Jupyter kernels

In the same terminal, create the Part 1 environment and register its kernel. This also installs Jupyter Notebook.

conda create --yes -n s5p-harp --override-channels -c conda-forge python=3.11 harp numpy matplotlib-base cartopy cmcrameri requests ipykernel notebook &&
    conda run -n s5p-harp python -m ipykernel install --user --name s5p-harp --display-name "Sentinel-5P (HARP)"

When you see Installed kernelspec s5p-harp, create the Part 2 environment and register its kernel.

conda create --yes -n s5p-districts --override-channels -c conda-forge python=3.11 xarray netcdf4 geopandas pandas rasterio rioxarray rasterstats basemap numpy matplotlib-base ipykernel &&
    conda run -n s5p-districts python -m ipykernel install --user --name s5p-districts --display-name "Sentinel-5P (districts)"

Create the working folder on the VM

In the VM terminal, create a folder for the notebook, the county boundaries and the files the notebook produces.

mkdir -p ~/sentinel5p && cd ~/sentinel5p

Place Sentinel5.ipynb and poland_pow.zip in this folder using either of the following methods.

Download directly to the VM. On the published documentation site, right-click each file link above in your desktop browser and copy its link address. In the VM terminal, replace NOTEBOOK_URL and ZIP_URL with the respective addresses, keeping the quotes.

curl -fL --remove-on-error -o Sentinel5.ipynb 'NOTEBOOK_URL'
curl -fL --remove-on-error -o poland_pow.zip 'ZIP_URL'

Copy from your desktop. If you are reading a local preview at 127.0.0.1, that address on the VM points back to the VM itself. Save both files to ~/Downloads in your desktop browser. Leave the VM session open and open a new terminal on your desktop. Run hostname there to check that it shows your desktop’s name.

Run the following command in that desktop terminal. Replace ~/.ssh/KEY_FILE, VM_USER and VM_IP with the key path, username and address from the SSH command that connected you to the VM. If you used a floating IP address for SSH, use that same IP here. The destination :sentinel5p/ names the folder you created in the VM user’s home directory.

scp -i ~/.ssh/KEY_FILE ~/Downloads/Sentinel5.ipynb ~/Downloads/poland_pow.zip VM_USER@VM_IP:sentinel5p/
The desktop terminal shows scp reporting 100% for Sentinel5.ipynb and poland_pow.zip.

On the desktop, each file reaches 100% when its transfer finishes.

Start Jupyter on the VM and open the notebook

In the VM terminal, check that both filenames appear in the working folder.

cd ~/sentinel5p
ls -lh Sentinel5.ipynb poland_pow.zip
The VM terminal lists Sentinel5.ipynb and poland_pow.zip in ~/sentinel5p.

On the VM, both filenames appear in ~/sentinel5p.

Start Jupyter from this folder and leave the terminal open. Part 1 will save the monthly mean here so Part 2 can read it after you switch kernels.

conda run --no-capture-output -n s5p-harp jupyter notebook --no-browser --ip=127.0.0.1 --port=8888
Jupyter startup output in the VM terminal shows a browser URL beginning with http://127.0.0.1:8888/tree?token=.

Jupyter prints the address for this session. The login token is hidden in this screenshot.

In a desktop terminal, run ssh to open the tunnel to Jupyter. If you used scp to copy the files, reuse the same key path, username and VM address in the command below. The -L option connects port 8888 on your desktop to Jupyter on the VM.

ssh -i ~/.ssh/KEY_FILE -N -L 8888:127.0.0.1:8888 VM_USER@VM_IP

After ssh connects, the desktop terminal normally stays quiet because -N runs the tunnel without opening a remote shell. Leave that terminal open. Copy the http://127.0.0.1:8888/ URL, including its token, from the VM terminal into your desktop browser. The Files tab shows the contents of the VM’s working folder.

Jupyter’s Files tab lists Sentinel5.ipynb and poland_pow.zip in the VM working folder.

Sentinel5.ipynb and poland_pow.zip appear together in the Files tab.

To check which kernels are available, open New in the Files tab. Look for Sentinel-5P (HARP) and Sentinel-5P (districts).

The New menu in the Files tab lists Sentinel-5P (HARP) and Sentinel-5P (districts).

Close the menu and open Sentinel5.ipynb from the file list.

PART #1 - Download and prepare data

Open Kernel → Change Kernel. In the Select Kernel dialog, choose Sentinel-5P (HARP).

The Select Kernel dialog for Sentinel5.ipynb shows Sentinel-5P (HARP) highlighted in the list.
The open Part 1 notebook shows Sentinel-5P (HARP) highlighted at the upper right.

Check that Sentinel-5P (HARP) appears at the upper right of the notebook.

Run the cells through the first map. They use Sentinel-5P offline Level-2 nitrogen dioxide products from March 2023 to calculate a monthly mean tropospheric NO₂ vertical column density (TVCD) over Poland.

import harp
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
from cmcrameri import cm
import requests

The query uses the March 2023 dates and the fixed search polygon over Poland. The polygon selects satellite overpasses that intersect the study area. The next step places their measurements on a rectangular map grid.

catalogue_url = "https://datahub.creodias.eu/odata/v1/Products"
start = "2023-03-01"
end = "2023-03-31"
polygon = (
    "POLYGON ((13.44866 55.702105, 24.616418 55.287061, "
    "24.505406 48.582106, 13.359851 49.556626, 13.44866 55.702105))"
)
filters = [
    "Collection/Name eq 'SENTINEL-5P'",
    f"ContentDate/Start ge {start}T00:00:00.000Z",
    f"ContentDate/Start le {end}T23:59:59.999Z",
    "Online eq true",
    f"OData.CSC.Intersects(Footprint=geography'SRID=4326;{polygon}')",
    "Attributes/OData.CSC.StringAttribute/any(a:a/Name eq 'productType' and a/Value eq 'L2__NO2___')",
    "Attributes/OData.CSC.StringAttribute/any(a:a/Name eq 'processingMode' and a/Value eq 'OFFL')",
]
params = {"$filter": " and ".join(filters), "$select": "S3Path", "$top": 1000}

For these Sentinel-5P products, each S3Path already includes the NetCDF filename. Collect the paths and pass them directly to HARP.

response = requests.get(catalogue_url, params=params, timeout=60)
response.raise_for_status()
products = response.json()
path_list = [item["S3Path"] for item in products["value"]]
while products.get("@odata.nextLink"):
    response = requests.get(products["@odata.nextLink"], timeout=60)
    response.raise_for_status()
    products = response.json()
    path_list.extend(item["S3Path"] for item in products["value"])

if not path_list:
    raise ValueError("The catalogue returned no matching Sentinel-5P products.")
path_list.sort()
print(f"{len(path_list)} products. First path: {path_list[0]}")

The first path printed should start with /eodata/Sentinel-5P/ and end in .nc.

HARP filters pixels for a quality value above 0.75 and surface wind speed below 5 m/s. The bin_spatial(A,S,SR,B,W,SR) operation uses A latitude edges starting at the southern boundary and B longitude edges starting at the western boundary. The grid runs from 14°E to 25°E and 49°N to 55°N. At a spacing of 0.01 degrees, it contains 1,100 columns and 600 rows.

W, E = 14.0, 25.0
S, N = 49.0, 55.0
SR = 0.01

A = round((N - S) / SR) + 1
B = round((E - W) / SR) + 1

operations = ";".join([
    "tropospheric_NO2_column_number_density_validity>75",             # keep pixels with qa_value > 0.75
    "derive(surface_wind_speed {time} [m/s])",                        # surface wind speed in m/s
    "surface_wind_speed<5",                                           # keep wind speeds below 5 m/s
    #keep variables defined below
    "keep(latitude_bounds,longitude_bounds,datetime_start,datetime_length,tropospheric_NO2_column_number_density, surface_wind_speed)",
    "derive(datetime_start {time} [days since 2000-01-01])",          #get start time of the acquisition
    "derive(datetime_stop {time}[days since 2000-01-01])",            #get end time of the acquisition
    "exclude(datetime_length)",                                       # remove the duration
    f"bin_spatial({A},{S},{SR},{B},{W},{SR})",
    "derive(tropospheric_NO2_column_number_density [Pmolec/cm2])",    #convert the NO2 units to 10^15 molec/cm^2
    "derive(latitude {latitude})",                                    #get latitude
    "derive(longitude {longitude})",                                  #get longitude
    "count>0"
])

Combine the observations over time and calculate the mean for each grid cell.

reduce_operations=";".join([
    "squash(time, (latitude, longitude, latitude_bounds, longitude_bounds))",
    "bin()"
])
mean_no2 = harp.import_product(path_list, operations, reduce_operations=reduce_operations)

HARP reads the matching satellite files before the import cell returns. This can take several minutes without printing progress. When the cell finishes, run the export cell to save the monthly mean in the notebook folder.

harp.export_product(mean_no2, "mean_no2_2023_03.nc")

Refresh the Files tab in Jupyter to check that mean_no2_2023_03.nc appears beside the notebook and poland_pow.zip. Part 2 will reopen this file after the kernel switch.

The Jupyter Files tab lists mean_no2_2023_03.nc beside Sentinel5.ipynb and poland_pow.zip.

Use the grid edges and the units from HARP to plot the NO₂ column.

#select NO2 pollution
no2 = mean_no2.tropospheric_NO2_column_number_density.data
#select description (name) of variable
no2_description = mean_no2.tropospheric_NO2_column_number_density.description
#select units of variable
no2_units = mean_no2.tropospheric_NO2_column_number_density.unit

#define coordinate grid
gridlat = np.append(mean_no2.latitude_bounds.data[:,0], mean_no2.latitude_bounds.data[-1,1])
gridlon = np.append(mean_no2.longitude_bounds.data[:,0], mean_no2.longitude_bounds.data[-1,1])

#define legend
colortable = cm.roma_r  #colors
vmin = 0                #min value
vmax = 10               #max value

Add OpenStreetMap tiles at zoom level 8, then draw the NO₂ values over the background.

bmap = cimgt.OSM(cache=True, user_agent="CloudFerro-Sentinel5-Notebook/1.0")
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={"projection": bmap.crs})
ax.set_extent([W, E, S, N], crs=ccrs.PlateCarree())
ax.add_image(bmap, 8)

img = ax.pcolormesh(gridlon, gridlat, no2[0], vmin=vmin, vmax=vmax,
                    cmap=colortable, transform=ccrs.PlateCarree(), alpha=0.55)
ax.coastlines()
ax.text(0.99, 0.01, "© OpenStreetMap contributors", transform=ax.transAxes,
        ha="right", va="bottom", bbox={"facecolor": "white", "edgecolor": "none"})

cbar = fig.colorbar(img, ax=ax, orientation="horizontal", fraction=0.04, pad=0.1)
cbar.set_label(f"{no2_description} [{no2_units}]")
cbar.ax.tick_params(labelsize=14)
plt.show()

PART #2 - Conversion and zonal statistics

In the notebook tab you will use for Part 2, open Kernel → Change Kernel. In the Select Kernel dialog, choose Sentinel-5P (districts). Each open notebook has its own kernel selection.

The Select Kernel dialog highlights Sentinel-5P (districts).
The notebook toolbar shows Sentinel-5P (districts) at the upper right.

Check that Sentinel-5P (districts) appears at the upper right.

Start with the imports below and run the Part 2 cells in order. If the first cell reports No module named 'pandas', check that this tab shows Sentinel-5P (districts), then rerun the imports. Part 2 reads mean_no2_2023_03.nc and poland_pow.zip from the notebook folder.

import pandas as pd
import geopandas as gpd
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import rasterstats
import rasterio
import rioxarray
from rasterio.plot import show

Read the monthly mean, order the rows from north to south and write the GeoTIFF. Longitude increases from west to east. The raster uses EPSG:4326 and marks missing observations as NoData.

with xr.open_dataset("mean_no2_2023_03.nc", engine="netcdf4") as dataset:
    column = dataset["tropospheric_NO2_column_number_density"].isel(time=0).load()

# Write north-up rows and west-to-east columns, keeping coordinates with their data.
da = column.rename({"longitude": "x", "latitude": "y"}).sortby("y", ascending=False).sortby("x")
da = da.rio.write_crs("EPSG:4326").fillna(-9999).rio.write_nodata(-9999)
raster_path = "mean_no2_2023_03.tif"
da.rio.to_raster(raster_path)

with rasterio.open(raster_path) as src:
    show(src)

Calculate the mean NO₂ value for each Polish county

Read poland_pow.zip from Prerequisite No. 4. GeoPandas converts its county boundaries to the coordinate system of the GeoTIFF (EPSG:4326). The cell prints 380 counties, then calculates the mean of the valid raster cells in each county and saves the results in a GeoPackage. A county with no valid cells has an empty mean.

If your copy asks for ms_A02_Granice_powiatow.gml, open the notebook supplied with this article in the same folder. Select Sentinel-5P (districts) in that notebook and resume at the Part 2 imports using the NetCDF file you already created.

districts = gpd.read_file("poland_pow.zip", columns=["JPT_KOD_JE", "JPT_NAZWA_"])
districts = districts.to_crs("EPSG:4326")
print(f"{len(districts)} counties")

stats = rasterstats.zonal_stats(districts.geometry, raster_path, stats=["mean"])
districts["mean_no2"] = [row["mean"] for row in stats]
district_file = "no2_districts_2023_03.gpkg"
districts.to_file(district_file, driver="GPKG", index=False)

Overlay the county boundaries on the monthly NO₂ grid.

west, south, east, north = da.rio.bounds()
fig, ax = plt.subplots(figsize=(20, 20))
m = Basemap(projection="cyl", llcrnrlat=south, urcrnrlat=north,
            llcrnrlon=west, urcrnrlon=east, resolution="c", ax=ax)
mesh = m.pcolormesh(column.longitude.values, column.latitude.values, column.values,
                    cmap="RdYlGn_r", vmin=0, vmax=10, shading="auto")
m.drawparallels(np.linspace(south, north, 5), labels=[1, 0, 0, 0], fontsize=20)
m.drawmeridians(np.linspace(west, east, 5), labels=[0, 0, 0, 1], fontsize=20)
districts.boundary.plot(ax=ax, color="black", linewidth=1)
cbar = fig.colorbar(mesh, ax=ax, fraction=0.03, pad=0.02)
cbar.set_label("NO₂ (Pmolec/cm²)", fontsize=24)
ax.set_title("Mean tropospheric NO₂ column number density in March 2023", fontsize=24)
plt.show()
March 2023 NO₂ grid over Poland with county outlines in black and higher values in the south.

The black lines mark county boundaries. Within each county, the colour shows the March mean for each grid cell.

Read the county means from the GeoPackage and plot one value per county.

district_means = gpd.read_file(district_file)
fig, ax = plt.subplots(figsize=(12, 6))
district_means.plot(column="mean_no2", cmap="RdYlGn_r", vmin=0, vmax=10,
                      ax=ax, legend=True, legend_kwds={"label": "NO₂ TVCD [Pmolec/cm²]"})
ax.set(xlim=(west, east), ylim=(south, north), title="Mean NO₂ TVCD by Polish county in March 2023")
plt.show()
Map of Poland with one colour per county showing its March 2023 mean tropospheric NO₂ column.

Each of the 380 counties has one colour, based on the mean of the valid grid cells inside its boundary.

Save the county map as a JPEG.

fig.savefig("no2_districts_2023_03.jpg", dpi=300)

List the counties in descending order of mean NO₂ column. The four-digit county code distinguishes counties that share a name.

NO2_df = pd.DataFrame({
    "County code": district_means["JPT_KOD_JE"],
    "County": district_means["JPT_NAZWA_"],
    "Mean NO2": district_means["mean_no2"].round(2),
}).sort_values("Mean NO2", ascending=False)
print(NO2_df)

Export the county codes, names and means to CSV.

NO2_df.to_csv("NO2_df.csv", index=False)

Stop Jupyter and close the SSH tunnel

Wait for the last cell to finish, then save the notebook in your browser.

  1. In the VM terminal where you started Jupyter, press Ctrl+C. If Jupyter asks whether to shut down the server, type y and press Enter. This stops the server and its kernels.

  2. In the desktop terminal running ssh -N -L, press Ctrl+C. The SSH tunnel closes and the desktop shell prompt returns.

On Linux, you can check port 8888 in each terminal. An empty result means nothing is listening on that port on that machine.

ss -ltnH 'sport = :8888'

If Jupyter is still listening on the VM after the shell prompt returns, stop the server by port from the VM terminal.

conda run -n s5p-harp jupyter server stop 8888

What to do next