Random walks as geometry: diffusion maps and PHATE
Let a random walk wander over the data, and call two rows close when the walk passes easily between them. Diffusion maps turn that into coordinates; PHATE turns it into a map built for branches and trajectories.
What runs in CodeSplash
- REP033Diffusion maps Runs in CodeSplash
- REP036PHATE Runs in CodeSplash
- Manifold maps (Isomap, LLE, diffusion maps, PHATE) Verified in Python and R
You will be able to
- Build a diffusion operator from a kernel, including density normalization, and read diffusion coordinates and time
- Explain why diffusion distance is robust to noise and uneven sampling
- Describe PHATE's potential distances and how it chooses the diffusion time
A walk on the data
ReadPut a walker on one row. At each step it hops to another row, preferring close ones, with probabilities from a kernel , normalized so each row's probabilities sum to 1. That gives a Markov chainTransition matrixFor each event, the share of times each other event (or the end of the journey) comes next. transition matrix .
After steps, says where the walk can be. Two rows are close in diffusion distance when walks starting from them end up in similar places. Noise adds stray paths, but they carry little probability, so the distance is far steadier than a single shortest path.
Coordinates from eigenvectors
ReadThe diffusion mapDiffusion mapCoordinates from a random walk on a Gaussian kernel; map distance approximates how easily the walk links two rows. uses the eigenvectors and eigenvalues of :
skipping the constant eigenvector. Euclidean distance between these coordinates equals the diffusion distance at time . Raising shrinks the small-eigenvalue directions, so the map shows coarser structure.
Diffusion map map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.942.
- Trustworthiness (k = 10)
- 0.9418
- Neighbors kept
- 60.8%
Plots
View data
| Group | Diffusion map 1 | Diffusion map 2 |
|---|---|---|
| All rows | −0.8997 | 0.1833 |
| All rows | −0.8451 | −0.5761 |
| All rows | −0.8945 | −0.5944 |
| All rows | 1.470 | −1.270 |
| All rows | 1.315 | −1.167 |
| All rows | −0.9266 | 0.1535 |
| All rows | −0.7427 | −0.7977 |
| All rows | 1.454 | −1.040 |
| All rows | 0.7358 | 0.9702 |
| All rows | −0.7788 | 0.7964 |
| All rows | 0.8855 | 1.179 |
| All rows | −0.6234 | −0.8794 |
| All rows | 1.510 | −1.139 |
| All rows | −0.9504 | −0.1363 |
| All rows | 0.1219 | 0.8984 |
| All rows | −0.9369 | −0.4627 |
| All rows | −0.8592 | −0.5864 |
| All rows | −0.6931 | −0.4793 |
| All rows | −0.8820 | −0.6868 |
| All rows | −0.2483 | −0.3942 |
| All rows | −0.7501 | −0.8313 |
| All rows | −0.9299 | 0.1291 |
| All rows | 1.418 | −0.6592 |
| All rows | 1.442 | −1.486 |
| All rows | 0.7603 | 1.223 |
| All rows | −0.7952 | 0.7534 |
| All rows | −0.8790 | −0.6149 |
| All rows | −0.3014 | −0.8681 |
| All rows | 0.2522 | 1.313 |
| All rows | −0.9178 | −0.5586 |
| All rows | −0.7556 | 0.7581 |
| All rows | −0.6630 | −0.7415 |
| All rows | −0.9290 | −0.5144 |
| All rows | 0.6056 | 1.775 |
| All rows | −0.3806 | −0.5377 |
| All rows | 1.433 | −1.490 |
| All rows | −0.8989 | −0.5966 |
| All rows | 0.1482 | 1.042 |
| All rows | −0.8635 | 0.3808 |
| All rows | −0.9415 | −0.5021 |
| All rows | −0.9333 | 0.1077 |
| All rows | −0.8340 | −0.5695 |
| All rows | 0.6397 | 1.719 |
| All rows | −0.9046 | −0.5610 |
| All rows | −0.8712 | −0.6575 |
| All rows | 1.218 | −1.336 |
| All rows | 1.427 | −1.501 |
| All rows | 1.024 | 0.8938 |
| All rows | 0.0542 | 0.8146 |
| All rows | −0.9421 | −0.5186 |
| All rows | −0.9297 | −0.1777 |
| All rows | −0.5321 | −0.3941 |
| All rows | 0.9785 | 1.036 |
| All rows | 0.9959 | 0.9831 |
| All rows | 0.6207 | 1.642 |
| All rows | 0.5176 | 1.678 |
| All rows | −0.3771 | −0.9270 |
| All rows | −0.9056 | −0.6503 |
| All rows | −0.8384 | −0.7487 |
| All rows | −0.9266 | −0.4150 |
First 60 of 240 rows.
Eigenvalues behind the map
| Dimension | Eigenvalue |
|---|---|
| 1 | 0.9704 |
| 2 | 0.9472 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec 254eb4a16aecb383
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = c("x", "y", "z"))), c("x", "y", "z"))
FEATURES <- c("x", "y", "z")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
x = "numeric",
y = "numeric",
z = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = LABEL))[[LABEL]]
METHOD <- "diffusion"
METHOD_LABEL <- c(isomap = "Isomap", lle = "LLE", hlle = "Hessian LLE", ltsa = "LTSA",
laplacian = "Laplacian eigenmaps", diffusion = "Diffusion map", phate = "PHATE")[[METHOD]]
keep <- cs_ml_sample_rows(length(rows), 1000)
if (length(keep) < length(rows)) {
warnings <- c(warnings, sprintf("%s maps %s evenly spaced rows of %s (the work grows with the square of the rows).",
METHOD_LABEL, format(length(keep), big.mark = ","), format(length(rows), big.mark = ",")))
}
X <- X[keep, , drop = FALSE]
rows <- rows[keep]
D_REQ <- 2L
k <- cs_ml_mf_check(METHOD, length(rows), ncol(X), 10L, D_REQ)
if (k < 10L) warnings <- c(warnings, sprintf("Only %d rows: the graph uses %d neighbors instead of 10.", length(rows), k))
# %% Map
fit <- cs_ml_mf_fit(
X, METHOD, k, D_REQ,
reg = 0.001,
affinity = "connectivity",
alpha = 0.5,
t = 2,
epsilon = NULL,
decay = 40,
phate_t = NULL,
max_iter = 300
)
Y <- fit$coords
K <- ncol(Y)
num_or_nan <- function(v) if (is.null(v)) NaN else as.numeric(v)
values <- list(
n = length(rows),
n_features = length(FEATURES),
n_components = K,
neighbors = k,
residual_variance = num_or_nan(fit$residual_variance),
recon_error = num_or_nan(fit$recon_error),
bandwidth = num_or_nan(fit$bandwidth),
epsilon = num_or_nan(fit$epsilon),
phate_t = if (METHOD == "phate") as.numeric(fit$t) else NaN,
stress = num_or_nan(fit$stress)
)
if (!is.null(fit$eigen)) for (j in seq_along(fit$eigen)) values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(Y[, j], rows)
# %% Neighborhood preservation (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
ok_eval <- k_eval >= 1L && 2 * length(sample) - 3 * k_eval - 1 > 0
trust_knn <- if (ok_eval) cs_ml_mf_neighborhood(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else c(NaN, NaN)
values$trustworthiness <- unname(trust_knn[1])
values$knn_preservation <- unname(trust_knn[2])
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.manifold/scurve_diffusion/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[sprintf("dim_%d", j)]] <- Y[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Charts
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
}
charts <- list(cs_chart("map", "cluster-scatter", paste(METHOD_LABEL, "map"), list(
x = cs_col(paste(METHOD_LABEL, 1), Y[pick, 1], "numeric"),
y = cs_col(paste(METHOD_LABEL, 2), Y[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
if (METHOD == "isomap") {
show <- cs_ml_even_sample(length(fit$geodesic), 2000) + 1L
note <- sprintf("Residual variance %.3f", values$residual_variance)
if (length(show) < length(fit$geodesic)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$geodesic), big.mark = ",")))
charts[[length(charts) + 1L]] <- cs_chart("shepard", "shepard-diagram", "Graph distance against map distance", list(
dissimilarity = cs_col("Graph (geodesic) distance", fit$geodesic[show], "numeric"),
distance = cs_col("Map distance", fit$map_distance[show], "numeric")
), note = note)
}
if (METHOD == "phate") {
ts <- seq_along(fit$vne)
charts[[length(charts) + 1L]] <- cs_chart("vne", "elbow-plot", "Choosing the diffusion time", list(
k = cs_col("Diffusion time t", as.numeric(ts), "numeric"),
score = cs_col("Von Neumann entropy", fit$vne, "numeric"),
criterion = cs_col("Criterion", rep("Von Neumann entropy", length(ts)), "categorical"),
chosen = cs_col("Chosen t", ts == fit$t, "boolean")
), note = sprintf("t = %d%s", as.integer(fit$t), if (is.null(NULL)) " (knee of the entropy curve)" else " (set)"))
}
# %% Result
tables <- list()
if (!is.null(fit$eigen)) {
tables[[1]] <- list(
key = "eigen",
title = "Eigenvalues behind the map",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Eigenvalue", type = "number")),
rows = lapply(seq_along(fit$eigen), function(j) list(dimension = j, eigen = fit$eigen[j]))
)
}
summary <- sprintf("%s map of %d rows in %d dimensions (%d neighbors): trustworthiness %.3f.", METHOD_LABEL, length(rows), K, k, values$trustworthiness)
if (METHOD == "isomap") summary <- paste(summary, sprintf("Residual variance %.3f.", values$residual_variance))
statistics <- list(
list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = values$trustworthiness),
list(key = "knn_preservation", label = "Neighbors kept", value = values$knn_preservation, format = "percent")
)
if (METHOD == "isomap") statistics[[length(statistics) + 1L]] <- list(key = "residual_variance", label = "Residual variance", value = values$residual_variance)
if (METHOD == "phate") statistics[[length(statistics) + 1L]] <- list(key = "phate_t", label = "Diffusion time t", value = values$phate_t)
cs_publish(list(
title = "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = statistics,
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Diffusion map map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.942.
- Trustworthiness (k = 10)
- 0.9418
- Neighbors kept
- 60.8%
To keep this page light, the plots are shown once, under the R tab.
Eigenvalues behind the map
| Dimension | Eigenvalue |
|---|---|
| 1 | 0.9704 |
| 2 | 0.9472 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec 254eb4a16aecb383
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
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.ml import embed as csembed
from codesplash.ml import manifold as csman
# %% Data
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=["x", "y", "z"]), ["x", "y", "z"])
FEATURES = ["x", "y", "z"]
df = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"x": "numeric",
"y": "numeric",
"z": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = None
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=[LABEL])[LABEL]
METHOD = "diffusion"
METHOD_LABEL = csman.METHOD_LABELS[METHOD]
keep = csembed.sample_rows(len(rows), 1000)
if len(keep) < len(rows):
warnings.append(f"{METHOD_LABEL} maps {len(keep):,} evenly spaced rows of {len(rows):,} (the work grows with the square of the rows).")
X = X[keep]
rows = rows[keep]
D_REQ = 2
k = csman.check_setup(METHOD, len(rows), X.shape[1], 10, D_REQ)
if k < 10:
warnings.append(f"Only {len(rows)} rows: the graph uses {k} neighbors instead of 10.")
# %% Map
fit = csman.fit(
X,
METHOD,
k,
D_REQ,
reg=0.001,
affinity="connectivity",
alpha=0.5,
t=2,
epsilon=None,
decay=40,
phate_t=None,
max_iter=300,
)
Y = fit["coords"]
K = Y.shape[1]
NAN = float("nan")
values = {
"n": len(rows),
"n_features": len(FEATURES),
"n_components": K,
"neighbors": k,
"residual_variance": float(fit.get("residual_variance", NAN)),
"recon_error": float(fit.get("recon_error", NAN)),
"bandwidth": float(fit.get("bandwidth", NAN)),
"epsilon": float(fit.get("epsilon", NAN)),
"phate_t": float(fit["t"]) if METHOD == "phate" else NAN,
"stress": float(fit.get("stress", NAN)),
}
eigen = fit.get("eigen")
if eigen is not None:
for j, v in enumerate(eigen):
values[f"eigen[{j + 1}]"] = float(v)
for j in range(K):
values[f"coord_check[{j + 1}]"] = csembed.checksum(Y[:, j], rows)
# %% Neighborhood preservation (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
ok_eval = k_eval >= 1 and 2 * len(sample) - 3 * k_eval - 1 > 0
trust_knn = csman.neighborhood_scores(X[sample], Y[sample], k_eval) if ok_eval else (NAN, NAN)
values["trustworthiness"], values["knn_preservation"] = float(trust_knn[0]), float(trust_knn[1])
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.manifold/scurve_diffusion/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = Y[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Charts
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", f"{METHOD_LABEL} map", {
"x": cs.col(f"{METHOD_LABEL} 1", Y[pick, 0], "numeric"),
"y": cs.col(f"{METHOD_LABEL} 2", Y[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
if METHOD == "isomap":
show = csc.even_sample(len(fit["geodesic"]), 2000)
charts.append(cs.chart("shepard", "shepard-diagram", "Graph distance against map distance", {
"dissimilarity": cs.col("Graph (geodesic) distance", fit["geodesic"][show], "numeric"),
"distance": cs.col("Map distance", fit["map_distance"][show], "numeric"),
}, note=f"Residual variance {values['residual_variance']:.3f}" + ("" if len(show) == len(fit["geodesic"]) else f"; {len(show):,} of {len(fit['geodesic']):,} pairs shown")))
if METHOD == "phate":
vne = fit["vne"]
ts = np.arange(1, len(vne) + 1)
charts.append(cs.chart("vne", "elbow-plot", "Choosing the diffusion time", {
"k": cs.col("Diffusion time t", ts.astype(float), "numeric"),
"score": cs.col("Von Neumann entropy", vne, "numeric"),
"criterion": cs.col("Criterion", ["Von Neumann entropy"] * len(vne), "categorical"),
"chosen": cs.col("Chosen t", [bool(t == fit["t"]) for t in ts], "boolean"),
}, note=f"t = {fit['t']}" + (" (knee of the entropy curve)" if None is None else " (set)")))
# %% Result
tables = []
if eigen is not None:
tables.append({
"key": "eigen",
"title": "Eigenvalues behind the map",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
"rows": [{"dimension": j + 1, "eigen": float(v)} for j, v in enumerate(eigen)],
})
trust = values["trustworthiness"]
summary = f"{METHOD_LABEL} map of {len(rows)} rows in {K} dimensions ({k} neighbors): trustworthiness {trust:.3f}."
if METHOD == "isomap":
summary += f" Residual variance {values['residual_variance']:.3f}."
statistics = [
{"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": values["trustworthiness"]},
{"key": "knn_preservation", "label": "Neighbors kept", "value": values["knn_preservation"], "format": "percent"},
]
if METHOD == "isomap":
statistics.append({"key": "residual_variance", "label": "Residual variance", "value": values["residual_variance"]})
if METHOD == "phate":
statistics.append({"key": "phate_t", "label": "Diffusion time t", "value": values["phate_t"]})
cs.publish({
"title": "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": statistics,
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
On the S-curve, the leading eigenvalues are 0.970 and 0.947: close to 1, so both directions survive many steps.
Two settings that matter
Read- The bandwidthKernel bandwidth (ε)Width of the Gaussian kernel exp(−distance² / ε) a diffusion map uses; automatic = median squared k-th neighbor distance. ε sets how far one hop reaches. CodeSplash picks it from the data (here 0.476, the median squared distance to each row's 10th neighbor) unless you fix it, as the unscaled run does with ε = 0.500.
- Density normalization α divides the kernel by local densities first. With α = 1, the map follows the shape of the surface (the Laplace–Beltrami operator) and ignores how densely each part was sampled; with α = 0, dense regions pull the walk.
PHATE: built for branches
ReadPHATEPHATEDiffuses a neighbor kernel, takes log potentials and places rows by metric scaling; keeps branches and trajectories. keeps the walk but changes what it reads from it:
- Diffuse for steps: .
- Take potentials, , so tiny probabilities far down a branch still count.
- Measure distances between rows' potential profiles.
- Place rows with metric MDS on those distances.
Branches, trajectories and gradual transitions stay visible, which made it popular for cell-development data. In the reference's tiny example, the first potential distance is 0.0199.
How PHATE chooses t
ReadToo few steps and noise dominates; too many and everything blurs together. PHATE tracks the von Neumann entropyVon Neumann entropy (PHATE)Entropy of the diffusion spectrum raised to t; PHATE picks t at the knee, where it stops falling quickly. of as grows and picks the knee of that curve, where information stops falling fast.
PHATE map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.951.
- Trustworthiness (k = 10)
- 0.9511
- Neighbors kept
- 60.0%
- Diffusion time t
- 7
Plots
View data
| band | PHATE 1 | PHATE 2 |
|---|---|---|
| D | 81.000 | 30.574 |
| C | 12.554 | −12.495 |
| C | 18.446 | −21.481 |
| A | −52.036 | 42.160 |
| A | −40.269 | 22.223 |
| D | 84.223 | 18.426 |
| C | −3.925 | −41.074 |
| A | −57.936 | 45.296 |
| B | −51.220 | −4.946 |
| D | 73.520 | 49.240 |
| B | −70.468 | 8.453 |
| C | 1.894 | −44.833 |
| A | −35.697 | 34.902 |
| D | 74.230 | 9.275 |
| B | −38.833 | −33.048 |
| D | 63.268 | −23.461 |
| C | 5.976 | −23.285 |
| C | −3.845 | −18.681 |
| D | 42.562 | −37.211 |
| C | −27.147 | −45.346 |
| C | 9.290 | −45.689 |
| D | 82.911 | 20.285 |
| A | −60.413 | 35.271 |
| A | −40.174 | 51.145 |
| B | −61.695 | −8.931 |
| D | 74.762 | 45.066 |
| C | 14.426 | −29.146 |
| C | −13.575 | −39.955 |
| B | −51.406 | −30.366 |
| C | 39.268 | −19.775 |
| D | 77.098 | 51.873 |
| C | −11.281 | −45.169 |
| D | 52.866 | −23.616 |
| B | −74.765 | −6.917 |
| C | −19.614 | −50.180 |
| A | −39.094 | 46.307 |
| C | 22.202 | −20.474 |
| B | −40.882 | −31.962 |
| D | 83.093 | 3.990 |
| D | 63.972 | −24.340 |
| D | 80.956 | 23.785 |
| C | 4.570 | −19.965 |
| B | −74.857 | −1.900 |
| C | 29.495 | −14.704 |
| C | 15.034 | −38.508 |
| A | −36.813 | 24.859 |
| A | −38.026 | 47.850 |
| A | −74.312 | 22.067 |
| C | −31.719 | −33.567 |
| D | 62.317 | −25.367 |
| D | 74.462 | −14.507 |
| C | −17.169 | −45.071 |
| B | −70.978 | 16.383 |
| A | −74.255 | 21.388 |
| B | −68.263 | −7.706 |
| B | −65.551 | −17.511 |
| C | −6.952 | −40.823 |
| C | 35.874 | −35.712 |
| C | 18.770 | −42.185 |
| D | 57.112 | −20.852 |
First 60 of 240 rows.
t = 7 (knee of the entropy curve)
View data
| Chosen t | Criterion | Diffusion time t | Von Neumann entropy |
|---|---|---|---|
| false | Von Neumann entropy | 1 | 4.673 |
| false | Von Neumann entropy | 2 | 3.807 |
| false | Von Neumann entropy | 3 | 3.392 |
| false | Von Neumann entropy | 4 | 3.169 |
| false | Von Neumann entropy | 5 | 3.019 |
| false | Von Neumann entropy | 6 | 2.906 |
| true | Von Neumann entropy | 7 | 2.814 |
| false | Von Neumann entropy | 8 | 2.738 |
| false | Von Neumann entropy | 9 | 2.674 |
| false | Von Neumann entropy | 10 | 2.618 |
| false | Von Neumann entropy | 11 | 2.569 |
| false | Von Neumann entropy | 12 | 2.525 |
| false | Von Neumann entropy | 13 | 2.486 |
| false | Von Neumann entropy | 14 | 2.450 |
| false | Von Neumann entropy | 15 | 2.418 |
| false | Von Neumann entropy | 16 | 2.388 |
| false | Von Neumann entropy | 17 | 2.359 |
| false | Von Neumann entropy | 18 | 2.333 |
| false | Von Neumann entropy | 19 | 2.308 |
| false | Von Neumann entropy | 20 | 2.284 |
| false | Von Neumann entropy | 21 | 2.261 |
| false | Von Neumann entropy | 22 | 2.239 |
| false | Von Neumann entropy | 23 | 2.217 |
| false | Von Neumann entropy | 24 | 2.196 |
| false | Von Neumann entropy | 25 | 2.176 |
| false | Von Neumann entropy | 26 | 2.156 |
| false | Von Neumann entropy | 27 | 2.136 |
| false | Von Neumann entropy | 28 | 2.117 |
| false | Von Neumann entropy | 29 | 2.098 |
| false | Von Neumann entropy | 30 | 2.079 |
| false | Von Neumann entropy | 31 | 2.061 |
| false | Von Neumann entropy | 32 | 2.043 |
| false | Von Neumann entropy | 33 | 2.025 |
| false | Von Neumann entropy | 34 | 2.007 |
| false | Von Neumann entropy | 35 | 1.989 |
| false | Von Neumann entropy | 36 | 1.972 |
| false | Von Neumann entropy | 37 | 1.955 |
| false | Von Neumann entropy | 38 | 1.938 |
| false | Von Neumann entropy | 39 | 1.921 |
| false | Von Neumann entropy | 40 | 1.904 |
| false | Von Neumann entropy | 41 | 1.887 |
| false | Von Neumann entropy | 42 | 1.871 |
| false | Von Neumann entropy | 43 | 1.855 |
| false | Von Neumann entropy | 44 | 1.839 |
| false | Von Neumann entropy | 45 | 1.823 |
| false | Von Neumann entropy | 46 | 1.807 |
| false | Von Neumann entropy | 47 | 1.791 |
| false | Von Neumann entropy | 48 | 1.775 |
| false | Von Neumann entropy | 49 | 1.760 |
| false | Von Neumann entropy | 50 | 1.745 |
| false | Von Neumann entropy | 51 | 1.729 |
| false | Von Neumann entropy | 52 | 1.714 |
| false | Von Neumann entropy | 53 | 1.700 |
| false | Von Neumann entropy | 54 | 1.685 |
| false | Von Neumann entropy | 55 | 1.670 |
| false | Von Neumann entropy | 56 | 1.656 |
| false | Von Neumann entropy | 57 | 1.642 |
| false | Von Neumann entropy | 58 | 1.628 |
| false | Von Neumann entropy | 59 | 1.614 |
| false | Von Neumann entropy | 60 | 1.600 |
First 60 of 100 rows.
The exact R script · R R version 4.5.1 (2025-06-13)
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec 359c0322c8918eb7
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = c("x", "y", "z"))), c("x", "y", "z"))
FEATURES <- c("x", "y", "z")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
x = "numeric",
y = "numeric",
z = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "band"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep3_scurve.parquet", col_select = LABEL))[[LABEL]]
METHOD <- "phate"
METHOD_LABEL <- c(isomap = "Isomap", lle = "LLE", hlle = "Hessian LLE", ltsa = "LTSA",
laplacian = "Laplacian eigenmaps", diffusion = "Diffusion map", phate = "PHATE")[[METHOD]]
keep <- cs_ml_sample_rows(length(rows), 1000)
if (length(keep) < length(rows)) {
warnings <- c(warnings, sprintf("%s maps %s evenly spaced rows of %s (the work grows with the square of the rows).",
METHOD_LABEL, format(length(keep), big.mark = ","), format(length(rows), big.mark = ",")))
}
X <- X[keep, , drop = FALSE]
rows <- rows[keep]
D_REQ <- 2L
k <- cs_ml_mf_check(METHOD, length(rows), ncol(X), 10L, D_REQ)
if (k < 10L) warnings <- c(warnings, sprintf("Only %d rows: the graph uses %d neighbors instead of 10.", length(rows), k))
# %% Map
fit <- cs_ml_mf_fit(
X, METHOD, k, D_REQ,
reg = 0.001,
affinity = "connectivity",
alpha = 1,
t = 1,
epsilon = NULL,
decay = 40,
phate_t = NULL,
max_iter = 300
)
Y <- fit$coords
K <- ncol(Y)
num_or_nan <- function(v) if (is.null(v)) NaN else as.numeric(v)
values <- list(
n = length(rows),
n_features = length(FEATURES),
n_components = K,
neighbors = k,
residual_variance = num_or_nan(fit$residual_variance),
recon_error = num_or_nan(fit$recon_error),
bandwidth = num_or_nan(fit$bandwidth),
epsilon = num_or_nan(fit$epsilon),
phate_t = if (METHOD == "phate") as.numeric(fit$t) else NaN,
stress = num_or_nan(fit$stress)
)
if (!is.null(fit$eigen)) for (j in seq_along(fit$eigen)) values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(Y[, j], rows)
# %% Neighborhood preservation (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
ok_eval <- k_eval >= 1L && 2 * length(sample) - 3 * k_eval - 1 > 0
trust_knn <- if (ok_eval) cs_ml_mf_neighborhood(X[sample, , drop = FALSE], Y[sample, , drop = FALSE], k_eval) else c(NaN, NaN)
values$trustworthiness <- unname(trust_knn[1])
values$knn_preservation <- unname(trust_knn[2])
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.manifold/scurve_phate/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[sprintf("dim_%d", j)]] <- Y[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Charts
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
}
charts <- list(cs_chart("map", "cluster-scatter", paste(METHOD_LABEL, "map"), list(
x = cs_col(paste(METHOD_LABEL, 1), Y[pick, 1], "numeric"),
y = cs_col(paste(METHOD_LABEL, 2), Y[pick, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ","))))
if (METHOD == "isomap") {
show <- cs_ml_even_sample(length(fit$geodesic), 2000) + 1L
note <- sprintf("Residual variance %.3f", values$residual_variance)
if (length(show) < length(fit$geodesic)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$geodesic), big.mark = ",")))
charts[[length(charts) + 1L]] <- cs_chart("shepard", "shepard-diagram", "Graph distance against map distance", list(
dissimilarity = cs_col("Graph (geodesic) distance", fit$geodesic[show], "numeric"),
distance = cs_col("Map distance", fit$map_distance[show], "numeric")
), note = note)
}
if (METHOD == "phate") {
ts <- seq_along(fit$vne)
charts[[length(charts) + 1L]] <- cs_chart("vne", "elbow-plot", "Choosing the diffusion time", list(
k = cs_col("Diffusion time t", as.numeric(ts), "numeric"),
score = cs_col("Von Neumann entropy", fit$vne, "numeric"),
criterion = cs_col("Criterion", rep("Von Neumann entropy", length(ts)), "categorical"),
chosen = cs_col("Chosen t", ts == fit$t, "boolean")
), note = sprintf("t = %d%s", as.integer(fit$t), if (is.null(NULL)) " (knee of the entropy curve)" else " (set)"))
}
# %% Result
tables <- list()
if (!is.null(fit$eigen)) {
tables[[1]] <- list(
key = "eigen",
title = "Eigenvalues behind the map",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Eigenvalue", type = "number")),
rows = lapply(seq_along(fit$eigen), function(j) list(dimension = j, eigen = fit$eigen[j]))
)
}
summary <- sprintf("%s map of %d rows in %d dimensions (%d neighbors): trustworthiness %.3f.", METHOD_LABEL, length(rows), K, k, values$trustworthiness)
if (METHOD == "isomap") summary <- paste(summary, sprintf("Residual variance %.3f.", values$residual_variance))
statistics <- list(
list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = values$trustworthiness),
list(key = "knn_preservation", label = "Neighbors kept", value = values$knn_preservation, format = "percent")
)
if (METHOD == "isomap") statistics[[length(statistics) + 1L]] <- list(key = "residual_variance", label = "Residual variance", value = values$residual_variance)
if (METHOD == "phate") statistics[[length(statistics) + 1L]] <- list(key = "phate_t", label = "Diffusion time t", value = values$phate_t)
cs_publish(list(
title = "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = statistics,
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
PHATE map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.951.
- Trustworthiness (k = 10)
- 0.9511
- Neighbors kept
- 60.0%
- Diffusion time t
- 7
To keep this page light, the plots are shown once, under the R tab.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Manifold maps (Isomap, LLE, diffusion maps, PHATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.manifold 1.0.0 · spec 359c0322c8918eb7
# Dataset: rep3_scurve (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
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.ml import embed as csembed
from codesplash.ml import manifold as csman
# %% Data
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=["x", "y", "z"]), ["x", "y", "z"])
FEATURES = ["x", "y", "z"]
df = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"x": "numeric",
"y": "numeric",
"z": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "band"
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/rep3_scurve.parquet", columns=[LABEL])[LABEL]
METHOD = "phate"
METHOD_LABEL = csman.METHOD_LABELS[METHOD]
keep = csembed.sample_rows(len(rows), 1000)
if len(keep) < len(rows):
warnings.append(f"{METHOD_LABEL} maps {len(keep):,} evenly spaced rows of {len(rows):,} (the work grows with the square of the rows).")
X = X[keep]
rows = rows[keep]
D_REQ = 2
k = csman.check_setup(METHOD, len(rows), X.shape[1], 10, D_REQ)
if k < 10:
warnings.append(f"Only {len(rows)} rows: the graph uses {k} neighbors instead of 10.")
# %% Map
fit = csman.fit(
X,
METHOD,
k,
D_REQ,
reg=0.001,
affinity="connectivity",
alpha=1,
t=1,
epsilon=None,
decay=40,
phate_t=None,
max_iter=300,
)
Y = fit["coords"]
K = Y.shape[1]
NAN = float("nan")
values = {
"n": len(rows),
"n_features": len(FEATURES),
"n_components": K,
"neighbors": k,
"residual_variance": float(fit.get("residual_variance", NAN)),
"recon_error": float(fit.get("recon_error", NAN)),
"bandwidth": float(fit.get("bandwidth", NAN)),
"epsilon": float(fit.get("epsilon", NAN)),
"phate_t": float(fit["t"]) if METHOD == "phate" else NAN,
"stress": float(fit.get("stress", NAN)),
}
eigen = fit.get("eigen")
if eigen is not None:
for j, v in enumerate(eigen):
values[f"eigen[{j + 1}]"] = float(v)
for j in range(K):
values[f"coord_check[{j + 1}]"] = csembed.checksum(Y[:, j], rows)
# %% Neighborhood preservation (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
ok_eval = k_eval >= 1 and 2 * len(sample) - 3 * k_eval - 1 > 0
trust_knn = csman.neighborhood_scores(X[sample], Y[sample], k_eval) if ok_eval else (NAN, NAN)
values["trustworthiness"], values["knn_preservation"] = float(trust_knn[0]), float(trust_knn[1])
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.manifold/scurve_phate/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = Y[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Charts
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = [cs.chart("map", "cluster-scatter", f"{METHOD_LABEL} map", {
"x": cs.col(f"{METHOD_LABEL} 1", Y[pick, 0], "numeric"),
"y": cs.col(f"{METHOD_LABEL} 2", Y[pick, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown.")]
if METHOD == "isomap":
show = csc.even_sample(len(fit["geodesic"]), 2000)
charts.append(cs.chart("shepard", "shepard-diagram", "Graph distance against map distance", {
"dissimilarity": cs.col("Graph (geodesic) distance", fit["geodesic"][show], "numeric"),
"distance": cs.col("Map distance", fit["map_distance"][show], "numeric"),
}, note=f"Residual variance {values['residual_variance']:.3f}" + ("" if len(show) == len(fit["geodesic"]) else f"; {len(show):,} of {len(fit['geodesic']):,} pairs shown")))
if METHOD == "phate":
vne = fit["vne"]
ts = np.arange(1, len(vne) + 1)
charts.append(cs.chart("vne", "elbow-plot", "Choosing the diffusion time", {
"k": cs.col("Diffusion time t", ts.astype(float), "numeric"),
"score": cs.col("Von Neumann entropy", vne, "numeric"),
"criterion": cs.col("Criterion", ["Von Neumann entropy"] * len(vne), "categorical"),
"chosen": cs.col("Chosen t", [bool(t == fit["t"]) for t in ts], "boolean"),
}, note=f"t = {fit['t']}" + (" (knee of the entropy curve)" if None is None else " (set)")))
# %% Result
tables = []
if eigen is not None:
tables.append({
"key": "eigen",
"title": "Eigenvalues behind the map",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
"rows": [{"dimension": j + 1, "eigen": float(v)} for j, v in enumerate(eigen)],
})
trust = values["trustworthiness"]
summary = f"{METHOD_LABEL} map of {len(rows)} rows in {K} dimensions ({k} neighbors): trustworthiness {trust:.3f}."
if METHOD == "isomap":
summary += f" Residual variance {values['residual_variance']:.3f}."
statistics = [
{"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": values["trustworthiness"]},
{"key": "knn_preservation", "label": "Neighbors kept", "value": values["knn_preservation"], "format": "percent"},
]
if METHOD == "isomap":
statistics.append({"key": "residual_variance", "label": "Residual variance", "value": values["residual_variance"]})
if METHOD == "phate":
statistics.append({"key": "phate_t", "label": "Diffusion time t", "value": values["phate_t"]})
cs.publish({
"title": "Manifold maps (Isomap, LLE, diffusion maps, PHATE)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": statistics,
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
On the S-curve it chose = 7, with stressStress (PHATE scaling)√(Σ(map distance − potential distance)² / Σ potential distance²) after PHATE's metric scaling; lower is closer. 0.115 and trustworthiness 0.951.
Readiness and limits
ReadBoth run in CodeSplash: Discover → Manifold maps, methods Diffusion map and PHATE.
- Neither gives a natural map for new rows without an extension method.
- A disconnected graph has more than one eigenvalue equal to 1; the pieces don't share a map.
- The kernel width, and change the picture; show the map at two settings before trusting a branch.
Check: diffusion maps and PHATE
CheckpointCheck yourself
Why is diffusion distance more robust to noise than a single shortest path through the neighbor graph?
Show the answer
Answer: a
A shortest path can be hijacked by one shortcut. Diffusion spreads probability over many paths, so a rare shortcut barely matters.
Check yourself
Rows are sampled densely in one region and sparsely elsewhere. Which density normalization makes the map follow the shape, not the sampling?
Show the answer
Answer: a
α = 1 divides out the sampling density, leaving the Laplace–Beltrami geometry of the surface.
Check yourself
In diffusion coordinates , what does increasing do?
Show the answer
Answer: a
decays fastest for small , so fine detail fades and broad structure remains.
Check yourself
Why does PHATE take the logarithm of diffused probabilities (the potential)?
Show the answer
Answer: a
Raw probabilities make distant parts of a branch indistinguishable; logs spread them out, which preserves long trajectories.
Check yourself
How does PHATE choose its diffusion time automatically?
Show the answer
Answer: a
Before the knee, diffusion is still removing noise; after it, it starts removing real structure.
Recap
Recap- A kernel turns rows into a random walk; diffusion distance compares where walks from two rows end up.
- Diffusion maps use eigenvectors scaled by ; ε and α change the picture.
- PHATE reads log-potentials of the walk and lays them out with MDS, choosing by the entropy knee.
Concepts in this lesson