
Note
This notebook has been developed and validated on the DeepESDL environment, where the necessary data, tools, and execution kernels are available. DeepESDL is part of ESA’s EarthCODE initiative, enabling open and reproducible Earth Science. Sponsored access can be requested through ESA’s Network of Resources.
Table of Contents ¶
Title ¶
Challenge: K-means clustering analysis of oceanographic patterns in the Mediterranean Sea¶
Authors:
Katie Lowery, British Antarctic Survey (BAS), Cambridge, United Kingdom of Great Britain
William Luty , University of Leeds, Leeds, United Kingdom of Great Britain - England, Scotland, Wales
Enrico Biscaro, Ca’ Foscari University of Venice, Italy
Description ¶
Scientific problem¶
Ocean water types - such as coastal, upwelling, oligotrophic, and eutrophic waters - exhibit distinct spectral and biogeochemical characteristics. Classifying these types is essential for understanding marine ecosystems, monitoring water quality, and supporting climate and fisheries research. This challenge leverages EO data and unsupervised learning to classify ocean water types based on spectral reflectance and derived indices.
Objective¶
Use clustering algorithms to classify ocean water types from EO spectral bands and indices. Validate clusters against known oceanographic features or water classifications and produce a map of water types for a selected region.
Method¶
K-means clustering.
Clustering optimization technique¶
Elbow method: to determine the optimal number of clusters to use.
Optimization metric: Inertia (Sum of Squared Errors)
Service used¶
Use case: Mediterranean Sea¶
Optimizing fish harvesting while preserving fish populations and marine biodiversity in the Mediterranean
Monitoring physico-chemical parameters of the Mediterranean Sea in a climate change scenario also considering its contribution to the Atlantic Meridional Overturning Circulation (AMOC)

Processing workflow¶

References ¶
Berthon, J.-F., Zibordi, G.: Bio-optical relationships for the northern Adriatic Sea. Int. J. Remote Sens., 25, 1527-1532, 2004
Buongiorno Nardelli, B., R. Droghei, and R. Santoleri, (2016): Multi-dimensional interpolation of SMOS sea surface salinity with surface temperature and in situ salinity data. Rem. Sens. Environ
Droghei, R., B. Buongiorno Nardelli, and R. Santoleri, 2016: Combining in-situ and satellite observations to retrieve salinity and density at the ocean surface. J. Atmos. Oceanic Technol.
Embury, O., Merchant, C.J., Good, S.A., Rayner, N.A., Høyer, J.L., Atkinson, C., Block, T., Alerskans, E., Pearson, K.J., Worsfold, M., McCarroll, N., Donlon, C., (2024). Satellite-based time-series of sea-surface temperature since 1980 for climate applications. Sci Data 11, 326
Pisano, A., Nardelli, B. B., Tronconi, C., & Santoleri, R. (2016). The new Mediterranean optimally interpolated pathfinder AVHRR SST Dataset (1982–2012). Remote Sensing of Environment, 176, 107-116
Sammartino, Michela, Salvatore Aronica, Rosalia Santoleri, and Bruno Buongiorno Nardelli. (2022). Retrieving Mediterranean Sea Surface Salinity Distribution and Interannual Trends from Multi-Sensor Satellite and In Situ Data, Remote Sensing 14, 250
Volpe, G., Buongiorno Nardelli, B., Colella, S., Pisano, A. and Santoleri, R. (2018). An Operational Interpolated Ocean Colour Product in the Mediterranean Sea, in New Frontiers in Operational Oceanography, edited by E. P. Chassignet, A. Pascual, J. Tintorè, and J. Verron, pp. 227–244z
Volpe, G., Colella, S., Brando, V. E., Forneris, V., Padula, F. L., Cicco, A. D., ... & Santoleri, R. (2019). Mediterranean ocean colour Level 3 operational multi-sensor processing. Ocean Science, 15(1), 127-146
Key Conclusions ¶
This study demonstrates the effectiveness of unsupervised clustering for identifying and mapping ocean water types from multi-parameter satellite observations. Key findings include:
Three distinct water types identified: Coastal (high productivity), eutrophic (moderate productivity), and oligotrophic (low productivity) waters distinguished by combined biological, physical, and atmospheric characteristics
Geographic coherence: Spatial patterns align with known Mediterranean oceanography, validating the clustering approach against established understanding
Seasonal dynamics captured: Temporal analysis reveals expansion/contraction of water types consistent with seasonal stratification and mixing cycles
Multi-parameter synergy: Integration of chlorophyll-a, SST, sea level height, and wind components provides richer characterization than single-parameter approaches
Study limitations and future directions:
Cluster number selection: Statistical optimum (5 clusters) provided insufficient detail, while chosen number (8) resulted in only 3 active clusters—suggesting need for adaptive cluster selection methods
Coastal water stability: Lack of seasonal variation in Cluster 2 (coastal waters) may indicate need for higher temporal resolution or separate coastal-specific analysis
Validation needed: No quantitative validation against in-situ measurements or existing water type classifications was performed
Algorithm exploration: Testing alternative clustering methods (hierarchical, DBSCAN, Gaussian mixture models) could improve classification
Additional parameters: Including sea surface salinity, turbidity, or fluorescence line height could enhance water type discrimination
Future work priorities:
Extend analysis to other ocean basins for method generalization
Incorporate in-situ validation data from research cruises and Argo floats
Develop operational products for near-real-time water type mapping
Investigate machine learning approaches for temporal prediction of water type transitions
The framework established here provides a foundation for automated ocean water type classification from Earth observation data, with potential applications in operational oceanography, ecosystem monitoring, and climate change impact assessment.
Societal Context ¶
Understanding marine ecosystems
Monitoring water quality
Supporting climate and fisheries research by mapping productive zones
Import Libraries ¶
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import os
import shapely.geometry
import xarray as xr
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from IPython.display import JSON, display, HTML
import joblib
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import xcube_cmems
from xcube.core.store import (
find_data_store_extensions,
get_data_store_params_schema,
new_data_store,
)
import pandas as pdData sources ¶
The table below shows the data products used with links to description, access source and classification attributes.
df = pd.DataFrame({
"Datacube name": ['CMEMS', 'CMEMS', 'CMEMS', 'CMEMS', 'CMEMS'],
"Variable description": [
'<a href="https://data.marine.copernicus.eu/product/OCEANCOLOUR_MED_BGC_L4_MY_009_144/description">CHL</a>',
'<a href="https://data.marine.copernicus.eu/product/MULTIOBS_GLO_PHY_S_SURFACE_MYNRT_015_013/description">SOS</a>',
'<a href="https://data.marine.copernicus.eu/product/SEALEVEL_EUR_PHY_L4_MY_008_068/description">SLA</a>',
'<a href="https://data.marine.copernicus.eu/product/SST_MED_SST_L4_REP_OBSERVATIONS_010_021/description">SST</a>',
'<a href="https://data.marine.copernicus.eu/product/WIND_GLO_PHY_CLIMATE_L4_MY_012_003/description">Wind</a>',
],
"Data access": [
'<a href="https://data.marine.copernicus.eu/product/OCEANCOLOUR_MED_BGC_L4_MY_009_144/services">source</a>',
'<a href="https://data.marine.copernicus.eu/product/MULTIOBS_GLO_PHY_S_SURFACE_MYNRT_015_013/services">source</a>',
'<a href="https://data.marine.copernicus.eu/product/SEALEVEL_EUR_PHY_L4_MY_008_068/services">source</a>',
'<a href="https://data.marine.copernicus.eu/product/SST_MED_SST_L4_REP_OBSERVATIONS_010_021/services">source</a>',
'<a href="https://data.marine.copernicus.eu/product/WIND_GLO_PHY_CLIMATE_L4_MY_012_003/services">source</a>',
],
"Temporal extent": ['Multi-year', 'Multi-year', 'Multi-year', 'Multi-year', 'Multi-year'],
"Temporal resolution": ['Daily,Monthly', 'Daily,Monthly', 'Daily,Monthly', 'Daily', 'Monthly'],
"Spatial extent": ['Mediterranean Sea','Global','Global','Mediterranean Sea','Global'],
"Spatial resolution": ['1 × 1 km','0.125° × 0.125°','0.0625° × 0.0625°','0.05° × 0.05°','0.25° × 0.25°'],
})
display(HTML(df.to_html(escape=False, index=False)))Copernicus Marine Service data cubes CMEMS products have been accessed via xcube plugin from the CMEMS API.
Further information on the available data sources on DeepESDL with data access example notebooks can be found here.
Combining input data ¶
Loading and combining CMEMS oceanographic datasets¶
def make_combined_dataset(time_selected = ['1998-01-01', '2023-11-01'], bounds = [-6,30,36.5,46], fill_nan_value = -9999, opt=False):
cmems_store = new_data_store("cmems")
ds_bgc = cmems_store.open_data('cmems_obs-oc_med_bgc-plankton_my_l4-multi-1km_P1M',
variable_names = ['CHL'],
time_range = time_selected,
bbox = bounds)
ds_sal = cmems_store.open_data('cmems_obs-mob_glo_phy-sss_my_multi_P1M',
variable_names = ['sos'],
time_range = time_selected,
bbox = bounds)
ds_ssh = cmems_store.open_data('cmems_obs-sl_eur_phy-ssh_my_allsat-l4-duacs-0.0625deg_P1M-m',
variable_names = ['sla'],
time_range = time_selected,
bbox = bounds)
ds_sst = cmems_store.open_data('cmems_SST_MED_SST_L4_REP_OBSERVATIONS_010_021',
variable_names = ['analysed_sst'],
time_range = time_selected,
bbox = bounds)
ds_sst = ds_sst.resample(time="MS").mean()
ds_wind = cmems_store.open_data('cmems_obs-wind_glo_phy_my_l4_P1M',
variable_names = ['eastward_wind', 'northward_wind', 'eastward_stress', 'northward_stress'],
time_range = time_selected,
bbox = bounds)
ds_ssh = ds_ssh.interp(latitude = ds_sal['latitude'], longitude = ds_sal['longitude'])
ds_sst = ds_sst.interp(latitude = ds_sal['latitude'], longitude = ds_sal['longitude'])
ds_bgc = ds_bgc.interp(latitude = ds_sal['latitude'], longitude = ds_sal['longitude'])
ds_wind = ds_wind.interp(latitude = ds_sal['latitude'], longitude = ds_sal['longitude'])
if opt:
ds_combined = xr.merge([ds_bgc, ds_ssh, ds_sst, ds_wind])
else:
ds_combined = xr.merge([ds_bgc, ds_ssh, ds_sal, ds_sst, ds_wind])
return ds_combined# Defining input parameters for the combined dataset
time_selected = ['1998-01-01', '2023-11-01']
bounds = [-6,30,36.5,46]
fill_nan_value = -9999
opt=True
ds_combined = make_combined_dataset(time_selected, bounds, fill_nan_value, opt)
ds_combined_m = ds_combined.where(~ds_combined['CHL'].isnull())INFO - 2025-11-13T21:53:44Z - Selected dataset version: "202311"
INFO - 2025-11-13T21:53:44Z - Selected dataset part: "default"
WARNING - 2025-11-13T21:53:45Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.005064010620117, 45.994937896728516]
WARNING - 2025-11-13T21:53:45Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-5.9935760498046875, 36.49357604980469]
WARNING - 2025-11-13T21:53:45Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.005064010620117, 45.994937896728516]
WARNING - 2025-11-13T21:53:45Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-5.9935760498046875, 36.49357604980469]
INFO - 2025-11-13T21:53:46Z - Selected dataset version: "202311"
INFO - 2025-11-13T21:53:46Z - Selected dataset part: "default"
INFO - 2025-11-13T21:53:47Z - Selected dataset version: "202411"
INFO - 2025-11-13T21:53:47Z - Selected dataset part: "default"
INFO - 2025-11-13T21:53:48Z - Selected dataset version: "202411"
INFO - 2025-11-13T21:53:48Z - Selected dataset part: "default"
WARNING - 2025-11-13T21:53:48Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.125, 46.025001525878906]
WARNING - 2025-11-13T21:53:48Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-18.125, 36.32500076293945]
WARNING - 2025-11-13T21:53:48Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.125, 46.025001525878906]
WARNING - 2025-11-13T21:53:48Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-18.125, 36.32500076293945]
INFO - 2025-11-13T21:53:50Z - Selected dataset version: "202411"
INFO - 2025-11-13T21:53:50Z - Selected dataset part: "default"
Visualizing input data ¶
Visualizing oceanographic input variables¶
def plot_geo_input(
ax, lon, lat, data,
*,
projection=ccrs.PlateCarree(),
cmap="viridis",
shading="auto",
add_gridlines=True,
gridlines_kwargs=None,
coastline_kwargs=None,
colorbar=True,
cbar_label="",
title="",
vmin=None,
vmax=None,
):
# colormesh plot
pcm = ax.pcolormesh(
lon,
lat,
data,
transform=projection,
cmap=cmap,
shading=shading,
vmin=vmin,
vmax=vmax,
)
# coastlines
if coastline_kwargs is None:
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.LAKES)
ax.coastlines()
else:
extra = coastline_kwargs.get("extra_features", [])
for item in extra:
if isinstance(item, tuple):
feature, feat_kwargs = item
else:
feature, feat_kwargs = item, {}
ax.add_feature(feature, **feat_kwargs)
ax.coastlines(linewidth=0.7)
# gridlines
if add_gridlines:
if gridlines_kwargs is None:
gridlines_kwargs = dict(draw_labels=True, linestyle="--", linewidth=0.5)
gl = ax.gridlines(crs=projection, **gridlines_kwargs)
gl.top_labels = False
gl.right_labels = False
# colorbar
cbar = None
if colorbar:
cbar = plt.colorbar(pcm, ax=ax, orientation="horizontal", pad=0.1, aspect=50)
if cbar_label:
cbar.set_label(cbar_label)
# title
if title:
dt_ = datetime.strptime(title, "%Y-%m-%d")
ax.set_title(dt_.strftime("%B - %Y"), weight='bold')
return pcm, cbar# --- Inputs ---
lon_ = ds_combined.longitude
lat_ = ds_combined.latitude
time_1 = '2000-01-01' # January
time_2 = '2000-08-01' # AugustChlorophyll-a concentrations¶
fig, axes = plt.subplots(1, 2, figsize=(15, 8),subplot_kw=dict(projection=ccrs.Mercator()))
# Inputs
var_ = ds_combined['CHL']
vmax = .5
cbar_label = r"Concentration of Chlorophyll-a [$\mathrm{mg}\,\cdot\,\mathrm{m}^{-3}$]"
# ---
plot_geo_input(axes[0],lon_, lat_,var_.sel(time=time_1), title=time_1,cbar_label=cbar_label,vmax=vmax)
plot_geo_input(axes[1],lon_, lat_,var_.sel(time=time_2), title=time_2,cbar_label=cbar_label,vmax=vmax)
plt.savefig('Chl-a_concentrations.png', dpi=300, bbox_inches="tight")
plt.show()
Sea Surface Height (SSH)¶
fig, axes = plt.subplots(1, 2, figsize=(15, 8),subplot_kw=dict(projection=ccrs.Mercator()))
# Inputs
var_ = ds_combined['sla']
vmin = min(var_.sel(time=time_1).min().compute().item(), var_.sel(time=time_2).min().compute().item())
vmax = max(var_.sel(time=time_1).max().compute().item(), var_.sel(time=time_2).max().compute().item())
cmap='magma'
cbar_label = r"Sea Surface Height [m]"
# ---
plot_geo_input(axes[0],lon_, lat_,var_.sel(time=time_1),cmap=cmap,title=time_1,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plot_geo_input(axes[1],lon_, lat_,var_.sel(time=time_2), cmap=cmap,title=time_2,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plt.savefig('Sea_Surface_Height.png', dpi=300, bbox_inches="tight")
plt.show()
Sea Surface Temperature (SST)¶
fig, axes = plt.subplots(1, 2, figsize=(15, 8),subplot_kw=dict(projection=ccrs.Mercator()))
# Inputs
var_ = ds_combined['analysed_sst']
vmin = min(var_.sel(time=time_1).min().compute().item(), var_.sel(time=time_2).min().compute().item())
vmax = max(var_.sel(time=time_1).max().compute().item(), var_.sel(time=time_2).max().compute().item())
cmap='coolwarm'
cbar_label = r"Sea Surface Temperature [K]"
# ---
plot_geo_input(axes[0],lon_, lat_,var_.sel(time=time_1),cmap=cmap,title=time_1,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plot_geo_input(axes[1],lon_, lat_,var_.sel(time=time_2), cmap=cmap,title=time_2,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plt.savefig('Sea_Surface_Temperature.png', dpi=300, bbox_inches="tight")
plt.show()
Eastward Wind component¶
fig, axes = plt.subplots(1, 2, figsize=(15, 8),subplot_kw=dict(projection=ccrs.Mercator()))
# Inputs
var_ = ds_combined['eastward_wind']
feat_ = {"extra_features": [(cfeature.LAND, {"zorder": 1}),(cfeature.RIVERS),(cfeature.LAKES)]}
vmin = min(var_.sel(time=time_1).min().compute().item(), var_.sel(time=time_2).min().compute().item())
vmax = max(var_.sel(time=time_1).max().compute().item(), var_.sel(time=time_2).max().compute().item())
cmap='PiYG'
cbar_label = r"Eastward wind at 10 m [$\mathrm{m}\,\cdot\,\mathrm{s}^{-1}$]"
# ---
plot_geo_input(axes[0],lon_, lat_,var_.sel(time=time_1),cmap=cmap,coastline_kwargs=feat_,title=time_1,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plot_geo_input(axes[1],lon_, lat_,var_.sel(time=time_2),cmap=cmap,coastline_kwargs=feat_,title=time_2,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plt.savefig('EastwardWind.png', dpi=300, bbox_inches="tight")
plt.show()
Northward Wind component¶
fig, axes = plt.subplots(1, 2, figsize=(15, 8),subplot_kw=dict(projection=ccrs.Mercator()))
# Inputs
var_ = ds_combined['northward_wind']
feat_ = {"extra_features": [(cfeature.LAND, {"zorder": 1}),(cfeature.RIVERS),(cfeature.LAKES)]}
vmin = min(var_.sel(time=time_1).min().compute().item(), var_.sel(time=time_2).min().compute().item())
vmax = max(var_.sel(time=time_1).max().compute().item(), var_.sel(time=time_2).max().compute().item())
cmap='PiYG'
cbar_label = r"Northward wind at 10 m [$\mathrm{m}\,\cdot\,\mathrm{s}^{-1}$]"
# ---
plot_geo_input(axes[0],lon_, lat_,var_.sel(time=time_1),cmap=cmap,coastline_kwargs=feat_,title=time_1,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plot_geo_input(axes[1],lon_, lat_,var_.sel(time=time_2),cmap=cmap,coastline_kwargs=feat_,title=time_2,cbar_label=cbar_label,vmin=vmin,vmax=vmax)
plt.savefig('NorthwardWind.png', dpi=300, bbox_inches="tight")
plt.show()
Analysis ¶
Utility functions ¶
Normalizing input variables¶
def normalise(variable_array):
scaler = StandardScaler()
scaler.fit(variable_array)
norm_data = scaler.transform(variable_array)
return norm_dataExtracting and normalizing monthly oceanographic variable¶
def get_month_variables(ds_combined, mth, fill_nan_value = -9999):
#ds_combined= ds_combined.sel(depth=0)
ds_months = ds_combined.groupby('time.month').mean()
ds_m = ds_months.sel(month=mth)
ds_vars = [i for i in ds_months.data_vars]
for i,var in enumerate(ds_vars):
var_2d = ds_m[f'{var}'].values
var_2d_n = normalise(var_2d)
var_f = var_2d_n[5:-5,5:-5].flatten()
if i ==0:
var_all = var_f
else:
var_all = np.vstack((var_all, var_f))
var_all_t = np.transpose(var_all)
var_all_t_mask = np.where(np.isfinite(var_all_t), var_all_t, fill_nan_value)
return var_all_t_maskAveraging and normalizing oceanographic variable¶
def get_average_variables(ds_combined, fill_nan_value = -9999, opt = False):
if opt:
ds_av = ds_combined.groupby('time.day').mean()
ds_av = ds_av.sel(day=1)
else:
ds_combined= ds_combined.sel(depth=0)
ds_av = ds_combined.mean()
ds_vars = [i for i in ds_av.data_vars]
for i,var in enumerate(ds_vars):
var_2d = ds_av[f'{var}'].values
var_2d_n = normalise(var_2d)
var_f = var_2d_n[5:-5,5:-5].flatten()
if i ==0:
var_all = var_f
else:
var_all = np.vstack((var_all, var_f))
var_all_t = np.transpose(var_all)
var_all_t_mask = np.where(np.isfinite(var_all_t), var_all_t, fill_nan_value)
return var_all_t_maskFinding the optimal number of clusters (optimization technique: Elbow Method)¶
def test_number_of_clusters(variables, n_max, random_state):
out = []
for i in range(3,n_max):
kmeans = KMeans(n_clusters=i, random_state=random_state)
labels = kmeans.fit_predict(variables)
out.append(kmeans.inertia_)
plt.plot(np.arange(3, n_max), out)
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.title('Optimal number of clusters\nElbow method')
return outConverting cluster assignments to Geo-DataArray¶
def masking_labels(labels):
cluster_map = labels
cluster_map = cluster_map.reshape(len(ds_combined_m.latitude[5:-5]), len(ds_combined_m.longitude[5:-5]))
da_clusters = xr.DataArray(
cluster_map,
coords={"latitude": ds_combined_m.latitude[5:-5], "longitude": ds_combined_m.longitude[5:-5]},
dims=("latitude", "longitude")
)
return da_clustersProcessing seasonal climatology variables by month¶
def get_month_variables_seasonal_avg(ds_combined_seasonally_all_yrs_avg, mth, fill_nan_value = -9999):
ds_combined_seasonally_all_yrs_avg = ds_combined_seasonally_all_yrs_avg.sel(depth=0)
ds_months = ds_combined_seasonally_all_yrs_avg
ds_m = ds_months.sel(month=mth)
ds_vars = [i for i in ds_months.data_vars]
for i,var in enumerate(ds_vars):
var_2d = ds_m[f'{var}'].values
var_2d_n = normalise(var_2d)
var_f = var_2d_n[5:-5,5:-5].flatten() # remove the border because getting weird edge effects, then flatten
if i ==0:
var_all = var_f
else:
var_all = np.vstack((var_all, var_f))
var_all_t = np.transpose(var_all)
var_all_t_mask = np.where(np.isfinite(var_all_t), var_all_t, fill_nan_value)
return var_all_t_maskConverting Geo-DataArray to csv¶
def xarr_to_csv(xarray_name, xarray_ds):
df_ = xarray_ds.to_dataframe(name=xarray_name).reset_index()
csv_path = f"{xarray_name}.csv"
df_.to_csv(csv_path, index=False)
return csv_path
def csv_to_xarray(csv_path, xarray_name):
df_ = pd.read_csv(csv_path)
xarray_ = (df_.set_index(["latitude", "longitude"]).to_xarray()[xarray_name])
return xarray_K-means implementation ¶
Finding the optimal number of clusters¶
variables_av = get_average_variables(ds_combined_m, fill_nan_value, opt)
np.savetxt('variables_all_masked.txt', variables_av)
variables_av = np.loadtxt('variables_all_masked.txt')
# Plotting Inertia against the number of clusters to find the optimal value
max_clusters = 15 # maximum number of clusters to be tested
random_state = 10 # setting <random state> for results reproducibility
elbow = test_number_of_clusters(variables_av, max_clusters, random_state)/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count

By looking at the graph, the Elbow point is at 5. However, 8 has been chosen since 5, 6 and 7 clusters led to only two water types (coastal and open).
opt_clusters = 8 # optimal number of clusters
random_state = 10 # setting <random state> for results reproducibility
kmeans = KMeans(n_clusters=opt_clusters, random_state=random_state)
labels = kmeans.fit_predict(variables_av)
joblib.dump(kmeans, 'kmeans.joblib')
joblib.dump(labels, 'labels.joblib')['labels.joblib']Monthly clustering ¶
Extracting monthly variables from the combined dataset¶
variables_8 = get_month_variables(ds_combined_m, 8) # August
variables_1 = get_month_variables(ds_combined_m, 1) # January/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
Applying K-means clustering to monthly variables¶
# Loading clusters centroids and labels
kmeans = joblib.load('kmeans.joblib')
labels = joblib.load('labels.joblib')
labels_8 = kmeans.predict(variables_8)
labels_1 = kmeans.predict(variables_1)
da_8 = masking_labels(labels_8)
da_1 = masking_labels(labels_1)
jan = da_1.values
aug = da_8.valuesVisualization of monthly clusters¶
fig = plt.figure(figsize=(15, 17))
ax = fig.add_subplot(121, projection=ccrs.PlateCarree())
ax.coastlines(zorder=4)
ax.add_feature(cfeature.LAKES, zorder=3)
ax.add_feature(cfeature.RIVERS, zorder=3)
pc = ax.pcolormesh(da_1.longitude,da_1.latitude, da_1, cmap='Accent')
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc, ax=ax, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax.set_title('January', fontsize=16, weight='bold')
ax = fig.add_subplot(122, projection=ccrs.PlateCarree())
pc2 = ax.pcolormesh(da_8.longitude,da_8.latitude,da_8, cmap='Accent', zorder=2)
ax.coastlines(zorder=4)
ax.add_feature(cfeature.LAKES, zorder=3)
ax.add_feature(cfeature.RIVERS, zorder=3)
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc2, ax=ax, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax.set_title('August', fontsize=16, weight='bold')
plt.tight_layout()
plt.savefig('JanuaryAugust_clustering.png',bbox_inches='tight')
plt.show()
fig = plt.figure(figsize=(15,6))
ax = plt.axes(projection = ccrs.PlateCarree())
ax.coastlines(zorder=4)
ax.add_feature(cfeature.LAND, zorder=2)
ax.add_feature(cfeature.LAKES, zorder=3)
ax.add_feature(cfeature.RIVERS, zorder=3)
ax.add_feature(cfeature.OCEAN)
pc3 = ax.pcolormesh(da_8.longitude, da_8.latitude, da_8 - da_1, cmap='bwr', zorder=1)
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--', zorder=5)
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
plt.colorbar(pc3, ax=ax, label = 'Cluster Difference', pad=0.10, shrink=0.8, )
ax.set_title('Cluster differences', fontsize=16, weight='bold')
plt.tight_layout()
plt.savefig('JanuaryAugust_ClusterDifferences.png',bbox_inches='tight')
plt.show()

Seasonal clustering ¶
Extracting seasonal variables from the combined dataset¶
# Input parameters
time_selected = ['1998-01-01', '2023-11-01']
bounds = [-6,30,36.5,46]
fill_nan_value = -9999
opt = False
# Extracting seasonal values from the combined dataset
ds_combined = make_combined_dataset(time_selected, bounds, fill_nan_value, opt)
ds_combined_m = ds_combined.where(~ds_combined['CHL'].isnull())
ds_combined_seasonally = ds_combined_m.resample(time="QS-DEC").mean()
ds_combined_seasonally_all_yrs_avg = ds_combined_seasonally.groupby('time.month').mean()
ds_combined_seasonally_all_yrs_avg = ds_combined_seasonally_all_yrs_avg.drop_vars('sos')
variables_DJF = get_month_variables_seasonal_avg(ds_combined_seasonally_all_yrs_avg, 12)
variables_MAM = get_month_variables_seasonal_avg(ds_combined_seasonally_all_yrs_avg, 3)
variables_JJA = get_month_variables_seasonal_avg(ds_combined_seasonally_all_yrs_avg, 6)
variables_SON = get_month_variables_seasonal_avg(ds_combined_seasonally_all_yrs_avg, 9)INFO - 2025-11-11T14:49:33Z - Selected dataset version: "202311"
INFO - 2025-11-11T14:49:33Z - Selected dataset part: "default"
WARNING - 2025-11-11T14:49:34Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.005064010620117, 45.994937896728516]
WARNING - 2025-11-11T14:49:34Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-5.9935760498046875, 36.49357604980469]
WARNING - 2025-11-11T14:49:34Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.005064010620117, 45.994937896728516]
WARNING - 2025-11-11T14:49:34Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-5.9935760498046875, 36.49357604980469]
INFO - 2025-11-11T14:49:35Z - Selected dataset version: "202311"
INFO - 2025-11-11T14:49:35Z - Selected dataset part: "default"
INFO - 2025-11-11T14:49:36Z - Selected dataset version: "202411"
INFO - 2025-11-11T14:49:36Z - Selected dataset part: "default"
INFO - 2025-11-11T14:49:37Z - Selected dataset version: "202411"
INFO - 2025-11-11T14:49:37Z - Selected dataset part: "default"
WARNING - 2025-11-11T14:49:37Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.125, 46.025001525878906]
WARNING - 2025-11-11T14:49:37Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-18.125, 36.32500076293945]
WARNING - 2025-11-11T14:49:37Z - Some of your subset selection [30, 46] for the latitude dimension exceed the dataset coordinates [30.125, 46.025001525878906]
WARNING - 2025-11-11T14:49:37Z - Some of your subset selection [-6.0, 36.5] for the longitude dimension exceed the dataset coordinates [-18.125, 36.32500076293945]
INFO - 2025-11-11T14:49:38Z - Selected dataset version: "202411"
INFO - 2025-11-11T14:49:38Z - Selected dataset part: "default"
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1144: RuntimeWarning: invalid value encountered in divide
updated_mean = (last_sum + new_sum) / updated_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1149: RuntimeWarning: invalid value encountered in divide
T = new_sum / new_sample_count
/home/conda/users/03ab8823-1758107623-131-deepesdl-xcube-1.11.0/lib/python3.13/site-packages/sklearn/utils/extmath.py:1169: RuntimeWarning: invalid value encountered in divide
new_unnormalized_variance -= correction**2 / new_sample_count
Applying K-means clustering to seasonal variables¶
# Loading clusters centroids and labels
kmeans = joblib.load('kmeans.joblib')
labels = joblib.load('labels.joblib')
# Clusters prediction
labels_DJF = kmeans.predict(variables_DJF)
labels_MAM = kmeans.predict(variables_MAM)
labels_JJA = kmeans.predict(variables_JJA)
labels_SON = kmeans.predict(variables_SON)
da_DJF = masking_labels(labels_DJF)
da_MAM = masking_labels(labels_MAM)
da_JJA = masking_labels(labels_JJA)
da_SON = masking_labels(labels_SON)# Dumping to csv
djf_path = xarr_to_csv('DJF_clusters', da_DJF)
mam_path = xarr_to_csv('MAM_clusters', da_MAM)
jja_path = xarr_to_csv('JJA_clusters', da_JJA)
son_path = xarr_to_csv('SON_clusters', da_SON)Visualization of seasonal clusters¶
# Loading seasonal clusters
da_DJF = csv_to_xarray(djf_path, 'DJF_clusters')
da_MAM = csv_to_xarray(mam_path, 'MAM_clusters')
da_JJA = csv_to_xarray(jja_path, 'JJA_clusters')
da_SON = csv_to_xarray(son_path, 'SON_clusters')
# Plotting
fig = plt.figure(figsize=(15, 17))
#fig.suptitle('Seasonal cycle of clusters', y=0.6, fontsize=23)
ax = fig.add_subplot(121, projection=ccrs.PlateCarree())
ax.coastlines(zorder=4)
ax.add_feature(cfeature.LAKES, zorder=3)
ax.add_feature(cfeature.RIVERS, zorder=3)
pc = ax.pcolormesh(da_DJF.longitude,da_DJF.latitude, da_DJF, cmap='Accent')
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc, ax=ax, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax.set_title('DJF', fontsize=16, weight='bold')
ax2 = fig.add_subplot(122, projection=ccrs.PlateCarree())
pc2 = ax2.pcolormesh(da_MAM.longitude,da_MAM.latitude,da_MAM, cmap='Accent', zorder=2)
ax2.coastlines(zorder=4)
ax2.add_feature(cfeature.LAKES, zorder=3)
ax2.add_feature(cfeature.RIVERS, zorder=3)
gl = ax2.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc2, ax=ax2, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax2.set_title('MAM', fontsize=16, weight='bold')
plt.tight_layout()
plt.savefig('Seasonal_clustering_DJF-MAM.png',bbox_inches='tight')
#plt.show()
fig = plt.figure(figsize=(15, 17))
ax = fig.add_subplot(121, projection=ccrs.PlateCarree())
ax.coastlines(zorder=4)
ax.add_feature(cfeature.LAKES, zorder=3)
ax.add_feature(cfeature.RIVERS, zorder=3)
pc = ax.pcolormesh(da_JJA.longitude,da_JJA.latitude, da_JJA, cmap='Accent')
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc, ax=ax, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax.set_title('JJA', fontsize=16, weight='bold')
ax2 = fig.add_subplot(122, projection=ccrs.PlateCarree())
pc2 = ax2.pcolormesh(da_SON.longitude,da_SON.latitude,da_SON, cmap='Accent', zorder=2)
ax2.coastlines(zorder=4)
ax2.add_feature(cfeature.LAKES, zorder=3)
ax2.add_feature(cfeature.RIVERS, zorder=3)
gl = ax2.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='k', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
cbar = plt.colorbar(pc2, ax=ax2, label='Cluster', pad=0.15, shrink=0.15)
cbar.set_ticks(np.arange(0,8,1))
ax2.set_title('SON', fontsize=16, weight='bold')
plt.tight_layout()
plt.savefig('Seasonal_clustering_JJA-SON.png',bbox_inches='tight')
plt.show()

Cluster 1 (violet) - Eutrophic Water: - Colder waters - Eastward Winds - Medium Chlorophyll-a content
Cluster 2 (orange) - Coastal Water: - Very high Chlorophyll-a - Sea Surface Height
Cluster 7 (grey) - Oligotrophic Water: - Warmer waters - Northward wind and wind stress - Low Chlorophyll-a Conten
Percentage change of seasonal clusters¶
DJF_1 = sum(sum(da_DJF == 1))
DJF_2 = sum(sum(da_DJF == 2))
DJF_7 = sum(sum(da_DJF == 7))
MAM_1 = sum(sum(da_MAM == 1))
MAM_2 = sum(sum(da_MAM == 2))
MAM_7 = sum(sum(da_MAM == 7))
JJA_1 = sum(sum(da_JJA == 1))
JJA_2 = sum(sum(da_JJA == 2))
JJA_7 = sum(sum(da_JJA == 7))
SON_1 = sum(sum(da_SON == 1))
SON_2 = sum(sum(da_SON == 2))
SON_7 = sum(sum(da_SON == 7))cluster_1 = [(JJA_1-JJA_1)/JJA_1, (SON_1-JJA_1)/JJA_1, (DJF_1-JJA_1)/JJA_1, (MAM_1-JJA_1)/JJA_1]
cluster_2 = [(JJA_2-JJA_2)/JJA_2, (SON_2-JJA_2)/JJA_2, (DJF_2-JJA_2)/JJA_2, (MAM_2-JJA_2)/JJA_2]
cluster_7 = [(JJA_7-JJA_7)/JJA_7, (SON_7-JJA_7)/JJA_7, (DJF_7-JJA_7)/JJA_7, (MAM_7-JJA_7)/JJA_7]# Plotting results
fig = plt.figure(figsize = (12,4))
fig.suptitle('Seasonal cycle of clusters\nPercentage Change', y=1, fontsize=15)
plt.plot(cluster_1, label = 'Cluster 1 - Eutrophic Water', color = 'tab:purple')
plt.plot(cluster_2, label = 'Cluster 2 - Coastal Water', color = 'tab:orange')
plt.plot(cluster_7, label = 'Cluster 7 - Oligotrophic Water', color = 'tab:gray')
plt.xticks([0,1,2,3], ['Summer','Autumn','Winter','Spring'])
plt.ylabel('Percentage Change')
plt.legend(loc='lower left', fontsize='small')
plt.savefig('SeasonalClusters_percentage-change.png')
plt.show()