raso 0.2.0

Pure-Rust dimensionality reduction and density clustering
Documentation

raso

CI Pages

PyPI crates.io Python versions Downloads

License Operating System Built with uv

High dimensions, low profile.

Pure-Rust dimensionality reduction and density clustering with Python abi3 bindings, WebAssembly bindings, and an interactive comparison demo. Methods include PCA, PPCA, truncated SVD, kernel PCA, classical MDS, spectral embedding, Isomap, PaCMAP, UMAP, t-SNE, and HDBSCAN.

Raso (Spanish: flat, level, open, unobstructed) is about flattening high-dimensional embeddings into a 2D/3D plane where structure and clusters become legible.

Workspace crates

Crate Purpose
raso Feature-gated facade: pca, svd, kernel-pca, mds, spectral, isomap, pacmap, umap, tsne, hdbscan, and parallel
raso-pca Exact centered PCA, low-rank PPCA EM, uncentered truncated SVD and kernel PCA
raso-mds Classical MDS from features or precomputed distances
raso-manifold Spectral embedding (Laplacian Eigenmaps), reusable exact kNN graph and Isomap
raso-pacmap Exact-neighbor PaCMAP with three-phase optimization
raso-tsne Exact t-SNE
raso-umap Pure-Rust UMAP dimensionality reduction
raso-hdbscan Pure-Rust HDBSCAN density-based clustering (EOM and Leaf selection, membership probabilities, persistence)

Implementation scope (80/20 UMAP)

raso-umap currently implements a clean, intentionally simple 80/20 UMAP:

  • Exact brute-force $O(n^2)$ k-NN search (fast and exact for small-to-medium datasets up to ~10k points; avoids NN-Descent complexity for now)
  • Smooth k-NN fuzzy simplicial set construction
  • Curve-fitted $(a, b)$ parameters and negative-sampling SGD layout optimization
  • Out-of-sample transform via weighted k-NN initialization + SGD refinement

raso-hdbscan implements core distances, mutual-reachability MST, condensed tree construction, EOM/Leaf cluster extraction, soft membership probabilities, and cluster persistence.

Usage

Add the umbrella crate (or a single member crate like raso-umap / raso-hdbscan) from GitHub:

[dependencies]
raso = { git = "https://github.com/mmacpherson/raso" }
ndarray = "0.16"
use ndarray::array;
use raso::hdbscan::{DistanceMetric as HdbscanMetric, Hdbscan};
use raso::umap::{DistanceMetric as UmapMetric, Umap};

let data = array![
    [0.0, 0.0], [0.2, 0.1], [0.1, 0.3],
    [10.0, 10.0], [10.2, 10.1], [10.1, 10.3],
];

let coords = Umap::new()
    .n_neighbors(2)
    .n_components(2)
    .min_dist(0.1)
    .metric(UmapMetric::Euclidean)
    .random_state(42)
    .fit_transform(data.view())?;

let clusters = Hdbscan::new()
    .min_cluster_size(2)
    .metric(HdbscanMetric::Euclidean)
    .fit(coords.view())?;

Single-threaded & wasm32-unknown-unknown

rayon parallelism is enabled by default via the parallel feature. Disable it for single-threaded or WebAssembly builds without SharedArrayBuffer / COOP+COEP headers:

[dependencies]
raso = { git = "https://github.com/mmacpherson/raso", default-features = false, features = ["pca", "mds", "umap", "hdbscan"] }

PCA, probabilistic PCA and classical MDS

use ndarray::array;
use raso::{pca::{Pca, Ppca}, mds::Mds};

let x = array![[1., 0., 0.], [-1., 0., 0.],
               [0., 2., 0.], [0., -2., 0.],
               [0., 0., 0.5], [0., 0., -0.5]];
let mut pca = Pca::new().n_components(2);
let scores = pca.fit_transform(x.view())?;
let reconstructed = pca.inverse_transform(scores.view())?;
let posterior = Ppca::new().n_components(2).random_state(42)
    .max_iter(500).tol(1e-6).fit_transform(x.view())?;
let coords = Mds::new().n_components(2).fit_transform(x.view())?;
  • PCA centers features without standardizing them. Component rows are orthonormal; explained variances use the sample divisor n - 1. A scale-normalized cyclic Jacobi solver diagonalizes the feature covariance matrix. Memory is O(n*d + d²) and time is O(n*d² + d³) for bounded sweeps. Wide data may favor PPCA instead.
  • PPCA fits the isotropic-noise latent Gaussian model from Tipping & Bishop (1999) by EM. It never forms a d × d covariance matrix: iteration cost is O(n*d*k + (n+d)*k² + k³). Component rows are loadings, not orthonormal PCA axes; transforms are posterior latent means and inverse transforms are generative reconstructions. Require 0 < k < d and k < n. A documented scale-relative positive noise floor handles rank deficiency. The last accepted iterate is returned at the iteration cap; inspect log_likelihood_history() and noise_variance() when assessing convergence.
  • Classical MDS double-centers squared distances and diagonalizes the resulting Gram matrix with a pure-Rust Jacobi solver. fit_transform accepts feature rows; fit_transform_distances accepts a symmetric nonnegative distance matrix with a zero diagonal. eigenvalues() includes negative modes for diagnosis; the embedding uses only positive modes and zero-fills remaining requested dimensions. Memory is O(n²) and bounded-sweep time is O(n³). This is classical scaling, not iterative SMACOF stress minimization.

For Euclidean feature distances, classical MDS and PCA agree up to rotations/reflections. Prefer these for global linear structure; use UMAP to examine nonlinear neighborhoods without treating its inter-cluster gaps as original distances. PPCA provides a linear probabilistic model rather than a nonlinear embedding. The new exact solvers/EM currently run serially; their parallel feature is reserved and adds no Rayon dependency.

Browser comparison

The Pages demo includes Who wore it better? A vs. B. Both panels receive the same source data, share source-space HDBSCAN colors and linked point highlighting, and display independent projection timings. Axis aspect ratios are preserved within each view; each view fits its own scale. PPCA on a 2D input uses one latent dimension (the vertical display coordinate is zero).

wasm-pack build bindings/wasm --target web --out-dir ../../web/src/wasm --no-pack
cd web
bun install --frozen-lockfile
bun test tests
bun run check
bun run build

The WASM API adds pca_fit_transform, ppca_fit_transform and mds_fit_transform; all consume flat row-major inputs and return flat row-major embeddings. PPCA takes an iteration cap, tolerance and BigInt seed. Invalid inputs return JavaScript errors.

The numerical tests were committed before implementation. Reference provenance and fixtures are in PCA tests, PPCA tests and MDS tests; the tests use reference numbers and geometry-aware comparisons rather than depending on Python/R at runtime.

Development

cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo test --workspace --no-default-features
cargo check --workspace --no-default-features --target wasm32-unknown-unknown

Roadmap

  • Approximate k-NN (NN-Descent) for larger datasets in raso-umap

License

MIT — see LICENSE.

Additional dimensionality reduction methods

use raso::{svd::TruncatedSvd, kernel_pca::{Kernel, KernelPca},
           spectral::SpectralEmbedding, isomap::Isomap, pacmap::Pacmap};
// x is an ndarray feature matrix; choose k < n_samples for graph methods.
let linear = TruncatedSvd::new().n_components(2).fit_transform(x.view())?;
let nonlinear = KernelPca::new().n_components(2)
    .kernel(Kernel::Rbf { gamma: 0.1 }).fit_transform(x.view())?;
let spectral = SpectralEmbedding::new().n_neighbors(10).fit_transform(x.view())?;
let geodesic = Isomap::new().n_neighbors(10).fit_transform(x.view())?;
let pairwise = Pacmap::new().n_neighbors(10).random_state(42).fit_transform(x.view())?;
  • Truncated SVD (LSA) leaves the mean intact and diagonalizes a dense feature Gram matrix. Component rows are orthonormal; singular values are descending, while explained variances describe the centered population variance of the uncentered scores (as in scikit-learn). Supports transform and inverse_transform. Cost is O(n d² + d³), memory O(n d + d²). It accepts dense matrices, not sparse text matrices; it is not a randomized or sparse SVD solver.
  • Kernel PCA centers an RBF, polynomial or cosine Gram matrix. Positive modes yield nonlinear coordinates; requested zero modes are zero-filled. Out-of-sample transform uses the training kernel means. RBF gamma is positive; polynomial gamma is positive, degree is a positive integer and coef0 is nonnegative. Cosine treats zero rows as zero similarity. Cost O(n² d + n³), memory O(n² + n d). No inverse feature map is fitted.
  • Spectral embedding uses the symmetrized directed kNN connectivity graph, W=(A+Aᵀ)/2, excluding self edges. It solves the normalized Laplacian and returns D⁻¹ᐟ²u for the smallest nontrivial modes, so coordinates are degree-orthonormal. The connected graph's trivial mode is omitted. KnnGraph, affinity() and normalized_laplacian() are available for reuse and diagnosis. No out-of-sample transform is defined.
  • Isomap uses a union kNN distance graph, exact all-pairs shortest paths and classical MDS. Out-of-sample transform extends geodesics through nearest training neighbors and projects into the fitted MDS axes. Negative MDS modes remain in the diagnostic spectrum; output uses positive modes. Spectral embedding and Isomap both reject disconnected graphs: increase neighbors or analyze components separately. Both use dense O(n²) storage and bounded O(n³) eigensolver/shortest-path work; these are small-to-medium dataset implementations.
  • PaCMAP uses exact locally scaled nearest neighbors, second-of-six mid-near sampling and nonneighbor further pairs. The original three-phase rational losses use Adam, with defaults [100,100,250] iterations. Seeded Gaussian initialization and f64 arithmetic are deterministic but do not reproduce the reference Python RNG/approximate-neighbor trajectory. Tiny datasets clamp pair counts to available distinct candidates. Exact neighbor search costs O(n² d) with O(n²) memory, then O(n k q) optimization per iteration for embedding dimension q and fixed pair ratios. Pair diagnostics and scalar loss/gradient helpers support independent checks.

The new implementations are serial and require no native BLAS/LAPACK; parallel remains a supported feature gate. Finite numerical range failures return errors rather than invalid embeddings. Eigenvector signs and bases in repeated eigenspaces are not uniquely identifiable: compare reconstructed kernels/distances or subspaces, not coordinate signs.

Python estimators

from raso import TruncatedSVD, KernelPCA, SpectralEmbedding, Isomap, PaCMAP
svd = TruncatedSVD(n_components=2).fit(X)
coordinates = svd.transform(X)
coordinates = KernelPCA(n_components=2, kernel="rbf", gamma=0.1).fit_transform(X)
coordinates = SpectralEmbedding(n_neighbors=10).fit_transform(X)
coordinates = Isomap(n_neighbors=10).fit_transform(X)
coordinates = PaCMAP(n_neighbors=10, n_iter=450, random_state=42).fit_transform(X)

These new classes implement fit(X, y=None), fit_transform, get_params, set_params, cloning/pipeline support and n_features_in_, without requiring scikit-learn at runtime. SVD, kernel PCA and Isomap also implement fitted transform; SVD has inverse_transform. Only dense array-like input is supported. Python kernel PCA defaults gamma=None to 1/n_features; the Rust default is gamma=1. Python/WASM PaCMAP's total n_iter is divided in the 100:100:250 ratio with at least one iteration per phase (minimum total 3). Spectral embedding counts nonself neighbors, so compare to scikit-learn connectivity graphs with their self-neighbor convention accounted for.

All five methods are available in the browser's A/B selectors. Kernel and gamma controls apply to kernel PCA; graph neighbors applies to spectral embedding, Isomap and PaCMAP, while UMAP retains its sidebar controls. Dense nonlinear solvers can take longer on larger samples. Linear axes, kernel coordinates, geodesic distances and neighbor layouts answer different questions: a cleaner-looking cluster separation alone does not establish better preservation.