303.5. Galaxy morphology clustering#
303.5. Galaxy morphology clustering¶
For the Rubin Science Platform at data.lsst.cloud.
Data Release: Data Preview 2
Container Size: Large
LSST Science Pipelines version: r30.0.11
Last verified to run: 2026-10-26
Repository: github.com/lsst/tutorial-notebooks
DOI: 10.11578/rubin/dc.20250909.20
Learning objective: Use unsupervised Gaussian Mixture Model clustering to find structure in DP2 galaxy morphological and photometric measurements, with no external classification catalog involved in training.
LSST data products: Object table, object_photoz (LSDB)
Packages: lsst.rsp, lsdb, astroquery, astropy.cosmology, scikit-learn, numpy, pandas, matplotlib
Credit:
Originally developed by the Rubin Community Science team.
Photometric redshifts from DP2's own object_photoz catalog (see the 310-series tutorials on photometric redshifts).
The optional validation in Section 8 uses morphological classifications from Tasca et al. 2009, A&A, 503, 379 (VizieR catalog VII/265).
Please consider acknowledging them if this notebook is used for the preparation of journal articles, software releases, or other notebooks.
Get Support: Everyone is encouraged to ask questions or raise issues in the Support Category of the Rubin Community Forum. Rubin staff will respond to all questions posted there.
1. Introduction¶
The previous notebook in this series trains a neural network to classify galaxies as early- or late-type using morphological labels from an external, independent catalog. That approach needs a labeled training set, which is not available for most of the sky. This notebook takes a complementary approach: cluster DP2 galaxies in an unsupervised way, using only their own measurements, and see what structure emerges without using any external classification at all.
The target result is a well-known one in galaxy evolution: the color-magnitude bimodality between the "red sequence" (quiescent, typically early-type galaxies) and the "blue cloud" (star-forming, typically late-type galaxies). This bimodality is one of the most robust results in extragalactic astronomy, discovered from large photometric surveys and reproduced in essentially every large survey since. Cluster DP2 galaxies using a Gaussian Mixture Model (GMM), a probabilistic clustering algorithm from scikit-learn, and see whether it recovers this structure directly from the data.
1.1. Import packages¶
Import common scientific analysis packages numpy, pandas, and matplotlib.
Import LSST Science Pipelines package utilities for remote data access, lsst.rsp, and lsst.utils.plotting for the standard Rubin plot style.
Import lsdb and upath to access DP2's native photometric redshift catalog, and astroquery to cross-match against the external Tasca et al. 2009 morphology catalog in Section 8.
Import astropy.cosmology to convert angular and apparent measurements to physical units, and scikit-learn utilities for standardising features and fitting the clustering model.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lsdb
from upath import UPath
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.cosmology import Planck18 as cosmo
from astroquery.vizier import Vizier
from sklearn.preprocessing import StandardScaler
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
from lsst.rsp import RSPDiscovery
from lsst.utils.plotting import set_rubin_plotstyle
set_rubin_plotstyle()
plt.rcParams["figure.dpi"] = 150
np.random.seed(1)
1.2. Define parameters and functions¶
Set up the TAP service client used for data access throughout the notebook, and the sky position of the COSMOS field used for every query and cross-match below.
discovery = RSPDiscovery("dp2")
tap_service = discovery.get_tap_client()
field_centre = SkyCoord(ra=150.1, dec=2.2, unit="deg")
Define a helper function to query VizieR, cycling through known mirrors of the service in case the primary server is unreachable.
VIZIER_MIRRORS = [
"vizier.cds.unistra.fr", "vizier.cfa.harvard.edu",
"vizier.china-vo.org", "vizier.idia.ac.za", "vizier.nao.ac.jp",
]
def query_vizier(columns, catalog, *region_args, **region_kwargs):
"""Query VizieR, trying each known mirror in turn."""
errors = []
for server in VIZIER_MIRRORS:
survey = Vizier(columns=columns, catalog=catalog, row_limit=-1, vizier_server=server)
try:
return survey.query_region(*region_args, catalog=catalog, **region_kwargs)[0]
except Exception as error:
errors.append(f"{server}: {error}")
details = " | ".join(errors)
raise RuntimeError(
"Could not reach VizieR on any known mirror. This may be a wider CDS "
f"outage, so try again later. Details: {details}") from None
2. Query for galaxy measurements in the COSMOS field¶
Query the Object table in a 0.8 degree radius around the COSMOS field centre for a clean sample of resolved galaxies with well-measured Sersic fits. Require refExtendedness = 1 to exclude point sources (stars) from the sample before any cross-matching happens. Include objectId, needed to join against the photometric redshift catalog in Section 3. Select the measurements that make up the feature vector used throughout this notebook:
sersic_index: the shape parameter of the single-component Sersic profile fit, with n = 4 corresponding to a de Vaucouleurs profile (centrally concentrated, typical of early-type galaxies) and n = 1 to an exponential profile (typical of disks).sersic_reff_major,sersic_reff_minor: the semi-major and semi-minor axis effective (half-light) radii from the same Sersic fit, in arcsec. Their ratio gives the apparent ellipticity.i_cModelMag: the i-band CModel (composite de Vaucouleurs + exponential) apparent magnitude, used as the total brightness.g_cModelMag - r_cModelMag,r_cModelMag - i_cModelMag: the g-r and r-i colors, from the same CModel photometry.
Although the Tasca et al. 2009 catalog is only used to verify the result, apply the same flux limit (I(AB) <= 23) so that this notebook operates on an identical underlying sample to the one used in the previous tutorial.
query = '''SELECT objectId, coord_ra, coord_dec, sersic_index, sersic_reff_major,
sersic_reff_minor, i_cModelMag, g_cModelMag - r_cModelMag AS g_minus_r,
r_cModelMag - i_cModelMag AS r_minus_i
FROM dp2.Object
WHERE CONTAINS(POINT('ICRS', coord_ra, coord_dec), CIRCLE('ICRS', 150.1, 2.2, 0.8))=1
AND refExtendedness = 1
AND i_cModel_flag = 0
AND g_cModel_flag = 0
AND r_cModel_flag = 0
AND g_cModelFlux/g_cModelFluxErr > 10
AND r_cModelFlux/r_cModelFluxErr > 10
AND i_cModelFlux/i_cModelFluxErr > 10
AND i_cModelMag < 23
AND sersic_unknown_flag = 0
AND sersic_no_data_flag = 0
'''
job = tap_service.submit_job(query)
job.run()
job.wait(phases=["COMPLETED", "ERROR"])
assert job.phase == "COMPLETED"
dp2_tab = job.fetch_result().to_table()
job.delete()
print(f"Retrieved {len(dp2_tab)} DP2 objects")
Retrieved 69157 DP2 objects
3. Join against DP2's photometric redshift catalog, and convert to rest-frame physical quantities¶
As in 303.4: the Sersic effective radius and apparent magnitude are observed-frame quantities that depend on distance as well as on a galaxy's true physical size and luminosity. DP2's photometric redshifts are found in a separate, LSDB-formatted catalog, object_photoz. Open it with lsdb, restrict it to the same field with a cone search, and join it to the Object query above on objectId. Use the FlexZBoost estimator's point estimate, fzboost_z_best, with fzboost_z_err68_low/fzboost_z_err68_high giving its 68% confidence interval. Also require z < 0.5, so that galaxies are well-resolved at DP2's angular resolution.
dp2 = dp2_tab.to_pandas()
dp2_renamed = dp2.rename(columns={"coord_ra": "ra", "coord_dec": "dec"})
dp2_lsdb = lsdb.from_dataframe(dp2_renamed, catalog_name="object")
base_path = UPath("/rubin/lsdb_data/dp2")
pz_cat = lsdb.open_catalog(
base_path / "object_photoz",
columns=["objectId", "ra", "dec", "fzboost_z_best", "fzboost_z_err68_low",
"fzboost_z_err68_high"])
pz_cat_cone = pz_cat.cone_search(
ra=field_centre.ra.deg, dec=field_centre.dec.deg, radius_arcsec=0.8 * 3600.0)
joined = pz_cat_cone.join(
dp2_lsdb, left_on="objectId", right_on="objectId", suffix_method="all_columns")
dpz = pd.DataFrame(joined.compute())
assert len(dpz) > 0, "FlexZBoost photometric redshift join returned no rows"
print(f"Joined {len(dpz)} DP2 objects with a FlexZBoost photometric redshift")
Joined 69157 DP2 objects with a FlexZBoost photometric redshift
Rename the joined columns back to their original names, cast them to a consistent numeric type, and keep only objects with a good-quality redshift (a narrow 68% confidence interval relative to (1 + z)) below 0.5.
dpz = dpz.rename(columns={
"fzboost_z_best_object_photoz": "zphot", "fzboost_z_err68_low_object_photoz": "z_lo",
"fzboost_z_err68_high_object_photoz": "z_hi", "objectId_object": "objectId",
"sersic_index_object": "sersic_index", "sersic_reff_major_object": "sersic_reff_major",
"sersic_reff_minor_object": "sersic_reff_minor", "i_cModelMag_object": "i_cModelMag",
"g_minus_r_object": "g_minus_r", "r_minus_i_object": "r_minus_i",
"ra_object": "coord_ra", "dec_object": "coord_dec",
})
numeric_cols = ["zphot", "z_lo", "z_hi", "sersic_index", "sersic_reff_major",
"sersic_reff_minor", "i_cModelMag", "g_minus_r", "r_minus_i",
"coord_ra", "coord_dec"]
dpz[numeric_cols] = dpz[numeric_cols].astype("float64")
has_good_z = (dpz["zphot"] > 0.01) & dpz["z_lo"].notna() & dpz["z_hi"].notna()
z_confidence_interval = (dpz["z_hi"] - dpz["z_lo"]) / (1 + dpz["zphot"])
dpz = dpz[has_good_z & (z_confidence_interval < 0.1) & (dpz["zphot"] < 0.5)].reset_index(drop=True)
print(f"DP2 galaxies with a good-quality photometric redshift below 0.5: {len(dpz)}")
DP2 galaxies with a good-quality photometric redshift below 0.5: 24894
Convert the Sersic effective radius (arcsec) to a physical effective radius (kpc) using the angular diameter distance, and the apparent i-band magnitude to an absolute magnitude using the distance modulus, both evaluated at each galaxy's photometric redshift. Use a flat $\Lambda$CDM cosmology (Planck Collaboration 2018).
Warning:
sersic_reff_majorandsersic_reff_minorin theObjecttable are too small by a factor of $2\ln(2) \approx 1.386$; the cell below corrects for this before computingreff_kpcandellipticity(see the DP2 known issues documentation).
sersic_reff_correction = 2 * np.log(2)
dpz["sersic_reff_major"] = dpz["sersic_reff_major"] * sersic_reff_correction
dpz["sersic_reff_minor"] = dpz["sersic_reff_minor"] * sersic_reff_correction
kpc_per_arcsec = cosmo.kpc_proper_per_arcmin(dpz["zphot"].values).to(u.kpc / u.arcsec).value
dpz["reff_kpc"] = dpz["sersic_reff_major"] * kpc_per_arcsec
distance_modulus = cosmo.distmod(dpz["zphot"].values).value
dpz["abs_mag_i"] = dpz["i_cModelMag"] - distance_modulus
reff_major = dpz["sersic_reff_major"]
reff_minor = dpz["sersic_reff_minor"]
dpz["ellipticity"] = (reff_major - reff_minor) / (reff_major + reff_minor)
feature_cols = ["sersic_index", "reff_kpc", "ellipticity", "abs_mag_i", "g_minus_r", "r_minus_i"]
4. Standardise the features¶
Gaussian Mixture Models, like most distance-based algorithms, are sensitive to the relative scale of the input features. Use scikit-learn's StandardScaler to rescale every feature to zero mean and unit variance.
X = dpz[feature_cols].values
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
5. Choose the number of clusters¶
A GMM needs the number of clusters (components) fixed in advance. Use the silhouette score, a measure of how well-separated and internally compact the resulting clusters are, with values closer to 1 indicating a cleaner separation. Fit a GMM for a range of cluster counts and compare. Use several random initialisations (n_init) for each fit, since GMM optimisation can converge to different local optima depending on the starting point.
cluster_range = range(2, 8)
silhouette_scores = []
rng = np.random.RandomState(0)
subsample_idx = rng.choice(len(X_scaled), size=3000, replace=False)
for n_clusters in cluster_range:
gmm = GaussianMixture(
n_components=n_clusters, covariance_type="full",
random_state=1, n_init=10, reg_covar=1e-3)
cluster_labels = gmm.fit_predict(X_scaled)
silhouette_scores.append(
silhouette_score(X_scaled[subsample_idx], cluster_labels[subsample_idx]))
print("clusters, silhouette")
for n_clusters, sil in zip(cluster_range, silhouette_scores):
print(f"{n_clusters}, {sil: .3f}")
clusters, silhouette 2, 0.250 3, 0.196 4, 0.167 5, 0.123 6, 0.141 7, 0.085
Plot the silhouette score against the number of clusters to identify the best-supported choice.
plt.figure(figsize=(5, 4), layout="constrained")
plt.plot(list(cluster_range), silhouette_scores, marker="o", color="k")
plt.xlabel("number of clusters")
plt.ylabel("silhouette score")
plt.grid(True, alpha=0.3)
Figure: Silhouette score as a function of the number of GMM components, peaking sharply at 2 clusters.
The silhouette score peaks at 2 clusters: that is where the clustering is most cleanly separated and internally consistent. Combined with the physical expectation of a red sequence/blue cloud bimodality, 2 clusters is both the best-supported and the most interpretable choice, so use that for the rest of this notebook.
6. Fit the final model and inspect the clusters¶
Fit the 2-component GMM. A GMM gives a membership probability for each cluster. Keep the probability of the more likely cluster as a per-galaxy confidence score alongside the cluster label itself.
gmm = GaussianMixture(
n_components=2, covariance_type="full", random_state=1, n_init=10, reg_covar=1e-3)
dpz["cluster"] = gmm.fit_predict(X_scaled)
dpz["confidence"] = gmm.predict_proba(X_scaled).max(axis=1)
print(dpz.groupby("cluster")[feature_cols].mean())
print()
print(dpz["cluster"].value_counts())
sersic_index reff_kpc ellipticity abs_mag_i g_minus_r r_minus_i cluster 0 3.514167 3.820196 0.242187 -20.225704 1.100257 0.447749 1 1.055261 3.500514 0.299115 -19.381638 0.750810 0.301961 cluster 1 16747 0 8147 Name: count, dtype: int64
The two clusters differ in their mean Sersic index, size, color, and magnitude. Label them neutrally as "cluster 1" and "cluster 2" for now.
dpz["cluster_label"] = "cluster " + (dpz["cluster"] + 1).astype(str)
print(dpz["cluster_label"].value_counts())
cluster_label cluster 2 16747 cluster 1 8147 Name: count, dtype: int64
7. Visualise the clusters¶
Look at the same kind of feature-space projections used in the previous classification notebook, now colored by the unsupervised cluster assignment instead of an external label. The clustering recovers many of the same trends as the labeled galaxies in the previous notebook, including the red sequence/blue cloud bimodality in the color-magnitude panel.
fig, axes = plt.subplots(2, 2, figsize=(9, 8), layout="constrained")
axes = axes.flatten()
panels = [
("abs_mag_i", "reff_kpc", "absolute i-band magnitude", "effective radius [kpc]"),
("sersic_index", "ellipticity", "Sersic index", "ellipticity"),
("abs_mag_i", "g_minus_r", "absolute i-band magnitude", "g - r [mag]"),
("g_minus_r", "r_minus_i", "g - r [mag]", "r - i [mag]"),
]
for label, marker in [("cluster 1", "o"), ("cluster 2", "^")]:
sel = dpz["cluster_label"] == label
for ax, (xcol, ycol, xlabel, ylabel) in zip(axes, panels):
ax.scatter(dpz.loc[sel, xcol], dpz.loc[sel, ycol],
s=8, alpha=0.4, marker=marker, label=label)
for ax, (xcol, ycol, xlabel, ylabel) in zip(axes, panels):
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xlim(dpz[xcol].quantile(0.001), dpz[xcol].quantile(0.999))
ax.set_ylim(dpz[ycol].quantile(0.001), dpz[ycol].quantile(0.999))
ax.grid(True, alpha=0.3)
handles, labels = axes[0].get_legend_handles_labels()
fig.legend(handles, labels, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.05))
<matplotlib.legend.Legend at 0x7e9d94a9f230>
Figure: Feature-space projections of the sample, colored by unsupervised GMM cluster assignment.
8. Validate against an external classification¶
As an optional check, cross-match against the Tasca et al. 2009 morphological catalog (VizieR catalog VII/265) to see whether the unsupervised clusters correspond to the morphological classification. Mph1 is Tasca et al. 2009's primary classification: 1 = early-type, 2 = spiral, 3 = irregular.
Cross-match each cluster's members against Tasca et al. 2009 by sky position, and tabulate how many matched galaxies from each cluster fall into each of Tasca et al. 2009's three morphological classes. The early-type fraction is then the fraction of each cluster's Tasca-matched members that Tasca et al. 2009 independently classified as early-type.
tasca_cat = query_vizier(["**"], "VII/265", field_centre, radius=0.8 * u.deg)
assert len(tasca_cat) > 0, "Tasca et al. 2009 VizieR query returned no rows"
coord_tasca = SkyCoord(
ra=np.array(tasca_cat["RAJ2000"]), dec=np.array(tasca_cat["DEJ2000"]), unit="deg")
coord_dpz = SkyCoord(ra=dpz["coord_ra"].values, dec=dpz["coord_dec"].values, unit="deg")
idx_dpz, separation, _ = coord_tasca.match_to_catalog_sky(coord_dpz)
is_matched = np.array(separation < 1.0 * u.arcsec)
mph1 = np.array(tasca_cat["Mph1"])[is_matched]
cluster_matched = dpz["cluster_label"].values[idx_dpz[is_matched]]
confidence_matched = dpz["confidence"].values[idx_dpz[is_matched]]
is_classified = mph1 > 0
mph1_label = pd.Series(mph1[is_classified]).map({1: "early-type", 2: "spiral", 3: "irregular"})
cluster_classified = cluster_matched[is_classified]
confidence_classified = confidence_matched[is_classified]
comparison = pd.crosstab(
cluster_classified, mph1_label, rownames=["cluster"], colnames=["Tasca et al. 2009"])
print(comparison)
early_type_fraction = comparison["early-type"] / comparison.sum(axis=1)
print()
print("Early-type fraction by cluster:")
for cluster_name, fraction in early_type_fraction.items():
print(f" {cluster_name}: {fraction * 100: .1f}%")
Tasca et al. 2009 early-type irregular spiral cluster cluster 1 3778 283 2135 cluster 2 1131 2154 9847 Early-type fraction by cluster: cluster 1: 61.0% cluster 2: 8.6%
One of the two clusters contains a substantially higher fraction of Tasca et al. 2009's own early-type classifications than the other -- that is the cluster that corresponds to early-type-like galaxies, recovered with no external labels used anywhere in the clustering itself. The correspondence is not perfect: the clusters were not defined to match Tasca et al. 2009's classification scheme, they reflect whatever structure the GMM found directly in the Sersic, size, and color measurements.
8.1. Does membership confidence track agreement with the external classification?¶
If the GMM's membership probability is meaningful, the two clusters should separate more cleanly in Tasca et al. 2009's classification among high-confidence galaxies than among low-confidence ones, where the model itself is unsure which cluster a galaxy belongs to. Bin galaxies by confidence and, within each bin, plot the early-type fraction separately for each cluster, with binomial error bars: each bin's early-type fraction is the mean of a binary early-type/not label, so its standard error follows the standard binomial-proportion formula, $\sqrt{p(1-p)/n}$, with $p$ the fraction and $n$ the number of galaxies in the bin.
is_early_type = (mph1_label == "early-type").values
bins = np.linspace(0.5, 1.0, 6)
bin_centres = (bins[:-1] + bins[1:]) / 2
bin_idx = np.clip(np.digitize(confidence_classified, bins) - 1, 0, len(bin_centres) - 1)
plt.figure(figsize=(5, 4), layout="constrained")
for label, marker in [("cluster 1", "o"), ("cluster 2", "^")]:
sel = cluster_classified == label
early_fraction = np.full(len(bin_centres), np.nan)
early_err = np.full(len(bin_centres), np.nan)
for bin_num in range(len(bin_centres)):
in_bin = sel & (bin_idx == bin_num)
n_in_bin = in_bin.sum()
if n_in_bin > 0:
p = is_early_type[in_bin].mean()
early_fraction[bin_num] = p
early_err[bin_num] = np.sqrt(p * (1 - p) / n_in_bin)
plt.errorbar(bin_centres, early_fraction, yerr=early_err, marker=marker,
capsize=3, label=label)
plt.xlabel("membership confidence")
plt.ylabel("early-type fraction")
plt.ylim(0, 1.05)
plt.legend()
plt.grid(True, alpha=0.3)
Figure: Early-type fraction (Tasca et al. 2009) for each cluster, binned by GMM membership confidence. The two clusters separate more cleanly in Tasca's classification at high confidence than at low confidence.
The two lines pull apart as confidence increases: close together (both near the sample's overall early-type fraction) for the lowest-confidence galaxies, and clearly separated for the highest-confidence ones.
Summary¶
This notebook clusters DP2 galaxies with an unsupervised Gaussian Mixture Model, using the same six Sersic, size, and color features as the previous classification notebook but no external labels during fitting. The silhouette score favors two clusters, and an optional cross-match to Tasca et al. 2009 shows that one cluster is substantially enriched in early-type galaxies and that the two clusters separate more cleanly in Tasca et al. 2009's own classification at higher GMM membership confidence, indicating that the clustering is recovering real morphological structure.