Skip to content

CDiscover · discover.optics

OPTICS

Which dense regions form clusters when the data has clusters of different densities?

Orders the rows so that dense regions sit next to each other and records each row's reachability distance — the reachability plot shows every DBSCAN clustering at once (valleys are clusters). Clusters are cut at a reachability threshold, chosen automatically at the knee of the core distances or set by you, or found by the Xi method from the steepness of each valley, which handles clusters of different densities in one run. The ordering loop is the same in both engines (next row = smallest reachability, ties by row), so orders and clusters agree.

Verified in Python and R Python and R agree to 10 decimals Also called OPTICS, OPTICS Xi, ordering points to identify the clustering structure…

A real result

Example “Iris”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

OPTICSRecorded · Python and R agreeRecorded 2026-11-25 · 23 values compared
R

OPTICS with at least 8 neighbors, cut at reachability 0.9483: 2 clusters, 4 noise rows.

Clusters
2
Mean silhouette
0.5967

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
ClusterPC1 (73%)PC2 (23%)
2−2.2650.4800
2−2.081−0.6741
2−2.364−0.3419
2−2.299−0.5974
2−2.3900.6468
2−2.0761.489
2−2.4440.0476
2−2.2330.2231
2−2.335−1.115
2−2.184−0.4690
2−2.1661.044
2−2.3260.1331
2−2.218−0.7287
2−2.633−0.9615
2−2.1991.860
-1−2.2622.686
2−2.2081.484
2−2.1900.4888
2−1.8991.405
2−2.3431.128
2−1.9140.4089
2−2.2070.9241
2−2.7740.4583
2−1.8190.0856
2−2.2270.1373
2−1.952−0.6256
2−2.0510.2422
2−2.1690.5271
2−2.1400.3132
2−2.265−0.3377
2−2.140−0.5045
2−1.8320.4237
2−2.6151.794
2−2.4462.151
2−2.110−0.4602
2−2.208−0.2061
2−2.0450.6616
2−2.5270.5923
2−2.430−0.9042
2−2.1700.2689
2−2.2860.4417
-1−1.858−2.337
2−2.554−0.4791
2−1.9640.4723
2−2.1371.142
2−2.070−0.7111
2−2.3851.120
2−2.394−0.3862
2−2.2290.9980
2−2.2040.0092
11.1020.8630
10.73130.5946
11.2410.6163
10.4075−1.754
11.075−0.2084
10.3887−0.5933
10.74650.7730
1−0.4873−1.852
10.92790.0322
10.0114−1.034

First 60 of 150 rows.

Reachability plotWhere are the dense regions, at every density at once?

Valleys below the cut (0.948) are clusters; bars at the top have no reachability (start of a new region).

View data
ClusterOrderReachability distanceUndefined
211.752true
220.2663false
230.2663false
240.2663false
250.2663false
260.2663false
270.2663false
280.2663false
290.2885false
2100.2885false
2110.2885false
2120.3323false
2130.3342false
2140.3578false
2150.3578false
2160.3592false
2170.3623false
2180.3809false
2190.3976false
2200.4340false
2210.3679false
2220.3635false
2230.3635false
2240.2885false
2250.2885false
2260.2885false
2270.2885false
2280.2885false
2290.3110false
2300.3110false
2310.3530false
2320.3635false
2330.3635false
2340.4340false
2350.4340false
2360.4822false
2370.4822false
2380.4641false
2390.4641false
2400.4641false
2410.4641false
2420.4972false
2430.5041false
2440.5203false
2450.5234false
2460.6004false
2470.6630false
2480.7511false
-1490.9803false
-1501.394false
1511.668false
1520.9464false
1530.7914false
1540.7914false
1550.5367false
1560.5367false
1570.5367false
1580.5367false
1590.4535false
1600.4535false

First 60 of 150 rows.

Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
10.6740
10.6724
10.6706
10.6687
10.6673
10.6652
10.6651
10.6632
10.6577
10.6526
10.6523
10.6482
10.6455
10.6425
10.6413
10.6412
10.6410
10.6380
10.6308
10.6299
10.6292
10.6292
10.6257
10.6250
10.6211
10.6198
10.6197
10.6181
10.6168
10.6137
10.6135
10.6114
10.6052
10.6037
10.6029
10.6013
10.6004
10.5987
10.5982
10.5965
10.5952
10.5912
10.5872
10.5870
10.5863
10.5855
10.5853
10.5815
10.5783
10.5771
10.5744
10.5701
10.5661
10.5609
10.5565
10.5555
10.5539
10.5527
10.5458
10.5446

First 60 of 146 rows.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
19865.3%6.2312.8534.8721.667
24832.0%5.0023.4311.4650.2417
  • Reachability cut chosen automatically at the knee of the core distances: 0.9483.
Python

OPTICS with at least 8 neighbors, cut at reachability 0.9483: 2 clusters, 4 noise rows.

Clusters
2
Mean silhouette
0.5967

To keep this page light, the plots are shown once, under the R tab.

Clusters

ClusterSizeSharesepal_lengthsepal_widthpetal_lengthpetal_width
19865.3%6.2312.8534.8721.667
24832.0%5.0023.4311.4650.2417
  • Reachability cut chosen automatically at the knee of the core distances: 0.9483.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Regress min samples above rowsml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Irisml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Usarrests cutml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Iris ximl_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Usarrests xi smallml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Penguins mixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass · label: species

In the guides

Where it sits in the decision guides

  • Density-based clustering (DBSCAN, HDBSCAN) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Featuresnumeric / categorical / boolean · 1–200 columns
Variables that define closeness (scaled; categories as 0/1 columns).
Known groupscategorical / boolean · 0–1 column
Optional — compared with the clusters (adjusted Rand index, AMI, NMI); never used to fit.
Row labelscategorical / numeric · 0–1 column
Optional names shown on the chart points.

Choices you make

model

Minimum neighborsdefault 5

Rows needed nearby (the row itself included) to be a core point; larger = smoother, fewer clusters.

Find clusters bydefault cut

How clusters are read off the reachability plot: one horizontal cut, or from the steepness of each valley.

  • Cut at one reachability(default) — Valleys below one height become clusters, the same as DBSCAN at that distance.
  • Xi (steepness of each valley) — A cluster starts at a steep drop and ends at a matching rise, so dense and sparse clusters can both be found (Ankerst et al. 1999).
Xi (steepness)default 0.05

Relative change in reachability that counts as steep; smaller finds more, shallower clusters.

Smallest clusterdefault —

Valleys with fewer rows than this are not clusters.

Reachability cutdefault —

Valleys below this reachability become clusters — the DBSCAN eps of the extracted clustering.

Advanced

Largest neighborhooddefault —

Ignore neighbors farther than this (speeds up large tables; unlimited finds every cluster).

preprocess

Scale numbersdefault standard

Standardize numbers so each counts equally in distances; turn off only when columns already share one unit.

  • Standardize (population SD)(default) — Every variable gets equal weight.
  • No scaling — Keep the original units (only when they are comparable).
Missing valuesdefault drop

Rows with missing values are left out, or filled with the column median (categories get none).

  • Leave the row out(default) — Use complete rows only.
  • Fill with the median (categories → none) — Keep every row.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n_used
How many independent units the analysis used; it sets precision and power.
n_noise
How many independent units the analysis used; it sets precision and power.
cut
Orders rows so dense regions sit together and records reachability distances — every DBSCAN radius at once.
min_samples
Orders rows so dense regions sit together and records reachability distances — every DBSCAN radius at once.
silhouette
How well each point sits in its cluster compared with the nearest other cluster, from −1 to 1.

Per group, level or term: size[<cluster>], mean[<cluster>,<feature>], order_check, extraction, xi, min_cluster_size, calinski_harabasz, davies_bouldin, ari, ami, nmi

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy; R uses codesplashr.

Default traps between the two languages

  • Both engines run codesplash's OPTICS twin, which follows scikit-learn's ordering loop exactly (core distance = distance to the min_samples-th row including itself; next row = smallest reachability, ties by row) and its DBSCAN-equivalent extraction. dbscan::optics in R breaks reachability ties differently, so its order can differ on tied distances; the Xi extraction is not offered yet.
Python

The exact script CodeSplash ran for example “Iris” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# OPTICS
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.optics 1.1.0 · spec a9596b1febe0b1b4
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed

# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "sepal_length": "numeric",
    "sepal_width": "numeric",
    "petal_length": "numeric",
    "petal_width": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.optics/iris/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
MIN_SAMPLES = 8
MAX_EPS = None
CUT = None
EXTRACTION = "cut"
fit = dx.optics(X, MIN_SAMPLES, float("inf") if MAX_EPS is None else float(MAX_EPS))
order, reach, core = fit["order"], fit["reach"], fit["core"]
if EXTRACTION == "cut" and CUT is None:
    finite = np.sort(core[np.isfinite(core)])
    if len(finite) == 0:
        raise ValueError("No row has enough neighbors within the largest neighborhood — raise it or lower the minimum neighbors.")
    CUT = float(finite[csc.kneedle(np.arange(1, len(finite) + 1), finite)])
    if CUT <= 0:
        CUT = float(finite[finite > 0][0]) if np.any(finite > 0) else 1.0
    CUT *= 1 + 1e-9  # the knee is a real distance: make the boundary inclusive in both engines
    warnings.append(f"Reachability cut chosen automatically at the knee of the core distances: {CUT:.4g}.")
values["cut"] = float(CUT) if EXTRACTION == "cut" else None
values["min_samples"] = MIN_SAMPLES
values["extraction"] = EXTRACTION
values["order_check"] = csembed.checksum(order.astype(np.float64), np.arange(len(order)))
if EXTRACTION == "xi":
    XI = 0.05
    MIN_SIZE = None or MIN_SAMPLES
    values["xi"] = XI
    values["min_cluster_size"] = MIN_SIZE
    raw = dx.optics_xi(order, reach, fit["pred"], XI, MIN_SAMPLES, MIN_SIZE)
else:
    raw = dx.optics_cut(order, reach, core, CUT)
show = csc.even_sample(len(order))
finite_reach = reach[np.isfinite(reach)]
top = float(finite_reach.max()) * 1.05 if len(finite_reach) else 1.0
ordered = reach[order]
charts.append(cs.chart(
    "reachability", "reachability-plot", "Reachability plot",
    {"position": cs.col("Order", list(show + 1), "numeric"),
     "reachability": cs.col("Reachability distance", [float(v) if np.isfinite(v) else top for v in ordered[show]], "numeric"),
     "cluster": cs.col("Cluster", [str(c) for c in csc.canonical(raw)[order][show]], "categorical"),
     "undefined": cs.col("Undefined", [not bool(np.isfinite(v)) for v in ordered[show]], "boolean")},
    controls={"cut": float(CUT) if EXTRACTION == "cut" else 0},
    note=(f"Valleys below the cut ({CUT:.3g}) are clusters; bars at the top have no reachability (start of a new region)." if EXTRACTION == "cut"
          else f"Clusters run from a drop of at least {XI:.0%} in reachability to a matching rise, so valleys of any depth count; bars at the top have no reachability."),
))
summary = (
    f"OPTICS with at least {MIN_SAMPLES} neighbors, " + (f"cut at reachability {CUT:.4g}: " if EXTRACTION == "cut" else f"Xi = {XI:g}: ") +
    f"{len(set(raw.tolist()) - {-1})} clusters, {int(np.sum(raw == -1))} noise rows."
)

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "OPTICS",
    "engine": cs.engine_info("numpy", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "min_samples": 8,
        "max_eps": None,
        "extraction": "cut",
        "xi": 0.05,
        "min_cluster_size": None,
        "cut": None,
        "scale": "standard",
        "missing": "drop",
    }},
})
R

The exact script CodeSplash ran for example “Iris” · R version 4.5.1 (2025-06-13)

# OPTICS
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.optics 1.1.0 · spec a9596b1febe0b1b4
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  sepal_length = "numeric",
  sepal_width = "numeric",
  petal_length = "numeric",
  petal_width = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.optics/iris/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
MIN_SAMPLES <- 8
MAX_EPS <- NULL
CUT <- NULL
EXTRACTION <- "cut"
fit <- cs_ml_optics(X, MIN_SAMPLES, if (is.null(MAX_EPS)) Inf else as.numeric(MAX_EPS))
ord0 <- fit$order; reach <- fit$reach; core <- fit$core
if (EXTRACTION == "cut" && is.null(CUT)) {
  finite <- sort(core[is.finite(core)])
  if (!length(finite)) stop("No row has enough neighbors within the largest neighborhood — raise it or lower the minimum neighbors.")
  CUT <- finite[cs_ml_kneedle(seq_along(finite), finite) + 1L]
  if (CUT <= 0) CUT <- if (any(finite > 0)) finite[finite > 0][1] else 1
  CUT <- CUT * (1 + 1e-9)  # the knee is a real distance: make the boundary inclusive in both engines
  warnings <- c(warnings, sprintf("Reachability cut chosen automatically at the knee of the core distances: %s.", formatC(CUT, digits = 4, format = "g")))
}
values["cut"] <- list(if (EXTRACTION == "cut") as.numeric(CUT) else NULL)
values$min_samples <- MIN_SAMPLES
values$extraction <- EXTRACTION
values$order_check <- cs_ml_checksum(as.numeric(ord0), seq_along(ord0) - 1L)
if (EXTRACTION == "xi") {
  XI <- 0.05
  MIN_SIZE <- NULL
  if (is.null(MIN_SIZE)) MIN_SIZE <- MIN_SAMPLES
  values$xi <- XI
  values$min_cluster_size <- MIN_SIZE
  raw <- cs_ml_optics_xi(ord0, reach, fit$pred, XI, MIN_SAMPLES, MIN_SIZE)
} else {
  raw <- cs_ml_optics_cut(ord0, reach, core, CUT)
}
show <- cs_ml_even_sample(length(ord0)) + 1L
finite_reach <- reach[is.finite(reach)]
top <- if (length(finite_reach)) max(finite_reach) * 1.05 else 1
ordered <- reach[ord0 + 1L]
canon <- cs_ml_canonical(raw)
charts[[length(charts) + 1L]] <- cs_chart(
  "reachability", "reachability-plot", "Reachability plot",
  list(position = cs_col("Order", show, "numeric"),
       reachability = cs_col("Reachability distance", ifelse(is.finite(ordered[show]), ordered[show], top), "numeric"),
       cluster = cs_col("Cluster", as.character(canon[ord0 + 1L][show]), "categorical"),
       undefined = cs_col("Undefined", !is.finite(ordered[show]), "boolean")),
  controls = list(cut = if (EXTRACTION == "cut") as.numeric(CUT) else 0),
  note = if (EXTRACTION == "cut") sprintf("Valleys below the cut (%s) are clusters; bars at the top have no reachability (start of a new region).", format(signif(CUT, 3)))
         else sprintf("Clusters run from a drop of at least %.0f%% in reachability to a matching rise, so valleys of any depth count; bars at the top have no reachability.", 100 * XI)
)
summary <- sprintf("OPTICS with at least %d neighbors, %s: %d clusters, %d noise rows.", MIN_SAMPLES,
                   if (EXTRACTION == "cut") paste("cut at reachability", formatC(CUT, digits = 4, format = "g")) else sprintf("Xi = %s", format(XI)),
                   length(setdiff(unique(raw), -1L)), sum(raw == -1L))

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "OPTICS",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    min_samples = 8,
    max_eps = NULL,
    extraction = "cut",
    xi = 0.05,
    min_cluster_size = NULL,
    cut = NULL,
    scale = "standard",
    missing = "drop"
  ))
))

Sources

  • Ankerst M, Breunig MM, Kriegel HP, Sander J (1999). OPTICS: ordering points to identify the clustering structure. SIGMOD 1999, 49–60.
  • Schubert E, Gertz M (2018). Improving the cluster structure extracted from OPTICS plots. LWDA 2018, 318–329.

From the CodeSplash method registry · discover.optics v1.1.0.