
Earth System Science Hub Challenge 1: Exploring our atmosphere with EarthCARE¶
Exploring our atmosphere with EarthCARE ¶
Clouds and aerosols interactions from EarthCare through k-means clustering
Author(s): Paula Romero Jure, Giacomo Roversi and Filippo Calì Quaglia
Group name: Group 1
Challenge: (1.) Aerosols and Clouds classification and interactions from EarthCare datasets on MAAP (AC-TC EarthCARE Level 2 (https://
Submission date: 30/09/2025
Table of Contents¶
Description ¶
Aerosols are linked to changes in clouds characteristics, as they play a key role in the formation of cloud droplets.
The idea of this study is to use EarthCARE measurements to analyse possible cloud-aerosol interactions (ACI) over three different regions: the West Pacific Ocean, the East Pacific Ocean and the Southern Ocean.
Why these regions?
The tropics are characterised by a band of high and deep convective clouds that is, on average, located between the Equator and 20 degrees north in latitude. This band is called the Intertropical Convergence Zone (ITCZ). In the West Pacific Ocean, we expect to find incoming anthropogenic aerosols from China or non-anthropogenic aerosols produced by biomass burning from Southeast Asia or Australia. In the East Pacific Ocean, we expect mostly sea salt aerosols.
It is not clear whether aerosols contribute to enhancing convection or not. Correlations between an increase in cloud amounts and aerosols have been found (Fan et al., 2013), but causality is still debated. This is particularly challenging to understand from satellite observations, as aerosols can be detected by a Lidar, but Lidar gets extinguished below high clouds with tops made of ice, such as the ones predominant in the ITCZ. In the southern ocean, incoming aerosols from higher latitudes could possibly produce changes in the clouds.
The main method for the analysis is the K-means clustering, which needs numerical, normalized variables. We select the satellite products accordingly. From the Cloud Profiling Radar (CPR), we wanted to obtain cloud variables, therefore we use the level 2A product and extract Liquid Water Path (LWP) and Ice Water Path (IWP), which give us information on the vertical structure of the cloud and its thickness.
From the Lidar (ATLID), we want to get information about the presence of aerosols, so we use the level 2A product to extract the Aerosol Optical Thickness (AOT), which gives us an idea of the presence and amount of aerosols.
Finally, we considered also the the synergetic product available: the AC__TC__2A. This product integrates radar and lidar measurements and provides us with a labelling of the dominant type of target (aerosol, droplet or ice crystal, for example). Since the labelling data does not allow for a distance metric, we leave it out of the clustering and use it to evaluate the clusters afterwards.
The Figure below shows, an example of AC__TC__2A profile over the West Pacific. We can clearly identify two deep convective clouds, where rain, liquid, ice and mixed phase are present. Regarding the aerosols, we see a mix of sea salt and continental pollution in the lower part of the troposphere. We also see how the lidar gets extinguished at the top of the deep convective cloud, as we cannot see aerosols beneath the cloud, but we do see them to the sides.
Finally, there are stratospheric aerosols at the top of the picture at the beginning of the stratosphere, a feature that seems common throughout many scenes in this area.

Key Conclusions ¶
The mechanism of cloud droplet formation within aerosol-polluted environment are very complex, still debated and different for different types of clouds and different aerosols species.
Here we present a VERY simplified theoretical framework on how this works, which is know as aerosols-clouds interactions.
Clouds can be made of liquid droplets or solid ice crystal (sometimes both). The amount of droplets within the cloud and their size is important because not only it can change the macrophysical properties of the clouds, and their “capacity” to make it rain, but also changes in these microphysical properties produce changes in the way that clouds interact with the incoming radiation from the sun and outgoing radiation from Earth.
Aerosols can produce changes in the microphysics of clouds, ie the formation and type of cloud droplets. Aerosols can act as Cloud condensation nuclei (CCN), which is a particle around which the water particles will condense and form cloud droplet. They can also be Ice nucleating particles, ie ice particles will form around the aerosol particle.
We know more about low and liquid clouds interactions with aerosols.
For deep convective clouds, high clouds and ice clouds, we have many hints through modelling and laboratory experiments. However, the complex and interaction conditions from the upper atmosphere are difficult to fully reproduce. Therefore, these mechanisms are still being debated.
Satellite observations have given us many hints on possible relations but there are still some constrains in understanding causality from them.
We can mostly expect sea salt aerosols in these area, although there might also be some stratospheric aerosols incoming mostly from volcanic eruptions.
The presence of aerosols can lead to precipitation changes (rain supression) by providing more CCNs.
Also, if the clouds change their properties due to the interactions with aerosols, these could lead to a feedback process with the surface.
Ie, if we have enough clouds, and the clouds become less reflective to the surface or does not allow the reflected radiation from the ice sheet to escape the Earth, then this could lead to a positive feedback process.
Societal Context ¶
There are different sources of aerosols that can even get to isolated areas in the Pacific.
Different types of aerosols can act differently.
Within the non-anthropogenic aerosols, i.e., aerosols not created directly by human activities, sea salt is one of them. The distribution of this type of aerosol is not uniform, as the winds, waves and convection can cause different distributions. This will be present across all the oceans.
Other non-anthropogenic aerosols that can reach the West Pacific are the carbon dioxide coming from forest burning in Southeast Asia.
Anthropogenic aerosols are aerosols that are directly produced from human activity. For example, the ones produced during fossil fuel burning or industrial activity, like sulfate and nitrogen oxides.
They can reach the western Pacific according to the winds and dynamical conditions, mostly incoming from south-west China.
Data sources ¶
| Instrument name | Variable name | Description | Reference* | Region | Time range | Resolution |
|---|---|---|---|---|---|---|
| ATLID | ATL_ALD_2A | Providing aerosol layer top/base height, optical thickness, extinction, backscatter, and depolarisation. | PDD | WP, EP, SO | 3 months | 1 minute |
| CPR | CPR_CLD_2A | Providing cloud water content and characteristic diameters, liquid water path, and ice water path. | PDD | WP, EP, SO | 3 months | 1 minute |
| ATLID, CPR | AC__TC__2B | Providing ATLID and CPR detection status, and ATLID/CPR target classification flags. | PDD | WP, EP, SO | 3 months | 1 minute |
PART 2: SCIENTIFIC EXPLOITATION AND ANALYSIS¶
Import Libraries ¶
# Install required libraries and packages with conda
#%conda install -y -c conda-forge numpy scipy xarray pandas h5py h5netcdf netcdf4 cftime zarr pystac-client fsspec matplotlib tqdm aiohttp requests ipykernel seaborn scikit-learn cartopy# Standard library
import os
import pathlib
# Third-party
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import fsspec
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import xarray as xr
from IPython.display import Image, display
from matplotlib.patches import Patch, Rectangle
from pystac_client import Client
from scipy import stats # will use scipy.stats.mode as the reducer
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from tqdm import tqdmToken¶
You can generate the token here. Currently, this is only valid for 10 h! Copy the token and save it in a .txt file in your home directory.
home = pathlib.Path.home()# Token for ectools
os.environ['MAAP_credentials'] = str(home/'token.txt')with open(home /'token.txt', 'r') as f:
token = f.read()We use ectools for some exploratory analysis. ectools is currently installed from their repository here.
import ectools
from ectools import ecioAnalysis cells ¶
We define some necessary variables: our areas of interest as geoboxes, the name of the products, the catalogue from MAAP where the products are stored.
catalog_url = 'https://catalog.maap.eo.esa.int/catalogue/'
catalog = Client.open(catalog_url)
EC_COLLECTION = ['EarthCAREL2Validated_MAAP']# Geographic areas
geoboxes = {
"WestPacific":[ 110, 0, 160, 20],
"EastPacific":[-160, 0, -100, 20],
"Antarctica1": [ 160, -80, 180, -60],
"Antarctica2": [ -180, -80, -140, -60],
}
# EarthCARE products
products = ["ATL_ALD_2A", "CPR_CLD_2A", "AC__TC__2B"]Let’s see how the geoboxes look like in a map
# Create map
fig = plt.figure(figsize=(10,5))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines()
ax.add_feature(cfeature.BORDERS, linewidth=0.5)
ax.gridlines(draw_labels=True)
# Plot regional boxes
for lon_min, lat_min, lon_max, lat_max in [geoboxes[i] for i in geoboxes]:
width = lon_max - lon_min
height = lat_max - lat_min
rect = Rectangle(
(lon_min, lat_min), width, height,
linewidth=2, edgecolor='red', facecolor='none',
transform=ccrs.PlateCarree()
)
ax.add_patch(rect)
plt.show()

We start by searching the data on the MAAP catalogue, for the defined areas (bbox) and period of interests.
#Searching for radar-derived products
searchCPR = ectools.ecio.search_MAAP_catalog( product='CPR_CLD_2A',
frame="E",
datetime=['2024-07-28T00:00:00Z','2025-09-30T00:00:00Z'],
bbox=[ 110, 0, 160, 20],
catalog_url='https://catalog.maap.eo.esa.int/catalogue/',
access_level='public',
max_items=5,
include_quicklooks=False,
take_latest=True)Access level: public
filter by: "product:type='CPR_CLD_2A' and frame='E'"
bbox: [110, 0, 160, 20]
datetime: ['2024-07-28T00:00:00Z', '2025-09-30T00:00:00Z']
Accessing 5 items (up to max_items=5).
1233 items found that matched the query.
#Searching for lidar-derived products
searchATL = ectools.ecio.search_MAAP_catalog( product='ATL_ALD_2A',
frame="E",
datetime=['2024-07-28T00:00:00Z','2025-09-30T00:00:00Z'],
bbox=[ 110, 0, 160, 20],
catalog_url='https://catalog.maap.eo.esa.int/catalogue/',
access_level='public',
max_items=5,
include_quicklooks=False,
take_latest=True)Access level: public
filter by: "product:type='ATL_ALD_2A' and frame='E'"
bbox: [110, 0, 160, 20]
datetime: ['2024-07-28T00:00:00Z', '2025-09-30T00:00:00Z']
Accessing 5 items (up to max_items=5).
1260 items found that matched the query.
Products ID and URL access, toghether with relevant data like orbit and frame ID, are stored as a pandas dataframe.
Let’s take a look at some of ATLID data that was found
items = list(searchATL.items())
# Using Pandas dataframes for ease of use. This is not mandatory, but just a nice way to get an overview of the products you found through the search. Please note that pandas dataframes run into issues if we try to pass to many products. Use max_items! :)
data = searchATL
datasearch_string = f"productType = 'AC__TC__2B'"
print(search_string)
productType = 'AC__TC__2B'
#dict_keys(['stac_version', 'assets', 'bbox', 'geometry', 'links', 'id', 'collection', 'type', 'stac_extensions', 'properties'])
#data['features'][1]['assets']['enclosure_hdr']
df = pd.json_normalize(data, record_path=['features'])[
[
"id", # Product id (file name)
"properties.product:type", # Product type
"properties.updated", # Product last update
"assets.product.href", # URL to product download link
"assets.quicklook_jpeg.href", # URL to product quicklook jpeg
"assets.enclosure_h5.href", # URL to product h5 download
"assets.enclosure_hdr.href", # URL to product hdr download
]
]Method¶
We define a method to process each product and generate a ready-to-train final file. This function needs the token as a str.
def load_and_prepare_all(bbox, product, token=token):
"""Function for preparing product.
Parameters:
----------
bbox: list
Region extention as [lon_min, lat_min, lon_max, lat_max]
product: str
product name
token: str
Your temporary token
Returns:
-------
data_1s: xarray.DataArray
Product resampled to 1 second.
"""
# Define the variables we want to extract from each product
variables = {
"ATL_ALD_2A": ['latitude', 'longitude', 'aerosol_optical_thickness_355nm'],
"CPR_CLD_2A": ['latitude', 'longitude', 'land_flag', 'ice_water_path', 'liquid_water_path'],
"AC__TC__2B" : ['latitude', 'longitude', 'synergetic_target_classification']
}
search_string = f"productType = '{product}'"
print(search_string)
# Search using the catalog module here!
search = catalog.search(
collections=EC_COLLECTION,
filter=search_string, # Filter by product type
bbox = bbox, # Geobox
method = 'GET', # This is necessary
)
items = list(search.items())
print(f"{search.matched()} items found that matched the query.")
# Create a dict with the items found and their properties, located under 'features' key as a list
data = search.item_collection_as_dict()
# Each element of data['features'] is a dict with one product info
# Here we extract some properties that we need
df = pd.json_normalize(data, record_path=['features'])[
[
"id", # Product id (file name)
"properties.product:type", # Product type
"properties.updated", # Product last update
"assets.product.href", # URL to product download link
"assets.quicklook_jpeg.href", # URL to product quicklook jpeg
"assets.enclosure_h5.href", # URL to product h5 download
"assets.enclosure_hdr.href", # URL to product hdr download
]
]
# Renaming the columns to make it easier
df.rename(columns={
'properties.product:type': 'product_type',
'properties.updated': 'last_modified',
'assets.product.href': 'Zipped Product',
'assets.quicklook_jpeg.href': 'quicklook_url',
'assets.enclosure_h5.href': 'h5_url',
'assets.enclosure_hdr.href': 'HDR_url',
}, inplace=True)
df.sort_values(by='id', ascending=True, inplace=True)
df.reset_index(drop=True, inplace=True)
frames = []
for i in tqdm(range(len(df))):
ds_url = df.loc[i, "h5_url"]
#print(ds_url)
if ds_url[-3:] != ".h5":
continue
fs = fsspec.filesystem("https", headers={"Authorization": f"Bearer {token}"})
with fs.open(ds_url, "rb") as f:
# Open the data
ds = xr.open_dataset(f, engine="h5netcdf", group="ScienceData").compute()
# Get the variables
selection = ds[variables[product]]
if product == "AC__TC__2B":
# Set unique coordinate to along track dimension
# selection = selection.assign_coords(along_track=ds['time'])
selection = selection.assign_coords(along_track=ds['time'], JSG_height=ds['height'].isel(along_track=0))
selection = selection.rename({"along_track":"time"})
binned = selection['synergetic_target_classification'].groupby_bins('JSG_height', bins=[0, 2500, 5000, 7500, 10000, 12500, 15000, 17500, 20000])
coarse = binned.reduce(lambda arr, axis: stats.mode(arr, axis=axis, keepdims=False).mode)
# Turn bins into variables
binned_ds = coarse.to_dataset(dim="JSG_height_bins")
# Clean variable names (optional: make them short and safe)
binned_ds = binned_ds.rename(
{bin_label: f"stc_{(i+1)*2500}" for i, bin_label in enumerate(binned_ds.data_vars)}
)
# Append to the original Dataset
final = selection[['latitude', 'longitude']].merge(binned_ds)
frames.append(final)
else:
# Set unique coordinate to along track dimension
selection = selection.assign_coords(along_track=ds['time'])
selection = selection.rename({"along_track":"time"})
frames.append(selection)
data = xr.concat(frames, dim='time')
data_sorted = data.sortby('time')
data_1s = data_sorted.resample(time='1s').mean().dropna(dim='time', how='all')
if product == "ATL_ALD_2A":
data_1s = data_1s.where(data_1s != 0.)
# Enforce the bounding box
data_1s = data_1s.where(
(data_1s.latitude >= bbox[1]) &
(data_1s.latitude < bbox[3]) &
(data_1s.longitude >= bbox[0]) &
(data_1s.longitude < bbox[2]),
drop=True
)
return data_1sRunning method for regions¶
The code here works now for Antarctica, some adjustments are needed for the other areas
suffix = ["_AN", "_EP", "_WP"]
if loc == "Antarctica":
# include also Antarctica2
geoboxes["Antarctica2"] ...In the following cell the function defined avobe is run for Antartica (SO) region
if not os.path.exists('challenge_1min_complete_AN.nc'):
# Run the function for all the three products on a specified area and merge the results
a = load_and_prepare_all(geoboxes["Antarctica1"], "AC__TC__2B")
b = load_and_prepare_all(geoboxes["Antarctica1"], "CPR_CLD_2A")
c = load_and_prepare_all(geoboxes["Antarctica1"], "ATL_ALD_2A")
challenge = a.merge(b[['land_flag', 'ice_water_path', 'liquid_water_path']], join='outer', compat='override')
challenge = challenge.merge(c, join='outer', compat='override')
# Repeat for the second part of Antarctica
a = load_and_prepare_all(geoboxes["Antarctica2"], "AC__TC__2B")
b = load_and_prepare_all(geoboxes["Antarctica2"], "CPR_CLD_2A")
c = load_and_prepare_all(geoboxes["Antarctica2"], "ATL_ALD_2A")
challenge2 = a.merge(b[['land_flag', 'ice_water_path', 'liquid_water_path']], join='outer', compat='override')
challenge2 = challenge2.merge(c, join='outer', compat='override')
challenge = challenge.merge(challenge2, join='outer', compat='override')
numerical_variables = [
'latitude',
'longitude',
'land_flag',
'ice_water_path',
'liquid_water_path',
'aerosol_optical_thickness_355nm'
]
# Let's put nans to zero when sensors are working and sky is clear
challenge[numerical_variables[2:]] = challenge[numerical_variables[2:]].fillna(0).clip(min=0, max=1e2)
## Now resample again to 1min to get both aerosols and clouds in the same pixel
# Numerical variables with mean:
challenge_1min_numerical = challenge[numerical_variables].resample(time='1min').mean().dropna(dim='time', how='any')
# Save the numerical dataset
challenge_1min_numerical.to_netcdf('challenge_1min_numerical_AN.nc')
# Label variables with mode
def mode_func(arr, axis): #They need a specific funcion to be resampled with the mode instead of the mean.
# scipy returns both mode and count, we only want the mode
return stats.mode(arr, axis=axis, keepdims=False).mode # , nan_policy="omit"
challenge_1min_labels = (
challenge
.drop_vars(numerical_variables)
.resample(time="1min")
.reduce(mode_func)
.dropna(dim="time", how="any")
)
# Save the resampled TC dataset
challenge_1min_labels.to_netcdf('challenge_1min_labels_AN.nc')
# Merge back together
challenge_1min_complete = (
challenge_1min_numerical
.merge(
challenge_1min_labels,
join='outer',
compat='override')
)
# Save the merged dataset
challenge_1min_complete.to_netcdf('challenge_1min_complete_AN.nc')
else:
challenge_1min_complete = xr.open_dataset(f"challenge_1min_complete_AN.nc")Here we run it for the West Pacific region
if not os.path.exists('challenge_1min_complete_WP.nc'):
# Run the function for all the three products on a specified area and merge the results
a = load_and_prepare_all(geoboxes["WestPacific"], "AC__TC__2B")
b = load_and_prepare_all(geoboxes["WestPacific"], "CPR_CLD_2A")
c = load_and_prepare_all(geoboxes["WestPacific"], "ATL_ALD_2A")
challenge = a.merge(b[['land_flag', 'ice_water_path', 'liquid_water_path']], join='outer', compat='override')
challenge = challenge.merge(c, join='outer', compat='override')
numerical_variables = [
'latitude',
'longitude',
'land_flag',
'ice_water_path',
'liquid_water_path',
'aerosol_optical_thickness_355nm'
]
# Let's put nans to zero when sensors are working and sky is clear
challenge[numerical_variables[2:]] = challenge[numerical_variables[2:]].fillna(0).clip(min=0, max=1e2)
## Now resample again to 1min to get both aerosols and clouds in the same pixel
# Numerical variables with mean:
challenge_1min_numerical = challenge[numerical_variables].resample(time='1min').mean().dropna(dim='time', how='any')
# Save the numerical dataset
challenge_1min_numerical.to_netcdf('challenge_1min_numerical_WP.nc')
# Label variables with mode
def mode_func(arr, axis): #They need a specific funcion to be resampled with the mode instead of the mean.
# scipy returns both mode and count, we only want the mode
return stats.mode(arr, axis=axis, keepdims=False).mode # , nan_policy="omit"
challenge_1min_labels = (
challenge
.drop_vars(numerical_variables)
.resample(time="1min")
.reduce(mode_func)
.dropna(dim="time", how="any")
)
# Save the resampled TC dataset
challenge_1min_labels.to_netcdf('challenge_1min_labels_WP.nc')
# Merge back together
challenge_1min_complete = (
challenge_1min_numerical
.merge(
challenge_1min_labels,
join='outer',
compat='override')
)
# Save the merged dataset
challenge_1min_complete.to_netcdf('challenge_1min_complete_WP.nc')
else:
challenge_1min_complete = xr.open_dataset(f"challenge_1min_complete_WP.nc")K-Means¶
We run the K-means algorithm
def cluster_variance(n, x):
variances=[]
kmeans=[]
outputs=[]
K=[i for i in range(1,n+1)]
for i in range(1,n+1):
variance=0
model=KMeans(n_clusters=i,random_state=82,verbose=2).fit(x)
kmeans.append(model)
variances.append(model.inertia_)
return variances,K,nOpen the dataset we have previously generated, resampled to 1 minute of temporal resolution.
ds = xr.open_dataset(f"challenge_1min_numerical_AN.nc")# Enforce the bounding box
ds = ds.where(
(
(ds.latitude >= geoboxes["Antarctica1"][1]) &
(ds.latitude < geoboxes["Antarctica1"][3]) &
(ds.longitude >= geoboxes["Antarctica1"][0]) &
(ds.longitude < geoboxes["Antarctica1"][2])
) | (
(ds.latitude >= geoboxes["Antarctica2"][1]) &
(ds.latitude < geoboxes["Antarctica2"][3]) &
(ds.longitude >= geoboxes["Antarctica2"][0]) &
(ds.longitude < geoboxes["Antarctica2"][2])
),
drop=True
)x = ds.drop_vars(['latitude','longitude']).to_array().transpose("time", "variable").values
# x = ds.to_array().transpose("time", "variable").valuesApply a min-max normalization to the data
x = (x - np.min(x, axis=0)) / (np.max(x, axis=0) - np.min(x, axis=0))
xarray([[0.66493506, 0.07297073, 0. , 0. ],
[0.20952381, 0.36253172, 0. , 0. ],
[1. , 0. , 0. , 0. ],
...,
[0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. ]], shape=(791, 4))Calculating the ideal number of clusters or groups for which the K-mean algorithm will converge, using the elbow method.
variances,K,n=cluster_variance(20, x)
plt.plot(K,variances)
plt.ylabel("Inertia ( Total Distance )")
plt.xlabel("K Value")
plt.xticks([i for i in range(1,n+1)])
plt.show()Initialization complete
Iteration 0, inertia 83.94128020063762.
Iteration 1, inertia 79.04169812862384.
Converged at iteration 1: strict convergence.
Initialization complete
Iteration 0, inertia 55.46179566017088.
Iteration 1, inertia 23.291296049752884.
Iteration 2, inertia 22.259663904984322.
Iteration 3, inertia 22.127212169527848.
Iteration 4, inertia 22.12265737795621.
Iteration 5, inertia 22.120893721611928.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 21.50591502854491.
Iteration 1, inertia 17.69848910829133.
Iteration 2, inertia 17.51409281451823.
Iteration 3, inertia 17.47445261533057.
Iteration 4, inertia 17.465234232507857.
Iteration 5, inertia 17.459938808821445.
Iteration 6, inertia 17.456770761891715.
Iteration 7, inertia 17.440405375460486.
Iteration 8, inertia 17.42033102539664.
Iteration 9, inertia 17.41226327971376.
Converged at iteration 9: strict convergence.
Initialization complete
Iteration 0, inertia 16.411053421764024.
Iteration 1, inertia 12.816898130993657.
Iteration 2, inertia 12.599351596707141.
Iteration 3, inertia 12.547681932648224.
Iteration 4, inertia 12.52360503185108.
Iteration 5, inertia 12.4972944090952.
Iteration 6, inertia 12.463517295876008.
Iteration 7, inertia 12.449610649736659.
Iteration 8, inertia 12.44665866827523.
Converged at iteration 8: strict convergence.
Initialization complete
Iteration 0, inertia 12.766910674737337.
Iteration 1, inertia 11.282008460973753.
Iteration 2, inertia 11.210980433478994.
Iteration 3, inertia 11.183437622164764.
Iteration 4, inertia 11.17517417016294.
Iteration 5, inertia 11.173546264456187.
Iteration 6, inertia 11.172056513772281.
Converged at iteration 6: strict convergence.
Initialization complete
Iteration 0, inertia 10.145794982971026.
Iteration 1, inertia 8.158980904030399.
Iteration 2, inertia 7.78231664542908.
Iteration 3, inertia 7.433779552658379.
Iteration 4, inertia 7.11504071413971.
Iteration 5, inertia 7.0661805532651245.
Iteration 6, inertia 7.060779639404569.
Converged at iteration 6: strict convergence.
Initialization complete
Iteration 0, inertia 8.93993606094572.
Iteration 1, inertia 7.16151110394229.
Iteration 2, inertia 6.779940614572866.
Iteration 3, inertia 6.421353953977841.
Iteration 4, inertia 6.106427547229407.
Iteration 5, inertia 6.05918880731252.
Iteration 6, inertia 6.055277644135872.
Converged at iteration 6: strict convergence.
Initialization complete
Iteration 0, inertia 5.925405629945825.
Iteration 1, inertia 5.14169531529863.
Iteration 2, inertia 5.083683093812935.
Iteration 3, inertia 5.0569492673484415.
Iteration 4, inertia 5.034942591571646.
Iteration 5, inertia 5.021885277116303.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 4.913389184834135.
Iteration 1, inertia 4.167436723526138.
Iteration 2, inertia 4.040394332101336.
Iteration 3, inertia 4.016218458764956.
Converged at iteration 3: strict convergence.
Initialization complete
Iteration 0, inertia 4.341214963728565.
Iteration 1, inertia 3.6630505704846987.
Iteration 2, inertia 3.546933211572808.
Iteration 3, inertia 3.5240319638394797.
Converged at iteration 3: strict convergence.
Initialization complete
Iteration 0, inertia 3.7622039615316507.
Iteration 1, inertia 3.1823082005237477.
Iteration 2, inertia 3.1341007667085266.
Iteration 3, inertia 3.113706750180148.
Iteration 4, inertia 3.1119543303358514.
Converged at iteration 4: strict convergence.
Initialization complete
Iteration 0, inertia 3.429633681718776.
Iteration 1, inertia 2.7505425904268703.
Iteration 2, inertia 2.6403432321807565.
Iteration 3, inertia 2.6155770715091657.
Iteration 4, inertia 2.6029440719327286.
Iteration 5, inertia 2.6020055173825796.
Iteration 6, inertia 2.6010125510869395.
Converged at iteration 6: strict convergence.
Initialization complete
Iteration 0, inertia 2.9804737470637077.
Iteration 1, inertia 2.394670941787254.
Iteration 2, inertia 2.3133517109983885.
Iteration 3, inertia 2.305756224124432.
Iteration 4, inertia 2.3037885192241174.
Iteration 5, inertia 2.3028499646739684.
Iteration 6, inertia 2.3018569983783297.
Converged at iteration 6: strict convergence.
Initialization complete
Iteration 0, inertia 2.613737597134922.
Iteration 1, inertia 2.0794984806759587.
Iteration 2, inertia 2.0362567744883258.
Iteration 3, inertia 2.0294301220964432.
Iteration 4, inertia 2.027472288453859.
Iteration 5, inertia 2.025354270658027.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 2.4202319362377804.
Iteration 1, inertia 1.8822753467917424.
Iteration 2, inertia 1.823531393638171.
Iteration 3, inertia 1.8135581409720243.
Iteration 4, inertia 1.8105288317577226.
Iteration 5, inertia 1.8084108139618906.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 2.2772017355578895.
Iteration 1, inertia 1.7645048013585782.
Iteration 2, inertia 1.70738310124905.
Iteration 3, inertia 1.6974098485829034.
Iteration 4, inertia 1.6944163035405593.
Iteration 5, inertia 1.692297503972988.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 1.9265163601226747.
Iteration 1, inertia 1.5255694654955467.
Iteration 2, inertia 1.4929432952689.
Iteration 3, inertia 1.477156926335045.
Iteration 4, inertia 1.473407490436966.
Iteration 5, inertia 1.4701678299060457.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 1.745356730763182.
Iteration 1, inertia 1.4223788439282676.
Iteration 2, inertia 1.3851463910379724.
Iteration 3, inertia 1.3776335257468715.
Iteration 4, inertia 1.3739101621769083.
Iteration 5, inertia 1.3706532839387773.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 1.6033559727396742.
Iteration 1, inertia 1.2651369064865794.
Iteration 2, inertia 1.2074132383581127.
Iteration 3, inertia 1.187696094702169.
Iteration 4, inertia 1.18568708060975.
Iteration 5, inertia 1.1854933397600134.
Converged at iteration 5: strict convergence.
Initialization complete
Iteration 0, inertia 1.4899910000955299.
Iteration 1, inertia 1.1079769988652661.
Iteration 2, inertia 1.049610789083364.
Iteration 3, inertia 1.0298936454274201.
Iteration 4, inertia 1.0278846313350007.
Iteration 5, inertia 1.0276908904852646.
Converged at iteration 5: strict convergence.

dsk = 5
# Appling K-Means classification
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
y_kmeans = kmeans.fit_predict(x)Checking the cluster’s centroids
kmeans.cluster_centers_array([[ 9.37773535e-01, 6.44299081e-02, -6.50521303e-19,
4.83169010e-03],
[ 5.99111239e-03, 1.01311943e-02, 1.62866450e-03,
1.34518700e-02],
[ 4.08730159e-02, 6.57179422e-01, 0.00000000e+00,
3.46944695e-18],
[ 4.56176368e-01, 2.43666637e-02, -4.33680869e-19,
2.24304667e-02],
[ 2.51322751e-03, 1.60728047e-03, -2.16840434e-19,
3.61514947e-01]])Plots: We define a funtion to plot the data points
vars = {
# 'lat': 0,
# 'lon': 1,
'landf' : 0 ,
'iwp': 1,
'lwp': 2,
'aot': 3
}def plot_kmeans(x, varX, varY, ax=None):
"""This method plots variables against each other showing the distribution of the data points and clusters.
Parameters:
-----------
x: dataset
varX: str
Variable name to be plotted on X axis
varY: str
Variable name to be plotted on Y axis
ax:
Subplot ax object
Returns: None
"""
if not ax:
fig, ax = plt.subplots()
# Visualizziamo i dati colorati in base ai cluster trovati
ax.scatter(x[:, vars[varX]], x[:, vars[varY]], c=y_kmeans, s=10, cmap='jet', alpha=0.5) #'viridis')
# Mostriamo anche i centroidi
centers = kmeans.cluster_centers_
ax.scatter(centers[:, vars[varX]], centers[:, vars[varY]], c='red', s=50, alpha=0.75, marker='X', label='Centroids')
for i in np.arange(1,6):
ax.text(centers[(i-1), vars[varX]]*1.1, centers[(i-1), vars[varY]]*1.1, s=str(i), c='red')
ax.set_title("K-Means clustering")
ax.set_xlabel(varX)
ax.set_ylabel(varY)
ax.legend()
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
varX='aot'
varY='iwp'
plot_kmeans(x, varX, varY, ax=axes[0])
varX='aot'
varY='lwp'
plot_kmeans(x, varX, varY, ax=axes[1])
varX='iwp'
varY='lwp'
plot_kmeans(x, varX, varY, ax=axes[2])
varX='aot'
varY='iwp'
plot_kmeans(x, varX, varY)
plt.xlim(0, 0.25)
plt.ylim(0, 0.25)(0.0, 0.25)
Classes we were expecting:¶
Cluster 4: Aerosol with no clouds
Cluster 3: Ice and water with no transparency (ATLID is not seeing aerosol)
Let’s see the other three
# select only clusters 1, 2 and 5np.unique(y_kmeans)array([0, 1, 2, 3, 4], dtype=int32)indices = np.where((y_kmeans == 0) | (y_kmeans == 1) | (y_kmeans == 4))[0]varX='lwp'
varY='iwp'
plot_kmeans(x, varX, varY)
plt.xlim(0, .1)(0.0, 0.1)
Now we plot the data points by their latitude and longitude, to understand the spatial distribution of the clusters
plt.scatter(ds['longitude'].values, ds['latitude'].values, c=y_kmeans, cmap='viridis')
# Same plot, different color map
plt.scatter(ds['longitude'].values, ds['latitude'].values, c=y_kmeans, cmap='jet')
plt.xlabel('longitude')
plt.ylabel('latitude')
Explore the classification differences among the clusters at different heights¶
ds_tc = challenge_1min_complete
ds_tc# Synergetic class range and colors
plot_range = range(-1, 35) # inclusive -1..33
plot_colors = [
"#c5c9c7", "#a2653e", "#ffffff", "#ff474c", "#0504aa", "#009337",
"#840000", "#042e60", "#d8dcd6", "#ffff84", "#f5bf03", "#f97306",
"#ff000d", "#5539cc", "#2976bb", "#0d75f8", "#014182", "#017b92",
"#06b48b", "#aaff32", "#6dedfd", "#01f9c6", "#7bc8f6", "#d7fffe",
"#a2cffe", "#04d9ff", "#7a9703", "#b2996e", "#ffbacd", "#d99b82",
"#947e94", "#856798", "#ac86a8", "#59656d", "#76424e", "#363737"
]
labels = [
"-1: unknown"," 0: ground"," 1: clear"," 2: possible rain (clutter)"," 3: possible snow (clutter)",
" 4: possible cloud (clutter)"," 5: heavy rain"," 6: heavy mixed-phase precip",
" 7: no rain/ice (possible liquid)"," 8: liquid cloud"," 9: drizzling liquid cloud",
"10: warm rain","11: cold rain","12: melting snow","13: snow (possible liquid)",
"14: snow (no liquid)","15: rimed snow (possible liquid)",
"16: rimed snow + supercooled liquid","17: snow + supercooled liquid",
"18: supercooled liquid","19: ice cloud (possible liquid)",
"20: ice + supercooled liquid","21: ice cloud (no liquid)",
"22: stratospheric ice","23: STS (PSC Type I)","24: NAT (PSC Type II)","25: insects",
"26: dust","27: sea salt","28: continental pollution","29: smoke","30: dusty smoke",
"31: dusty mix","32: stratospheric ash","33: stratospheric sulfate","34: stratospheric smoke"
]
# Build discrete colormap
cmap = mcolors.ListedColormap(plot_colors)
bounds = list(plot_range) + [34] # bin edges
norm = mcolors.BoundaryNorm(bounds, cmap.N)# Example: suppose your classification variable is called "target_class"
# s = ds_tc["stc_2500"][y_kmeans == 0].plot.hist(bins=bounds)
row_labels = [
"stc_2500",
"stc_5000",
"stc_7500",
"stc_10000",
"stc_12500",
"stc_15000",
"stc_17500",
"stc_20000"
]
fig, axes= plt.subplots(8, 5, figsize=(24, 20))
for i, label in enumerate(row_labels):
row_axes = axes[i, :]
# Calcola il centro verticale medio
y_pos = np.mean([ax.get_position().y0 + ax.get_position().height / 2 for ax in row_axes])
# Prende la x minima (sinistra)
x_pos = row_axes[0].get_position().x0 - 0.05
# Aggiunge il testo
fig.text(x_pos, y_pos, label, va='center', ha='right', fontsize=14) #, fontweight='bold')
for k in range(4):
# Crea l'istogramma con 5 bin
n, bins, patches = axes[i,k].hist(
ds_tc[label][y_kmeans == k],
bins=bounds)
for patch, color in zip(patches, plot_colors):
patch.set_facecolor(color)
col_labels = [
"Cluster 1",
"Cluster 2",
"Cluster 3",
"Cluster 4",
"Cluster 5"
]
for j, label in enumerate(col_labels):
# Prendi gli assi della colonna j
col_axes = axes[:, j]
# Calcola la posizione orizzontale centrale della colonna (in figura)
x0 = min(ax.get_position().x0 for ax in col_axes)
x1 = max(ax.get_position().x0 + ax.get_position().width for ax in col_axes)
x_center = (x0 + x1) / 2
# Calcola la y poco sopra la parte superiore degli assi (usa l’asse superiore)
top_ax = axes[0, j]
y_top = top_ax.get_position().y0 + top_ax.get_position().height
y_text = y_top + 0.02 # spostalo un po’ sopra (modifica questo offset se serve)
fig.text(x_center, y_text, label, ha='center', va='bottom', fontsize=16) #, fontweight='bold')

References ¶
EarthCARE Product Data Handbook: https://
earthcarehandbook .earth .esa .int /catalogue Lorian, A., et al. (2023). Aerosol effects on deep convection: A review. Atmospheric Research.
AMT - Cloud top heights and aerosol layer properties from EarthCARE lidar observations
Wildfires in Southeast Asia pollute the atmosphere in the northern South China Sea
Copernicus - Wildfires 2025 review: ASEAN reduces emissions, but haze persists
- Heikenfeld, M., White, B., Labbouz, L., & Stier, P. (2019). Aerosol effects on deep convection: the propagation of aerosol perturbations through convective cloud microphysics. Atmospheric Chemistry and Physics, 19(4), 2601–2627. 10.5194/acp-19-2601-2019
- Grabowski, W. W. (2015). Untangling Microphysical Impacts on Deep Convection Applying a Novel Modeling Methodology. Journal of the Atmospheric Sciences, 72(6), 2446–2464. 10.1175/jas-d-14-0307.1
- Igel, M. R., & van den Heever, S. C. (2015). The relative influence of environmental characteristics on tropical deep convective morphology as observed by CloudSat. Journal of Geophysical Research: Atmospheres, 120(9), 4304–4322. 10.1002/2014jd022690