graph_cluster() clusters a matrix, compact graph, or file-backed input
with a native
multilevel Louvain implementation, a Leiden local-move/refine/aggregate
implementation. Louvain and Leiden have CPU, CUDA, and Metal
implementations. No Python,
igraph, cuGraph, or external clustering function is called at run time.
Usage
graph_cluster(
graph,
method = c("leiden", "louvain"),
backend = NULL,
resolution = 1,
n_iterations = 10L,
n_runs = 1L,
steps = 4L,
seed = 1L,
layout_merge = NULL,
projection = NULL,
small_groups = NULL,
n.cores = 1L,
devices = NULL,
parallel.mode = c("restarts", "fit"),
massive = NULL,
storage = NULL,
landmarks = NULL,
k = 30L,
vote_k = k,
target_recall = NULL,
...
)Arguments
- graph
A resident data matrix,
fastEmbedR_graph, file-backed matrix or prepared file-backed graph. An edge-list list withfrom,to,weight, andn_verticesis also accepted. Data matrices build a KNN graph first; prepared graphs reuse their existing edges.- method
"leiden"or"louvain".- backend
Execution backend.
"cuda"and"metal"are available for Louvain and Leiden only and fail explicitly if the requested accelerator was not compiled or is unavailable. They never fall back to CPU.- resolution
Positive finite modularity resolution(s). A vector automatically enables consensus across all resolution-seed combinations. The first value controls final clustering on the reweighted graph.
- n_iterations
Maximum local-moving passes for Louvain and Leiden.
- n_runs
Independent seeded Louvain/Leiden runs; the highest-modularity result is returned for scalar controls. Must be 1 with vector controls; use
seedto specify consensus repeats.- steps
Reserved legacy control; only the default is accepted.
- seed
Finite integer seed(s). A vector automatically enables consensus; each seed is tested once per supplied resolution. The first seed controls the final clustering. Scalars preserve ordinary clustering.
- layout_merge
Optional list with a two-column
layout(matrix orfastEmbedR_embedding),min_connectivity(default 0.2),max_stretch(default 2), andmin_cross_edges(default 2). Merging requires both original-graph connectivity and layout-edge continuity. Float32 layouts are converted to double for edge scoring. This is an exploratory PAGA-inspired postprocessing rule, not PAGA.- projection
Optional list with an observation-aligned, finite n-by-2
layout(matrix orfastEmbedR_embedding), local-radiusk(default 30),stretch(default 4), andcutoff(default 0.001). Native exact double-precision 2D search finds each point's kth non-self radius. Edge length is divided by the geometric mean of endpoint radii; weights are multiplied byexp(-max(ratio / stretch - 1, 0)^2). Penalties belowcutoffare removed. Float32 layouts are explicitly converted to double; distance calculations remain double precision. The default NULL skips projection weighting. When enabled, it runs after consensus and before final clustering.- small_groups
Optional list with precomputed
knnindices and distances,min_size(default 20), and optional neighbork(default graph construction k, otherwise 30). Small communities are assigned to their nearest supplied neighbor belonging to a large raw community. Distance ties use neighbor-column order. Groups are renumbered by size. Rows without a core neighbor receive label 0 and are reported separately; modularity and connectivity are then NA.min_size = 1preserves all communities. No original feature matrix is used by these options.- n.cores
CPU workers for Louvain/Leiden. With
parallel.mode = "restarts", requires scalar controls andn_runs >= n.cores. Withparallel.mode = "fit", workers propose moves for one shared partition; coarsening and Leiden refinement remain serial.- devices
Optional vector of one or more distinct CUDA device IDs for a coordinated resident fit. One device uses the same algorithm as multiple devices. Requires
backend = "cuda".- parallel.mode
"restarts"preserves parallel independent runs;"fit"parallelizes local moves within one CPU fit.- massive
Optional data mode:
"auto","landmark", or"out_of_core_graph". A file-backed graph selects full-graph mode; a matrix selects auto mode unlessstorage = "file_backed"requests a landmark fit. Resident graphs reject it.- storage
"auto","resident", or"file_backed". When omitted, usesoptions(storage = ...). Explicit"resident"on amassive_matrix()file descriptor loads float32 input after a RAM andmemory_limitcheck; the limit does not bound the subsequent fit. A file-backed matrix needslandmarks; a full file-backed fit needs a prepared graph. These controls are rejected for a resident graph.- landmarks
Optional reference-row fraction, count, or indices for resident data; a count for file-backed data.
FALSEexplicitly selects full clustering for resident data. Prepared graphs reject a landmark selection.- k
Neighbors in a landmark reference graph. Ignored unless
landmarksis supplied. Prepared graphs reject it.- vote_k
Neighbors for assigning non-landmark resident rows. File-backed data and prepared graphs reject it.
- target_recall
Requested KNN tuning tier for data input:
0.9,0.95, or0.99. Prepared graphs retain their KNN provenance.- ...
For file-backed data, storage controls such as
output,chunk_rows,memory_limit,checkpoint,resume, andgpu_storage. When omitted for file-backed input, the memory budget usesoptions(memory_limit = ...), or detected available RAM.
Value
A fastEmbedR_graph_cluster containing one-based membership,
modularity, method, implementation, and run metadata. With
layout_merge, membership_original, modularity_original, and
layout_merge_pairs preserve the unmerged result and decisions.
Graph reweighting adds reweighted_graph and records the native controls
and weighted edge count in parameters. small_groups adds
membership_original, modularity_original, reassigned and
unassigned (one-based row IDs). Reported modularity uses the weighted
graph when reweighting is enabled.
Enhanced workflows record final_resolution, final_seed and
processing_order; consensus metadata records the exact ensemble size.
CUDA returns repeatability = "not_bitwise_deterministic": parallel
community updates can yield different partitions for the same seed.
Coordinated CUDA fits report native graph-build, move, and host-hierarchy
times separately. Move time includes GPU work and host synchronization.
Matrix input with explicit landmarks returns a
fastEmbedR_landmark_clusters result with all-row labels.
Details
When either resolution or seed has length greater than one,
native consensus runs length(resolution) * length(seed) partitions
using the requested method. Existing edge weights are multiplied by
squared coassignment frequencies. Optional projection weighting follows.
Final clustering uses resolution[1] and seed[1]; no additional
resolution or seed is inferred. n_iterations applies to every partition.
small_groups, when supplied, is applied last.
With devices, CUDA partitions graph rows across the selected GPUs.
Every device updates the same partition, with labels synchronized
through host RAM after each color phase. Separate n_runs remain
independent repeats. Consensus and graph reweighting apply to
coordinated partitions and are recorded as host stages.
This experimental route requires device qualification.
CUDA and Metal run Louvain/Leiden partitions on their devices; consensus
edge agreement, exact projection weighting, and small-group assignment
run on the host and are recorded as such. Enhanced options cannot be
combined with layout_merge. Unsupported requests fail explicitly.
These procedures do not request
a fixed group count. Scalar controls with projection = NULL and no
small-group postprocessing retain the ordinary clustering workflow.
Methodological inspiration
Vector-triggered consensus draws on coassignment-based clustering (Lancichinetti and Fortunato, 2012), multiresolution ensembles (Jeub et al., 2018), and sparse consensus construction (Tandon et al., 2019). This package retains only original graph edges and multiplies their weights by squared coassignment frequencies. It does not implement the iterative thresholding, hierarchical consensus/null model, or additional node-pair sampling of those published algorithms.
projection is a custom layout-based edge penalty. Its local distance
normalization is related to the local-scaling principle of Zelnik-Manor
and Perona (2004); PARC (Stassen et al., 2020) motivates refining graph
edges before community detection. The soft-margin penalty on supplied
UMAP/t-SNE coordinates is package-specific. It does not implement
self-tuning spectral clustering or PARC's pruning procedure.
References
Blondel VD, Guillaume JL, Lambiotte R, Lefebvre E. Fast unfolding of communities in large networks. J Stat Mech. 2008;2008:P10008.
Traag VA, Waltman L, van Eck NJ. From Louvain to Leiden: guaranteeing well-connected communities. Sci Rep. 2019;9:5233.
Pons P, Latapy M. Computing communities in large networks using random walks. J Graph Algorithms Appl. 2006;10:191-218.
Wolf FA et al. PAGA: graph abstraction reconciles clustering with trajectory inference through a topology preserving map of single cells. Genome Biol. 2019;20:59. doi:10.1186/s13059-019-1663-x.
Lancichinetti A, Fortunato S. Consensus clustering in complex networks. Sci Rep. 2012;2:336. doi:10.1038/srep00336 .
Jeub LGS, Sporns O, Fortunato S. Multiresolution consensus clustering in networks. Sci Rep. 2018;8:3259. doi:10.1038/s41598-018-21352-7 .
Tandon A, Albeshri A, Thayananthan V, Alhalabi W, Fortunato S. Fast consensus clustering in complex networks. Phys Rev E. 2019;99:042301. doi:10.1103/PhysRevE.99.042301 .
Zelnik-Manor L, Perona P. Self-tuning spectral clustering. Adv Neural Inf Process Syst. 2004;17:1601-1608.
Stassen SV et al. PARC: ultrafast and accurate clustering of phenotypic data of millions of single cells. Bioinformatics. 2020;36:2778-2786. doi:10.1093/bioinformatics/btaa042 .