raso
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
transformvia 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:
[]
= { = "https://github.com/mmacpherson/raso" }
= "0.16"
use array;
use ;
use ;
let data = array!;
let coords = new
.n_neighbors
.n_components
.min_dist
.metric
.random_state
.fit_transform?;
let clusters = new
.min_cluster_size
.metric
.fit?;
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:
[]
= { = "https://github.com/mmacpherson/raso", = false, = ["pca", "mds", "umap", "hdbscan"] }
PCA, probabilistic PCA and classical MDS
use array;
use ;
let x = array!;
let mut pca = new.n_components;
let scores = pca.fit_transform?;
let reconstructed = pca.inverse_transform?;
let posterior = new.n_components.random_state
.max_iter.tol.fit_transform?;
let coords = new.n_components.fit_transform?;
- 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 isO(n*d + d²)and time isO(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 × dcovariance matrix: iteration cost isO(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. Require0 < k < dandk < n. A documented scale-relative positive noise floor handles rank deficiency. The last accepted iterate is returned at the iteration cap; inspectlog_likelihood_history()andnoise_variance()when assessing convergence. - Classical MDS double-centers squared distances and diagonalizes the resulting Gram matrix with a pure-Rust Jacobi solver.
fit_transformaccepts feature rows;fit_transform_distancesaccepts 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 isO(n²)and bounded-sweep time isO(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).
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
Roadmap
- Approximate k-NN (NN-Descent) for larger datasets in
raso-umap
License
MIT — see LICENSE.
Additional dimensionality reduction methods
use ;
// x is an ndarray feature matrix; choose k < n_samples for graph methods.
let linear = new.n_components.fit_transform?;
let nonlinear = new.n_components
.kernel.fit_transform?;
let spectral = new.n_neighbors.fit_transform?;
let geodesic = new.n_neighbors.fit_transform?;
let pairwise = new.n_neighbors.random_state.fit_transform?;
- 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
transformandinverse_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
transformuses 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()andnormalized_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
transformextends 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
=
=
=
=
=
=
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.