Skip to content

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.

Advanced ~14 min8 steps

What runs in CodeSplash

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

Read first

01

A walk on the data

Read

Put a walker on one row. At each step it hops to another row, preferring close ones, with probabilities from a kernel k(xi,xj)=e−∥xi−xj∥2/ϵk(x_i, x_j) = e^{-\lVert x_i - x_j\rVert^2/\epsilon}, 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 PP.

After tt steps, PtP^t 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.

02

Coordinates from eigenvectors

Read

The diffusion mapDiffusion mapCoordinates from a random walk on a Gaussian kernel; map distance approximates how easily the walk links two rows. uses the eigenvectors ψk\psi_k and eigenvalues λk\lambda_k of PP:

Ψt(xi)=(λ1t ψ1(i),  λ2t ψ2(i),  …),\Psi_t(x_i) = \big(\lambda_1^t\, \psi_1(i),\; \lambda_2^t\, \psi_2(i),\; \ldots\big),

skipping the constant eigenvector. Euclidean distance between these coordinates equals the diffusion distance at time tt. Raising tt shrinks the small-eigenvalue directions, so the map shows coarser structure.

Manifold maps (Isomap, LLE, diffusion maps, PHATE)Recorded · Python and R agreeRecorded 2026-11-25 · 16 values compared
R

Diffusion map map of 240 rows in 2 dimensions (10 neighbors): trustworthiness 0.942.

Trustworthiness (k = 10)
0.9418
Neighbors kept
60.8%

Plots

Diffusion map mapWhich rows group together, and how well separated are the groups?
View data
GroupDiffusion map 1Diffusion map 2
All rows−0.89970.1833
All rows−0.8451−0.5761
All rows−0.8945−0.5944
All rows1.470−1.270
All rows1.315−1.167
All rows−0.92660.1535
All rows−0.7427−0.7977
All rows1.454−1.040
All rows0.73580.9702
All rows−0.77880.7964
All rows0.88551.179
All rows−0.6234−0.8794
All rows1.510−1.139
All rows−0.9504−0.1363
All rows0.12190.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.92990.1291
All rows1.418−0.6592
All rows1.442−1.486
All rows0.76031.223
All rows−0.79520.7534
All rows−0.8790−0.6149
All rows−0.3014−0.8681
All rows0.25221.313
All rows−0.9178−0.5586
All rows−0.75560.7581
All rows−0.6630−0.7415
All rows−0.9290−0.5144
All rows0.60561.775
All rows−0.3806−0.5377
All rows1.433−1.490
All rows−0.8989−0.5966
All rows0.14821.042
All rows−0.86350.3808
All rows−0.9415−0.5021
All rows−0.93330.1077
All rows−0.8340−0.5695
All rows0.63971.719
All rows−0.9046−0.5610
All rows−0.8712−0.6575
All rows1.218−1.336
All rows1.427−1.501
All rows1.0240.8938
All rows0.05420.8146
All rows−0.9421−0.5186
All rows−0.9297−0.1777
All rows−0.5321−0.3941
All rows0.97851.036
All rows0.99590.9831
All rows0.62071.642
All rows0.51761.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

DimensionEigenvalue
10.9704
20.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"))
))
Python

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

DimensionEigenvalue
10.9704
20.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.

03

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.
04

PHATE: built for branches

Read

PHATEPHATEDiffuses 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:

  1. Diffuse for tt steps: PtP^t.
  2. Take potentials, −log⁡Pt-\log P^t, so tiny probabilities far down a branch still count.
  3. Measure distances between rows' potential profiles.
  4. 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.

05

How PHATE chooses t

Read

Too 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 PtP^t as tt grows and picks the knee of that curve, where information stops falling fast.

Manifold maps (Isomap, LLE, diffusion maps, PHATE)Recorded · Python and R agreeRecorded 2026-11-25 · 14 values compared
R

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

PHATE mapWhich rows group together, and how well separated are the groups?
View data
bandPHATE 1PHATE 2
D81.00030.574
C12.554−12.495
C18.446−21.481
A−52.03642.160
A−40.26922.223
D84.22318.426
C−3.925−41.074
A−57.93645.296
B−51.220−4.946
D73.52049.240
B−70.4688.453
C1.894−44.833
A−35.69734.902
D74.2309.275
B−38.833−33.048
D63.268−23.461
C5.976−23.285
C−3.845−18.681
D42.562−37.211
C−27.147−45.346
C9.290−45.689
D82.91120.285
A−60.41335.271
A−40.17451.145
B−61.695−8.931
D74.76245.066
C14.426−29.146
C−13.575−39.955
B−51.406−30.366
C39.268−19.775
D77.09851.873
C−11.281−45.169
D52.866−23.616
B−74.765−6.917
C−19.614−50.180
A−39.09446.307
C22.202−20.474
B−40.882−31.962
D83.0933.990
D63.972−24.340
D80.95623.785
C4.570−19.965
B−74.857−1.900
C29.495−14.704
C15.034−38.508
A−36.81324.859
A−38.02647.850
A−74.31222.067
C−31.719−33.567
D62.317−25.367
D74.462−14.507
C−17.169−45.071
B−70.97816.383
A−74.25521.388
B−68.263−7.706
B−65.551−17.511
C−6.952−40.823
C35.874−35.712
C18.770−42.185
D57.112−20.852

First 60 of 240 rows.

Choosing the diffusion timeHow many clusters does the data support?

t = 7 (knee of the entropy curve)

View data
Chosen tCriterionDiffusion time tVon Neumann entropy
falseVon Neumann entropy14.673
falseVon Neumann entropy23.807
falseVon Neumann entropy33.392
falseVon Neumann entropy43.169
falseVon Neumann entropy53.019
falseVon Neumann entropy62.906
trueVon Neumann entropy72.814
falseVon Neumann entropy82.738
falseVon Neumann entropy92.674
falseVon Neumann entropy102.618
falseVon Neumann entropy112.569
falseVon Neumann entropy122.525
falseVon Neumann entropy132.486
falseVon Neumann entropy142.450
falseVon Neumann entropy152.418
falseVon Neumann entropy162.388
falseVon Neumann entropy172.359
falseVon Neumann entropy182.333
falseVon Neumann entropy192.308
falseVon Neumann entropy202.284
falseVon Neumann entropy212.261
falseVon Neumann entropy222.239
falseVon Neumann entropy232.217
falseVon Neumann entropy242.196
falseVon Neumann entropy252.176
falseVon Neumann entropy262.156
falseVon Neumann entropy272.136
falseVon Neumann entropy282.117
falseVon Neumann entropy292.098
falseVon Neumann entropy302.079
falseVon Neumann entropy312.061
falseVon Neumann entropy322.043
falseVon Neumann entropy332.025
falseVon Neumann entropy342.007
falseVon Neumann entropy351.989
falseVon Neumann entropy361.972
falseVon Neumann entropy371.955
falseVon Neumann entropy381.938
falseVon Neumann entropy391.921
falseVon Neumann entropy401.904
falseVon Neumann entropy411.887
falseVon Neumann entropy421.871
falseVon Neumann entropy431.855
falseVon Neumann entropy441.839
falseVon Neumann entropy451.823
falseVon Neumann entropy461.807
falseVon Neumann entropy471.791
falseVon Neumann entropy481.775
falseVon Neumann entropy491.760
falseVon Neumann entropy501.745
falseVon Neumann entropy511.729
falseVon Neumann entropy521.714
falseVon Neumann entropy531.700
falseVon Neumann entropy541.685
falseVon Neumann entropy551.670
falseVon Neumann entropy561.656
falseVon Neumann entropy571.642
falseVon Neumann entropy581.628
falseVon Neumann entropy591.614
falseVon Neumann entropy601.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"))
))
Python

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 tt = 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.

06

Readiness and limits

Read

Both 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, α\alpha and tt change the picture; show the map at two settings before trusting a branch.
07

Check: diffusion maps and PHATE

Checkpoint

Check 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 λktψk\lambda_k^t \psi_k, what does increasing tt do?

Show the answer

Answer: a

λkt\lambda_k^t decays fastest for small λk\lambda_k, 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.

08

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 λt\lambda^t; ε and α change the picture.
  • PHATE reads log-potentials of the walk and lays them out with MDS, choosing tt by the entropy knee.

Concepts in this lesson