Learn R Programming

grip

grip embeds graphs in Euclidean space and helps assess how well the resulting coordinates preserve graph distances and local structure.

Start with metric multidimensional scaling (MDS) using stochastic gradient descent (SGD). Use full metric MDS when pairwise graph distances are affordable, and sparse metric MDS for larger problems. Targets can be unweighted hop distances or shortest-path distances defined by positive edge lengths.

The package also provides classical MDS, multiscale GRIP layouts, alternative optimization methods, and tools for comparing and visualizing embeddings. Use 2D or 3D for visualization; metric MDS also supports higher dimensions.

Get started · Choose a task · Sparse MDS · Explore the gallery

Installation

The workflows below target grip 0.3.0. While this update is awaiting CRAN, install from GitHub. Observation-based Euclidean and geodesic sparse preparation also requires dgraphs 0.4.0 or later. Building from source requires R and a C++17 toolchain (Rtools on Windows or command-line developer tools on macOS).

install.packages("remotes")
remotes::install_github("pgajer/grip", build_vignettes = FALSE)

Use the online guides, or install Pandoc, knitr, and rmarkdown and set build_vignettes = TRUE for offline guides. List available installed guides with vignette(package = "grip").

The native SGD backend needs no additional runtime package. Optional viewers and numerical backends are needed only for workflows that use them; install smacof to use metric.mds(backend = "smacof").

First embedding

Draw a 494-vertex power network from the SuiteSparse Matrix Collection. The graph is bundled with grip: no download or matrix conversion is needed. Browse all 85 bundled graphs with suitesparse.graphs(); its gallery column identifies the 80 curated comparison graphs. Edges come from the matrix’s nonzero off-diagonal pattern and have unit length; matrix coefficients are not used as distances. Targets are shortest-path hop counts.

library(grip)
g <- suitesparse.graph("494_bus")

fit <- metric.mds(
  edges = g$edges, n = g$n, dim = 3,
  backend = "sgd", seed = 11
)
#> Warning: Selected metric.mds() start terminated with iteration_limit; budget
#> exhaustion does not certify convergence; inspect metadata$starts
coords <- fit$coords
edges <- g$edges
plot.layout(fit$coords, edges = g$edges, projection = "ortho")

Rotate and explore the power network in the interactive gallery (its saved fits have their own stated settings). For an interactive view of this exact fit in R:

ivue::plot3D.plain(fit$coords,
  layers = list(ivue::layer3D.edges(g$edges)))

This is an embedding of network connectivity, not a geographic map of the power system. Inspect fit$metadata$starts: an iteration-limit warning means coordinates were returned without meeting the stopping criterion. A returned embedding does not establish convergence or an optimum.

Choosing a workflow

TaskStarting point
Fit unweighted or weighted graph distancesmetric.mds(..., backend = "sgd")
Avoid a full pairwise distance matrixmetric.mds(..., backend = "sgd", approximation = "sparse")
Assess an embeddingscore.layout() and the diagnostics relevant to the application
Compare optimization methodsSGD versus backend = "smacof", on the same full-MDS targets and weights
Explore alternative layoutsClassical MDS or multiscale GRIP; see below

Weighted graph distances

Supply positive edge lengths, not connection strengths. Full MDS uses shortest paths computed from these lengths.

weighted.edges <- cbind(1:3, 2:4)
weighted.fit <- metric.mds(
  edges = weighted.edges, n = 4, edge.weights = c(1, 2, 1.5),
  dim = 2, backend = "sgd", seed = 12, diagnostics = FALSE
)
#> Warning: Selected metric.mds() start terminated with iteration_limit; budget
#> exhaustion does not certify convergence; inspect metadata$starts

Sparse MDS for larger graphs

Sparse mode retains graph edges and represents longer-range influences using selected vertices called pivots. Pass graph inputs directly rather than preparing a dense distance matrix first.

large.edges <- edges.mesh(20, 20)
sparse.fit <- metric.mds(
  edges = large.edges, n = 400, dim = 3,
  backend = "sgd", approximation = "sparse", seed = 3,
  sparse.control = list(n.pivots = 32), max.iter = 100
)

This modest example demonstrates the API; it is not a threshold for switching to sparse mode. Choose according to graph size, memory and accuracy needs. More pivots cost more and do not guarantee improvement in every run.

Sparse mode currently requires a connected graph, uses inverse-squared stress weights, and supports SGD only. Its fitted proxy stress is not directly comparable with full-MDS stress. For weighted graphs, a supplied edge longer than an alternative route can also have a different target in sparse and full MDS. See the sparse guide for constraints, diagnostics and measured examples.

Assess the result

Evaluate the aspect of geometry that matters to the application, rather than choosing a drawing by appearance alone.

quality <- score.layout(coords, edges = edges, n = g$n,
                        sample.size.stress = 200, stress.seed = 11,
                        edge.crossings = "never")
quality[, c("sampled.stress", "edge.length.cv")]
#>   sampled.stress edge.length.cv
#> 1      0.1258268      0.3295209

Sampled stress compares drawn separations with graph hop distances after fitting a common scale; zero means exact agreement on the sampled pairs. The edge-length coefficient of variation measures relative variation in drawn edge lengths, useful here because the graph is unweighted. Neither measure certifies recovery of a reference shape, and this assessment stress need not match the optimizer’s weighted objective.

For method comparisons, hold graph inputs, target distances and evaluation pairs fixed where applicable. Report seeds and computational budgets. For sparse MDS, evaluate against independently selected shortest-path targets rather than comparing sparse proxy values across pivot counts.

Do not append edge-KK automatically. It changes the fitting objective; retain an additional refinement only when its diagnostics support the intended use. See Choose a score.

Other layout methods

  • classical.mds() performs classical scaling.
  • metric.mds(backend = "smacof") provides an alternative full-MDS optimizer.
  • grip(metric = "hop") and grip(metric = "edge_length") provide multiscale GRIP layouts. weighted.grip.nd() supports higher-dimensional weighted GRIP.
  • trace.grip() records the GRIP construction process.
  • edge.kk() provides optional edge-length refinement. Geodesic-KK helpers are advanced experimental tools; consult their individual references.

GRIP presets ("mesh", "carpet", "tree", "torus") configure that algorithm, not metric MDS. For GRIP specifically, metric = "hop" uses hops for hierarchy and neighborhoods; metric = "edge_length" uses supplied positive lengths throughout its weighted shortest-path hierarchy. See the function guide.

Comparing GRIP presets

compare.layouts() can compare GRIP candidates across seeds. The example below compares GRIP presets; it does not compare SGD, sparse MDS and GRIP.

comparison.edges <- edges.mesh(4, 5)
cmp <- compare.layouts(comparison.edges, n = 20, dim = 2,
                       candidates = c("default", "mesh"), seeds = 1:3)
cmp$summary[, c("candidate", "score.composite", "sampled.stress.mean")]

Gallery

A completed Sierpinski triangle layout. Play the trace on the website to see vertices introduced and refined.

This construction animation illustrates GRIP, an alternative method in the package. The showcase recipes also include carpet traces and saddle rotations. Construction traces show algorithm steps; rotations show saved coordinates. Each example retains its actual fitting provenance.

Documentation

Start with help("grip-package", package = "grip"), the getting-started guide, or the function guide.

Use vignette(package = "grip") to discover offline guides in an installation built with vignettes. The website includes additional articles and galleries.

Citation

Use citation("grip") for the package citation, and cite the methods used in your analysis. Relevant algorithm references include:

License

GPL (>= 3)

Development

The developer map traces graph validation, preparation, engines, results, and displays, and lists source regeneration and full-dependency checks. The recommended embedding workflow is metric.mds() → fit$coords → visualization and independent assessment.

Copy Link

Version

Install

install.packages('grip')

Monthly Downloads

235

Version

0.3.0

License

GPL (>= 3)

Issues

Pull Requests

Stars

Forks

Maintainer

Pawel Gajer

Last Published

November 8th, 2026

Functions in grip (0.3.0)

edge.kk

Optimize an edge-KK local repair layout
edge.length.density.stiffness

Construct edge-length stiffnesses for edge-isometric GMDS layouts
grip-mds-migration

Migrating classical and metric stress MDS workflows
globalrep.weighted.grip

Compute a weighted geometry-aware GRIP layout
graph_generators

Sample graph generators
geodesic.kk

Optimize a layout under the full geodesic KK energy
estimate.preparation

Estimate preparation storage before allocating graph distances
graph.riemannian.star.structure

Build a local Riemannian star structure for Gram-gKK layouts
geometry.diagnostics

Geometry-aware diagnostics against a canonical target
gripui.project.from.compare

Convert compare.layouts() output into a gripui_project
globalrep.grip

Compute a GRIP layout with coarse global repulsion
gripui.project.from.dir

Create a gripui_project from a directory of saved artifacts
grip

Compute a GRIP layout
grip-package

grip: Graph dRawing with Intelligent Placement
gripui.validate.project

Validate a gripui_project
gripui.app

Build the gripui Shiny application
gripui.project

Create a normalized gripui project object
gripui.family.app

Build the graph-family geometry explorer Shiny application
gripui.graph.family.catalog

Catalog of graph families for the geometry explorer app
irregular_ball_solid_helpers

Weighted irregular ball solid helpers
irregular_annulus_surface_helpers

Weighted irregular annulus surface helpers
hmp.u01.gc.coarse

HMP/U01 Coarsened Giant-Component Graph
kary_tree_weighted_graph_helpers

Intrinsically weighted k-ary tree helpers
grip-0.2-migration

Migrate code to the grip 0.2 API
irregular_sphere_surface_helpers

Weighted irregular sphere surface helpers
irregular_double_torus_surface_helpers

Weighted irregular double-torus surface helpers
irregular_rectangle_surface_helpers

Irregular rectangle surface helpers
hmp.gc

HMP Illumina 16S Giant-Component Graph
irregular_torus_surface_helpers

Weighted irregular torus surface helpers
kernel.gram.gkk

Optimize a kernel Gram-gKK layout
irregular_pair_of_pants_surface_helpers

Weighted irregular pair-of-pants surface helpers
irregular_shell_solid_helpers

Weighted irregular shell solid helpers
occupied_mesh_surface_helpers

Occupied-mesh and perforated-grid helpers
landmark.mds.constraints

Construct sparse MDS targets from landmark distances
menger_sponge_surface_helpers

Weighted Menger sponge surface helpers
mask_pattern_helpers

Mask pattern helpers for recursive grid families
legacy.grip

Compute the legacy GRIP layout
landmark.geodesic.kk

Optimize a layout under the landmark geodesic KK energy
mesh_surface_helpers

Weighted mesh surface helpers
layout.coords

Extract coordinates from a layout result
misf.geodesic.kk

Optimize an embedding with the MISF-based geodesic-KK pipeline
metric.mds

Metric stress MDS using stochastic gradient descent or SMACOF
prepare.misf.geodesic.kk

Prepare a MISF-based multiscale geodesic-KK object
prepare.landmark.geodesic.kk

Prepare sparse landmark-geodesic KK data for repeated layout evaluation
prepare.graph.geodesic.mds

Prepare a graph-first geodesic-MDS path cache
plot.layout

Quick plot for graph layouts
perforated_grid_helpers

Deterministic perforated-grid occupancy helpers
params.from.summary

Extract layout parameters from a comparison summary row
porous_cube_surface_helpers

Weighted porous cube-mask surface helpers
prepare.edge.kk

Prepare an edge-only graph for edge-KK repair
prepare.sparse.mds

Prepare sparse metric MDS directly from observations
prepare.geodesic.kk

Prepare full geodesic KK data for repeated layout evaluation
repulsive.state

Evaluate a pure repulsive layout objective
recursive_mask_grid_surface_helpers

Weighted recursive mask-grid surface helpers
recursive_triangle_mask_surface_helpers

Weighted recursive triangle-mask surface helpers
recursive_tetrahedron_mask_surface_helpers

Weighted recursive tetrahedron-mask surface helpers
project.3d

Project 3D coordinates to 2D for static plotting
recursive_cube_mask_surface_helpers

Weighted recursive cube-mask surface helpers
print.grip_gmds_layout

Print a geodesic-MDS layout summary
print.grip_misf

Print a multiscale hierarchy summary
run.gripui.family

Run the graph-family geometry explorer Shiny application
score.gmds

Score a layout with the common GMDS diagnostic panel
run.gripui

Run the gripui Shiny application
sampled_rectangle_surface_helpers

Sampled rectangle surface helpers
repulsive.stage

Optimize one pure repulsive layout stage
score.misf.geodesic.kk

Score a MISF-based geodesic-KK fit
score.coordinates

Score coordinates against corresponding reference observations
score.layout

Score a single layout using graph-aware quality heuristics
score.geodesic.kk

Score a layout under the full geodesic KK energy
score.landmark.geodesic.kk

Score a layout under the landmark geodesic KK energy
score.surface

Estimate symmetric area-weighted distance between triangular surfaces
sierpinski_carpet_surface_helpers

Weighted Sierpinski carpet surface helpers
trace.grip

Trace a GRIP layout
sierpinski_tetrahedron_surface_helpers

Weighted Sierpinski tetrahedron surface helpers
tetrahedron_mask_helpers

Tetrahedron mask helpers for recursive gasket families
torus_surface_helpers

Weighted torus surface helpers
sierpinski_triangle_surface_helpers

Weighted Sierpinski triangle surface helpers
triangle_mask_helpers

Triangle mask helpers for recursive gasket families
sphere_surface_helpers

Weighted sphere surface helpers
vicsek_surface_helpers

Weighted Vicsek surface helpers
triangulated_pair_of_pants_surface_helpers

Weighted triangulated pair-of-pants surface helpers
triangulated_annulus_surface_helpers

Weighted triangulated annulus surface helpers
triangulated_polyhedron_surface_helpers

Weighted triangulated polyhedron surface helpers
suitesparse.graph

Bundled SuiteSparse Graphs
trace.legacy.grip

Compute a trace for the legacy GRIP layout
weighted.grip.nd

Weighted GRIP layout in arbitrary dimensions
compare.layouts

Compare multiple layout candidates across seeds
edge.repulsive.stage

Optimize one edge-isometric repulsive unfolding stage
edge.repulsive.state

Evaluate an edge-isometric repulsive unfolding objective
classical.mds

Classical-MDS baseline layout for GMDS experiments
cube_mask_pattern_helpers

Cube mask pattern helpers for recursive porous families
build.misf

Build a maximal independent set filtration (MISF) for a graph
cylinder_surface_helpers

Weighted cylinder surface helpers
build.weighted.misf

Build a weighted MISF hierarchy