Skip to contents

dgraphs turns numerical observations into graphs and provides tools to inspect their connectivity, paths and geometry. Start with the question you want to answer. Use the task map, follow a small workflow, then consult the complete catalog.

Choose a starting point

Your question Entry point Choice that matters
Which nearby observations should be linked? create.mknn.graph() or create.sknn.graph() Mutual neighbors require agreement; symmetric neighbors accept either direction.
Can I adapt a Gabriel graph while retaining connectivity? create.ian.graph() Build the optional IAN backend first; inspect completion, graphs and affinity diagnostics.
How should support adapt to sampling density? create.rknn.graph() or create.cknn.graph() Fixed radius, local radius rules, or a geometric mean of local scales.
Should overlapping neighborhoods define edges? create.single.iknn.graph() Intersection graphs can connect points that are not direct nearest neighbors.
How sensitive is my graph to neighborhood size? Plural constructors such as create.sknn.graphs() Inspect a parameter sequence and its component counts.
Do I need paths between every pair? graph.connected.components(), then constructor repair controls Bridge edges make a modeling assumption across gaps.
How far apart are vertices along this graph? graph.geodesic.distances() Edge values must represent additive lengths or costs.
Does the graph preserve known distances? summarize.isometry.deviation() Requires a reference distance matrix with matching vertex order.
Do I need coordinates for a graph? graph.embedding() or graph.spectral.embedding() A visualization layout and a spectral representation serve different purposes.
How can I generate points with known geometry? sample.synthetic.geometry() Pair a geometry with a compatible sampling specification.

For powered path costs and complete-versus-restricted comparisons, read Density-sensitive paths with Fermat distances.

A first graph

Use a finite numeric matrix with observations in rows. This example samples a circle, constructs a symmetric nearest-neighbor graph, requests connectivity repair, and measures distances on the final graph.

library(dgraphs)
points <- sample.synthetic.geometry(
  synthetic.circle(),
  synthetic.sampling.grid.interval(0, 2 * pi, endpoints = "exclude.lower"),
  n = 24, seed = 17
)
X <- points$predictors
graph <- create.sknn.graph(X, k = 2, connect.components = TRUE)
print(graph)
#> Symmetric kNN graph
#> Number of vertices: 24 
#> Number of edges: 24 
#> k: 2 
#> Connected components before MST augmentation: 1 
#> Connected components after MST augmentation: 1 
#> MST bridge edges added: 0 
#> Connection method: component.mst 
#> Bridge method: none 
#> Neighbor method: exact
length(unique(graph.connected.components(graph)))
#> [1] 1
D <- graph.geodesic.distances(graph)
round(D[1:4, 1:4], 3)
#>       [,1]  [,2]  [,3]  [,4]
#> [1,] 0.000 0.261 0.522 0.783
#> [2,] 0.261 0.000 0.261 0.522
#> [3,] 0.522 0.261 0.000 0.261
#> [4,] 0.783 0.522 0.261 0.000
ig <- as_igraph(graph)
c(vertices = igraph::vcount(ig), edges = igraph::ecount(ig))
#> vertices    edges 
#>       24       24

Distances here sum straight chords between observed coordinates. They approximate circular arc distances through a finite graph; they are not exact continuous arc lengths. For a longer comparison of graph families, repair and diagnostics, read Constructing and Diagnosing Data-Derived Graphs. For sampling and embedding details, read Synthetic geometry and point sampling.

Constructing a standard graph

Use create.graph(type, ...) when you want a familiar topology or a small example. The required type selects the graph; arguments following n must be named. Every result uses the same graph accessors as a data-derived graph.

Type Arguments Edge lengths
"empty" n (zero allowed) Absent
"complete" n Absent
"chain" n or x; optional span = 1, y One, or absolute coordinate differences
"cycle" n >= 3 Absent
"complete_bipartite" sizes = c(n1, n2) Absent
"star" arms: positive edge counts along each arm Absent
"random" n, mean.degree; optional connected = TRUE, seed Independent uniform lengths on [0.5, 1.5]
"circle" n >= 3; optional sampling, edge.length, seed Shorter unit-circle arcs (default) or chords
standard <- list(
  empty = create.graph("empty", n = 5),
  complete = create.graph("complete", n = 5),
  chain = create.graph("chain", n = 5, span = 2, labels = 101:105),
  cycle = create.graph("cycle", n = 5),
  complete_bipartite = create.graph("complete_bipartite", sizes = c(2, 3)),
  star = create.graph("star", arms = c(1, 2, 1)),
  random = create.graph("random", n = 5, mean.degree = 2, seed = 23),
  circle = create.graph("circle", n = 5, sampling = "uniform",
                        edge.length = "chord")
)
knitr::kable(data.frame(
  type = names(standard),
  vertices = vapply(standard, graph.order, integer(1)),
  edges = vapply(standard, function(g) nrow(graph.edges(g)), integer(1)),
  stored.lengths = vapply(standard, function(g) !is.null(graph.lengths(g)), logical(1))
), row.names = FALSE)
type vertices edges stored.lengths
empty 5 0 FALSE
complete 5 10 FALSE
chain 5 7 TRUE
cycle 5 5 FALSE
complete_bipartite 5 6 FALSE
star 5 4 FALSE
random 5 5 TRUE
circle 5 5 TRUE

For chains, span counts positions on each side, so an interior vertex has at most 2 * span neighbors. This differs from k in nearest-neighbor workflows. Optional x sorts vertices by coordinate, with ties resolved by input position; y and labels follow the same ordering. The sorted-to-input mapping is metadata$order. An ordinary star has all arm counts equal to one; larger counts subdivide its arms.

A cycle describes topology. A circle also records unit-circle coordinates in metadata$coordinates and angles in metadata$angles. Circle sampling is "random" by default; "uniform" spaces angles equally. Choose edge.length = "chord" for Euclidean edge lengths or "arc" for shorter circular arcs. A shorter arc can cross an unsampled gap; graph shortest paths still follow the edges actually present. Arc lengths are measured in radians on the unit circle, not squared distances or conductances.

Random graphs have floor(n * mean.degree / 2) edges. A connected graph needs at least n - 1, and an impossible request errors. With connected = TRUE, a growing random tree precedes additional edges; the result is not a uniform draw from all connected graphs. With connected = FALSE, edges are sampled uniformly without replacement from all vertex pairs. Candidate storage is quadratic in the number of vertices, so this generator is intended for small examples. For both random graphs and randomly sampled circles, an explicit seed restores the caller’s random state after generation; seed = NULL uses and advances the current stream. Uniform circle sampling uses no random numbers. Unknown or irrelevant arguments error instead of being ignored.

Conventions that affect your choice

A common graph object

Every graph constructor returns a dgraph, including basic fixtures. Use graph.adjacency(graph) for its neighbor lists, graph.lengths(graph) for aligned lengths, and graph.edges(graph) for one row per undirected edge. graph.order(graph) includes isolated vertices. A bare adj.list has one integer vector per vertex, containing 1-based neighbor indices; length.list gives the corresponding finite, nonnegative lengths.

dgraph(adj.list, length.list) validates reciprocal edges and values, rejects duplicates and self-loops, and sorts neighbors and values together. Omit length.list for topology alone. A stored zero-length edge remains an edge. as_igraph(graph) preserves isolates, lengths as the length attribute, and other named edge attributes. For igraph distance calculations, explicitly use weights = igraph::E(ig)$length. Raw-list matrix conversions retain weight.list for quantities that need not represent distances.

Path-search results contain their graph in $graph and paths in $shortest.paths; a parameter sequence contains separate graph objects. Subgraphs use compact indices and record metadata$original.vertices. create.graph(type, ..., labels = ...) assigns vertex labels independently of adjacency indices. For example, labels = 101:110 names ten vertices without changing their internal indices 1:10.

Neighborhood sizes and edge quantities

All sequence constructors take an explicit, strictly increasing k.values vector with 1 <= k < n. In coordinate and graph-geodesic intersection workflows, k counts other vertices. Each cover explicitly includes its source plus those neighbors. Equal distances are resolved by vertex index, including coincident observations. Coordinate ANN search uses an exact fallback when its boundary candidates are tied. The specialized knn.metric = "linf.simplex" search currently evaluates all candidates to honor the same tie rule, with quadratic distance-evaluation cost.

X.line <- matrix(c(0, 1, 3, 6), ncol = 1)
initial <- create.single.iknn.graph(X.line, k = 1, prune.method = "none",
                                  connect.components = FALSE, verbose = FALSE)
rebuilt <- create.geodesic.iknn.graph(initial, k = 1)
rebuilt$metadata$neighborhood
#> $k
#> [1] 1
#> 
#> $effective.k
#> [1] 1 1 1 1
#> 
#> $metric
#> [1] "graph.geodesic"
#> 
#> $self
#> [1] "explicit"
#> 
#> $ties
#> [1] "distance.then.vertex.index"
#> 
#> $convention.version
#> [1] 3

Graph-geodesic construction errors if any component has fewer than k + 1 vertices. Choose small.component = "truncate" to use all reachable other vertices instead; metadata$neighborhood$effective.k records the count for each vertex, including zero for isolates. Iterated construction applies the same requested k and component policy at every rebuild.

Construction Edge-length contract
Mutual and symmetric kNN Euclidean distance between endpoints.
Fixed/adaptive radius and continuous kNN Euclidean distance; radius rules govern which edges exist.
Coordinate intersection kNN Minimum summed metric distance through a common cover member, in working coordinates after any PCA.
Geodesic intersection kNN Previous-graph shortest-path distance between the new endpoints.
Nerve of arbitrary sets No lengths; cardinality of overlap is the overlap edge attribute.

An overlap score or conductance is not a travel distance. Read named attributes with graph.edge.attribute(graph, "overlap"), or the corresponding column of graph.edges(graph). A length-based operation rejects a graph with no lengths; graph.geodesic.distances(graph, distance = "hop") explicitly requests unweighted distance. graph.spectrum(graph) uses the unweighted Laplacian. graph.embedding(graph) is unweighted by default; choose an edge.attribute and transform = "identity" or "reciprocal" explicitly. Layout values must be strictly positive, so zero lengths require a separate, explicit choice of layout quantity.

Connectivity, stages and cost

Mutual, symmetric and radius constructors can leave components separate. Request connect.components = TRUE when bridges are appropriate. Exact component-MST repair joins components through shortest Euclidean bridges; the ANN candidate version can fall back to exact search. A global minimum spanning tree is another repair option. join.graphs() identifies one vertex from each of two graphs and preserves aligned lengths and attributes.

graph.stages(graph) lists the stored stages. Every graph has final; constructors may additionally retain raw, pruned, raw.repaired, pruned.repaired and repaired.pruned. Pass the same stage to any accessor, as_igraph() or graph.geodesic.distances(). A missing stage errors, and stage selection never prunes, repairs or reconstructs a graph. The geodesic intersection constructor stores only final because it performs no pruning or repair. Symmetric kNN’s graph.detail = "minimal" requires both disabled.

Disconnected pairs have infinite distances. All-pairs distances require a quadratic-size matrix; request selected vertices when possible. Geometric pruning and exact component bridging can be expensive even with ANN neighbor search. Native construction is serial; thread controls do not promise native parallel execution.

Distances and stored routes

Use graph.geodesic.distances() for a matrix of distances. Supply exactly one of an existing graph or a coordinate matrix points. With coordinates, graph.type = "sknn" requires an explicit k and builds a symmetric kNN graph without pruning or connectivity repair. graph.type = "mst" builds a Euclidean minimum spanning tree and does not accept k. Setting k = 1 never changes the construction method. Coincident observations remain connected by zero-length edges when selected by the construction.

line.points <- matrix(c(0, 0, 1, 10, 11), ncol = 1)
D.tree <- graph.geodesic.distances(points = line.points, graph.type = "mst")
D.neighbors <- graph.geodesic.distances(points = line.points,
                                       graph.type = "sknn", k = 1)
knitr::kable(data.frame(
  pair = c("Coincident observations", "First to last observation"),
  tree.distance = c(D.tree[1, 2], D.tree[1, 5]),
  symmetric.neighbor.distance = c(D.neighbors[1, 2], D.neighbors[1, 5])
), row.names = FALSE, col.names = c("Pair", "Tree distance", "Symmetric kNN distance"))
Pair Tree distance Symmetric kNN distance
Coincident observations 0 0
First to last observation 11 Inf

Both calculations are exact shortest-path distances on their chosen graphs. Neither construction guarantees exact continuous manifold geodesics. The symmetric-neighbor example has disconnected components, represented by Inf. vertices selects matrix rows and columns in the requested order; paths may still pass through any vertex in the graph. distance = "hop" counts edges; distance = "length" requires stored lengths. To reuse a graph or choose additional construction options, construct it first and pass graph = g.

Use create.path.graph() when the routes themselves matter. Its h.values argument specifies strictly increasing positive integer maximum hop counts; a hop traverses one edge. It always returns a named collection, including when only one limit is requested. Select a member before retrieving a route.

weighted.graph <- dgraph(
  list(c(2L, 3L), c(1L, 3L, 4L), c(1L, 2L), 2L),
  list(c(5, 1), c(5, 1, 1), c(1, 1), 1))
paths <- create.path.graph(weighted.graph, h.values = c(2, 3))
knitr::kable(compare.paths(paths, from = 1, to = 4)[,
  c("h", "path_exists", "path_length", "n_hops")], row.names = FALSE,
  col.names = c("Hop limit", "Route exists", "Route length", "Hops used"))
Hop limit Route exists Route length Hops used
2 TRUE 6 2
3 TRUE 3 3
get.shortest.path(paths[["h_2"]], from = 1, to = 4)
#> $path
#> [1] 1 2 4
#> 
#> $length
#> [1] 6
#> 
#> $hops
#> [1] 2
get.shortest.path(paths[["h_3"]], from = 4, to = 1)
#> $path
#> [1] 4 2 3 1
#> 
#> $length
#> [1] 3
#> 
#> $hops
#> [1] 3

With two hops, the best route has length 6; allowing three hops lowers it to 3. The returned route’s edges, stored length and hop count agree. Each result stores a graph of reachable pairs in $graph, with a hops edge attribute. get.shortest.path() returns a vertex sequence, length and hop count, or NULL when the pair is unreachable within the selected limit. Both directions are supported; a vertex’s route to itself has length and hop count zero. For equal-length routes, fewer hops are preferred. These all-pairs route collections can require substantial memory; use modest hop limits when possible.

For a path expressed as coordinates, path.length() sums Euclidean segment lengths and subdivide.path() includes both endpoints at equally spaced distances along the polyline. Points on opposite sides of a corner need not have equal straight-line distances from each other.

polyline <- rbind(c(0, 0), c(1, 0), c(1, 2))
path.length(polyline) # 3
#> [1] 3
subdivide.path(polyline, n.subdivision.pts = 5)
#>      [,1] [,2]
#> [1,] 0.00 0.00
#> [2,] 0.75 0.00
#> [3,] 1.00 0.50
#> [4,] 1.00 1.25
#> [5,] 1.00 2.00
path.dist(1:3, polyline) # normalized cumulative distances: 0, 1/3, 1
#> [1] 0.0000000 0.3333333 1.0000000

The five subdivision rows correspond to arc distances 0, 0.75, 1.5, 2.25 and 3. Repeated consecutive points contribute zero length. For a singleton or a path whose points all coincide, length and normalized cumulative distances are zero, and subdivision repeats that location. Empty paths are rejected; subdivision requires at least two output points.

Positive spectra and spectral coordinates

graph.spectrum() uses the final graph’s unweighted combinatorial Laplacian, regardless of stored lengths. Its nev counts positive eigenpairs, ordered from smallest upward. Every connected component, including an isolated vertex, contributes one omitted zero mode. The spectrum records this count as nullity and preserves component IDs in vertex order. nev = NULL requests all positive modes; use a small explicit count for large graphs. Requests larger than the number of positive modes error rather than silently changing the count.

chain <- create.graph("chain", n = 8)
spectrum <- graph.spectrum(chain, nev = 3)
round(spectrum$evalues, 6)
#> [1] 0.152241 0.585786 1.234633
spectrum$nullity
#> [1] 1
coordinates <- graph.spectral.embedding(spectrum, dim = 2)
dim(coordinates)
#> [1] 8 2

The three eigenvalues are approximately 0.152241, 0.585786 and 1.234633; the embedding uses the first two. use.R = TRUE has the same output contract. Both backends honor return.Laplacian = TRUE and return.dense; sparse output uses the optional Matrix package. The native backend uses a sparse solver for partial spectra and a dense solver for the full spectrum. The R backend uses a full dense solve, so both an R solve and a full native spectrum require quadratic memory. A documented absolute tolerance separates computed zero modes from positive modes; an unresolved separation errors explicitly.

Pass the spectrum object to graph.spectral.embedding(). Its default scale = "none" uses orthonormal eigenvectors; scale = "inverse.sqrt" scales each column by the inverse square root of its eigenvalue. With every positive mode on a connected graph, squared distances in the latter embedding equal effective resistance. With fewer modes it is a truncated representation. Neither coordinate choice generally reproduces graph shortest-path distances. Signs and bases in repeated eigenspaces can differ between solvers. Include the whole tied eigenspace when comparing distances between embeddings.

Disconnected graphs have spectra, but no common embedding is assigned: select a component with create.subgraph(graph, which(spectrum$components == id)), compute its spectrum and embed it separately. Distances between independently embedded components have no defined meaning. Empty and singleton graphs have no positive-dimensional spectral embedding.

Plotting a graph and reusing its layout

graph.embedding() computes coordinates without drawing. The standard plot() method for a dgraph computes a two-dimensional layout only when coordinates are absent and invisibly returns the coordinates actually drawn. Use vertex.values for numeric values mapped through a palette, or vertex.colors for explicit colors; supplying both errors. Constant numeric values use the palette midpoint. Every undirected edge is drawn once.

cycle <- create.graph("cycle", n = 8)
set.seed(4101)
xy <- plot(cycle, vertex.values = seq_len(8), main = "Numeric vertex values")

Graph layout with vertex colors defined by the example; the same coordinates are reused for comparison.

plot(cycle, coordinates = xy, vertex.values = rep(7, 8),
     main = "Same layout, constant values")

Graph layout with vertex colors defined by the example; the same coordinates are reused for comparison.

The same stage controls both layout computation and drawn edges. For three-dimensional coordinates, choose an explicit two-column projection; the plotting method never silently discards a coordinate. Layout generation itself remains available in both two and three dimensions.

set.seed(4102)
xyz <- graph.embedding(cycle, dim = 3)
colnames(xyz) <- c("x", "y", "z")
plot(cycle, coordinates = xyz, projection = c(1, 3), vertex.colors = "navy",
     main = "Explicit x/z projection")

Graph layout with vertex colors defined by the example; the same coordinates are reused for comparison.

Reuse an expensive computation

Keep a constructed graph for repeated graph.geodesic.distances() calls; this reuses its edges, not a memoized distance matrix. Save D yourself when reusing the same distances. Coordinate input constructs a fresh graph for each distance call. Geodesic intersection and iterated intersection workflows deliberately build on existing graph metrics.

create.sknn.graphs() reuses one ANN search across its k values. A single symmetric constructor also accepts ordered, 1-based, non-self knn.index rows with neighbor.method = "ann"; these must correspond to the same input points. Intersection constructors expose knn.cache.path and knn.cache.mode: "read" requires a valid cache, "write" replaces it, and "readwrite" creates a missing cache but rejects an existing invalid one. Format version 3 caches store only non-self neighbors and check point values, row order, metric, working-coordinate preprocessing and maximum k. Old cache formats are rejected. The adaptive-radius sequence has a batched ANN backend. These are distinct contracts; there is no universal public neighbor-cache object shared by all constructors. Internal cache and native solver helpers are not installed public functions to call directly.

Function catalog

The catalog covers all 117 explicit public exports exactly once; 44 registered S3 methods are described separately through object workflows. Internal helpers and development applications are not public entry points. Links open the exact help included with this build, offline.

Each row is one explicit export. Open exact arguments and examples with help("create.sknn.graph", package = "dgraphs"), replacing the name as needed. The package reference manual describes the released version; newly added functions require the corresponding release or development installation.

Graph construction and parameter sequences

Function Purpose
create.ian.graph() Adapt local scales and prune a Gabriel graph, preserving connectivity by default; requires the optional backend.
build.ian.backend() Build the optional pinned IAN module on macOS arm64 and return its path.
create.mknn.graph() Build a mutual Euclidean nearest-neighbor graph, with optional pruning and repair.
create.mknn.graphs() Build mutual-neighbor graphs across a range of neighborhood sizes.
create.sknn.graph() Build a symmetric Euclidean nearest-neighbor graph, with optional pruning and repair.
create.sknn.graphs() Build a symmetric-neighbor sequence using a shared ANN search.
create.rknn.graph() Build a fixed-radius or adaptive-radius Euclidean graph.
create.rknn.graphs() Vary the local neighborhood scale in adaptive-radius graphs.
create.cknn.graph() Build a continuous-kNN graph using geometric-mean local scales.
create.single.iknn.graph() Build one intersection-neighborhood graph with optional pruning.
create.iknn.graphs() Build an intersection-neighborhood sequence and its pruning branches.
create.geodesic.iknn.graph() Rebuild intersection neighborhoods using an existing graph’s distances.
create.iterated.iknn.graphs() Repeat intersection construction in successive graph metrics.
build.iknn.graphs.and.selectk() Select an intersection neighborhood size using structural or label-mixing stability.
create.cmst.graph() Complete a Euclidean minimum spanning tree using an edge-length quantile.
create.threshold.distance.graph() Connect points satisfying a distance threshold.
nerve.graph() Construct a graph from overlaps between sets in a cover.

Basic graphs and representation

Function Purpose
create.graph() Construct standard graph types, labeled chains, random graphs and sampled circles.
dgraph() Validate aligned neighbor, length and attribute lists as an undirected graph.
graph.adjacency() Read the neighbor list for a stored stage.
graph.lengths() Read aligned lengths, or NULL when absent.
graph.edges() Read one ordered row per undirected edge, with lengths and attributes.
graph.order() Count vertices, including isolates.
graph.stages() List stages actually stored in a graph.
graph.edge.attribute() Read an explicitly named edge attribute.
as_igraph() Convert a dgraph stage to an undirected igraph object.
convert.adjacency.list.to.adjacency.matrix() Convert bare neighbor lists to an adjacency matrix.
convert.weighted.adjacency.matrix.to.adjacency.list() Convert a weighted adjacency matrix to aligned lists.
convert.adjacency.to.edge.matrix() Extract an edge matrix and optional aligned weights.
count.edges() Count undirected edges once from reciprocal neighbor lists.
compare.adj.lists() Compare neighbor sets, optionally reporting differences.
edge.diff() Find edges present in one graph but absent from another.
identical.vertex.set.weighted.graph.similarity() Compare weighted graphs on the same vertex set.

Connectivity and graph editing

Function Purpose
graph.connected.components() Assign a component identifier to every vertex.
convert.to.undirected() Add reciprocal links to a directed adjacency list.
rm.self.loops() Remove each vertex from its own neighbor list.
join.graphs() Identify one vertex from each of two graphs.
create.subgraph() Extract the graph induced by selected vertices.
create.grid.graph() Refine graph edges toward approximately uniform spatial spacing.

Paths and distances

Function Purpose
fermat.knn() Find exact complete-graph Fermat nearest neighbors.
create.fermat.sknn.graph() Union-symmetrize exact Fermat neighbor selections.
fermat.distances() Compute complete-graph sample Fermat distances or explicit graph-restricted alternatives.
graph.geodesic.distances() Compute shortest-path distances for a supported graph object and stage.
compute.graph.distance() Compute a weighted shortest-path distance between two vertices.
compute.graph.diameter() Compute a weighted graph diameter.
get.shortest.path() Recover a shortest vertex path.
geodesic.disk() Find a graph neighborhood within a distance radius.
geodesic.knn() Find nearest vertices in a graph metric.
geodesic.knnx() Find graph-metric nearest neighbors for query vertices.
create.path.graph() Construct a collection of path results for one or several hop limits.
create.plm.graph() Build a path-length-matrix graph structure.
compare.paths() Compare paths obtained under different hop limits.
minh.limit() Find a minimum hop limit that permits a path.
path.length() Measure Euclidean length along a coordinate path.
path.dist() Compute normalized cumulative distance along a vertex path.
subdivide.path() Include both endpoints and space points equally along a polyline; repeat the location for zero-length paths.

Edge lengths and pruning

Function Purpose
extract.trajectory.edge.lengths() Extract stored edge lengths along a graph vertex trajectory.
wgraph.prune.long.edges() Prune edges using length constraints on alternative paths.

Diagnostics, endpoints and packing

Function Purpose
compute.graph.summary.pmf() Represent a degree, weight, component-size or label-neighborhood summary as probability masses.
graph.summary.divergence() Compare graph-summary probability masses using a chosen divergence.
jensen.shannon.divergence() Measure Jensen-Shannon divergence between probability distributions.
compute.graph.summary.stability() Track summary divergence between consecutive graphs.
compute.stability.metrics() Summarize structural stability of an intersection-graph sequence.
compute.geodesic.stats() Summarize geodesic growth around grid vertices.
compute.vertex.geodesic.stats() Inspect geodesic growth around one grid vertex.
compute.graph.endpoint.scores() Score directional concentration in a 3D embedding using graph neighborhoods.
detect.graph.endpoints() Select and consolidate candidate geometric endpoints.
geodesic.core.endpoints() Detect endpoints using a graph-geodesic core.
detect.local.extrema() Find graph-local maxima or minima of vertex values.
vertices() Extract vertices through the generic, currently for local-extrema results.
remove.knn.outliers() Identify and remove observations with unusual nearest-neighbor distances.
create.maximal.packing() Select separated vertices at a requested graph scale.
validate.maximal.packing() Check separation and maximality of a vertex packing.
verify.maximal.packing() Verify a packing result using its graph and scale.
isometry.scale() Fit a global scale aligning estimated distances with reference distances.
isometry.rel.rms.error() Measure target-normalized root-mean-square distance error.
isometry.rel.abs.error() Summarize quantiles of relative absolute distance errors.
isometry.distortion.quantiles() Summarize multiplicative distance distortion.
isometry.distance.correlations() Compare estimated and reference distances by correlation.
isometry.geodesic.diagnostics() Diagnose shortcuts and distance-scale-dependent geodesic bias.
summarize.isometry.deviation() Combine scale, error, distortion and correlation diagnostics.

Spectral methods and graph display

Function Purpose
graph.spectrum() Compute the smallest positive Laplacian eigenpairs, with component nullity.
graph.spectral.embedding() Embed a connected graph from its spectrum, with explicit coordinate scaling.
graph.embedding() Compute a graph visualization layout.

Synthetic geometry and embedding

Function Purpose
synthetic.quadform() Specify a flat or quadratic geometry with intrinsic and ambient dimensions.
synthetic.circle() Specify a circle or circular arc.
synthetic.helix() Specify a helical curve.
synthetic.trefoil() Specify the supported trefoil parameterization.
synthetic.sphere.cap() Specify a spherical cap over a planar footprint.
synthetic.torus.patch() Specify a torus patch over two angular parameters.
synthetic.simplex() Specify a compositional simplex with a given number of parts.
synthetic.stratum.point() Specify a zero-dimensional point stratum.
synthetic.stratum.segment() Specify a one-dimensional line-segment stratum.
synthetic.stratum.rectangle() Specify a two-dimensional rectangular stratum.
synthetic.stratified() Assemble compatible strata and optional junction metadata; general sampling is not implemented.
synthetic.point.line.junction() Specify a point and segment junction.
embed.synthetic.geometry() Deterministically map supported latent coordinates to ambient coordinates.
embed.quadform.surface() Lift two-column coordinates using the versioned Geometry Lab quadratic arithmetic.
quadform.gradient() Evaluate gradients of quadratic height functions.
quadform.metric() Evaluate the induced metric of a quadratic geometry.
edge.lengths.synthetic.geometry() Measure lifted straight latent segments; currently supports quadforms only.
validate.synthetic.geometry() Validate a geometry specification or latent coordinate matrix.

Point sampling

Function Purpose
sample.synthetic.geometry() Realize geometry-only points with an explicit seed or random-state plan.
synthetic.sampling.uniform.interval() Specify uniform interval draws and their ordering.
synthetic.sampling.grid.interval() Specify deterministic interval points and endpoint inclusion.
synthetic.sampling.uniform.box() Specify uniform box draws with scalar or coordinate-wise bounds.
synthetic.sampling.uniform.rectangle() Specify two-dimensional rectangle draws.
synthetic.sampling.uniform.disk() Specify parameter-area-uniform disk draws.
synthetic.sampling.truncated.normal() Specify bounded normal draws on an interval.
synthetic.sampling.gapped.uniform() Specify draws across disjoint intervals with allocation controls.
synthetic.sampling.clustered() Specify a fixed number of two-dimensional clusters and observations per cluster.
synthetic.sampling.dirichlet.zeros() Specify compositional draws with a fraction on a structural-zero face.
synthetic.sampling.quadform.lab() Specify versioned quadratic-surface sampling, including surface-area rejection sampling.
validate.synthetic.sampling() Validate a sampling specification and its compatibility with a geometry.

Interactive graph reconstruction explorer

Function Purpose Input and interpretation
explore.graphs() Open the Graph Reconstruction Explorer. A saved benchmark directory, manifest, or registered project name; optional Shiny dependencies.
read.graph.benchmark() Read saved benchmark indexes without launching an app. Existing dggraphui manifests and asset tables; relative paths resolve within the run.
register.graph.project() Add a benchmark to the local project picker. Stores a name and path; scientific assets remain outside the package.

Opening a project reads saved results without refitting. An explicit action can compute a missing weighted layout using grip and save it to a separate user cache. The default display preserves original coordinates with equal x/y/z units. A centered common-scale view preserves proportions; optional per-axis scaling is labeled as distorting proportions. Saved metric tables never change with the display.

Try the installed, deterministic twelve-point circle project:

demo <- system.file("extdata", "graph-explorer-demo", package = "dgraphs")
benchmark <- read.graph.benchmark(demo)
nrow(benchmark$graph_assets)
#> [1] 2

Compare k = 2 with k = 4. The additional chords shorten graph distances relative to exact shorter unit-circle arcs. The saved GRIP layouts visualize the graphs; their apparent circularity is not the distance-error metric.

Object workflows and method help

Call a generic such as print(x), summary(x) or plot(x); R selects its registered S3 method from the object’s class. A class need not support all three operations. For example, print a symmetric graph, summarize a mutual sequence, or plot an intersection stability result. vertices(extrema) extracts vertices from detect.local.extrema() output. Geometry samples have concise print and summary methods; plot their coordinate matrices explicitly. Path-series summaries compare hop limits in a table.

The method links open version-matched help below. From R, the same topics are available through help("print.sknn_graph", package = "dgraphs"). Links inside another package’s help may require online access; dgraphs topics and their examples are included here and work without a network connection.

Generic Object class and detailed method help
print() dgraph; adaptive_radius_graph; build_iknn_graphs_and_selectk; cknn_graph; geodesic_stats; knn.outliers; maximal_packing; mknn_graph; mknn_graphs; mst_completion_graph; packing_validation; path.graph; path.graph.plm; radius_graph; rknn_graphs; sknn_graph; sknn_graphs; summary.knn.outliers; summary.local_extrema; summary.mst_completion_graph; synthetic_geometry_sample; summary.synthetic_geometry_sample; path.graph.series
summary() IkNN; geodesic_stats; iknn_graphs; iterated_iknn_graphs; knn.outliers; local_extrema; mknn_graphs; mst_completion_graph; path.graph; rknn_graphs; vertex_geodesic_stats; synthetic_geometry_sample; path.graph.series
plot() dgraph; IkNNgraphs; build_iknn_graphs_and_selectk; cst_graph_mixing_stats; geodesic_stats; iknn_stability_metrics; vertex_geodesic_stats
vertices() local_extrema

Finding more help

help(package = "dgraphs")
help("dgraphs-package", package = "dgraphs")
vignette(package = "dgraphs")

The organization draws inspiration from the short function-purpose entries and related-help navigation in Hmisc’s overview and its usage examples. The task groups here follow dgraphs’ own API. The source repository’s make audit-guides target checks catalog completeness and method-help coverage against NAMESPACE and the maintained help sources.

Detailed help for this build

These expandable topics are generated from the installed package’s help sources. They are the same documentation opened by help() in R.

as_igraph — detailed help

Title

Convert a dgraph to igraph

Name

as_igraph

Description

Convert a dgraph to igraph

Usage

as_igraph(graph, stage = "final")

Arguments

Value

An undirected igraph. Edge lengths are named length; other attributes retain their names. No implicit weight or unit lengths are added. For metric paths pass weights = igraph::E(g)$length explicitly; for hop distance pass weights = NA.

Examples

graph <- dgraph(list(2L, 1L, integer()), list(0, 0, numeric()))
ig <- as_igraph(graph)
igraph::vcount(ig)
igraph::E(ig)$length
build.ian.backend — detailed help

Title

Build the Optional IAN Backend

Name

build.ian.backend

Description

Compile the pinned IAN and Clarabel sources installed with dgraphs in a new directory. The supported build target is macOS arm64. Setup requires Python 3, Apple’s C++ compiler/SDK, and matching native Cargo/Rust tools (Rust >= 1.77). An initial build needs cached crates or network access. No tools are installed by this function. Compilation is explicit and never starts inside create.ian.graph() or ordinary package installation.

Usage

build.ian.backend(
  build.dir,
  python = "python3",
  cargo = "cargo",
  rustc = "rustc",
  cxx = "clang++",
  offline = FALSE
)

Arguments

Value

The absolute path to dgraphs_ian.so, invisibly. Save this path and pass it to create.ian.graph(…, backend = path). Reuse the built module with the same R installation; rebuild when changing R runtime or backend sources. Build errors retain available logs and raise an R error. No shared package library is modified. Build records identify source files and tool commands.

See Also

create.ian.graph()

Examples

## Not run: 
backend <- build.ian.backend("ian-build")
fit <- create.ian.graph(matrix(c(0, 1, 2), ncol = 1), backend = backend)
stopifnot(fit$complete)

## End(Not run)
build.iknn.graphs.and.selectk — detailed help

Title

Build iKNN Graphs and Select a Neighborhood Size

Name

build.iknn.graphs.and.selectk

Description

Builds an iKNN graph sequence and selects k from structural edit-distance stability, label-mixing stability, or both.

Usage

build.iknn.graphs.and.selectk(
  X,
  k.values,
  method = c("both", "edit", "mixing", "none"),
  pca.dim = 100,
  variance.explained = 0.99,
  trim.disconnected = TRUE,
  edit.min.lcc.frac = 1,
  edit.eps = 0.05,
  labels = NULL,
  perm.blocks = NULL,
  mixing.metric = c("homophily.effect", "homophily.z", "homophily.adjusted",
    "assortativity.effect", "assortativity.z", "homophily", "assortativity",
    "conductance.median", "conductance.wmean"),
  mixing.min.lcc.frac = 0.98,
  mixing.eps = 0.05,
  mixing.require.local.extremum = TRUE,
  mixing.window = 1L,
  n.perm = 200L,
  use.edge.weights = TRUE,
  weights.are.edge.lengths = FALSE,
  affinity.method = c("exp", "inv"),
  affinity.sigma = NULL,
  affinity.sigma.from = c("k.cc.mixing", "k.max.lcc", "k.trim"),
  affinity.eps = 1e-08,
  simplify.multiple = TRUE,
  seed = 1L,
  verbose = TRUE,
  ...
)

Arguments

Value

An object of class “build_iknn_graphs_and_selectk” containing the graph sequence, connectivity diagnostics, selection curves, selected neighborhood sizes, trimming metadata, and call parameters.

Examples

set.seed(1)
x <- matrix(rnorm(60), ncol = 2)
selected <- build.iknn.graphs.and.selectk(x, k.values = seq.int(2, 4),
    method = "edit",
    verbose = FALSE)
selected$k.opt.edit
compare.adj.lists — detailed help

Title

Compare Two Adjacency Lists

Name

compare.adj.lists

Description

Compare Two Adjacency Lists

Usage

compare.adj.lists(adj.list1, adj.list2, verbose = FALSE)

Arguments

Value

TRUE when each vertex has the same neighbor set in both lists, ignoring order; otherwise FALSE.

Examples

graph <- list(c(2L, 3L), 1L, 1L)
compare.adj.lists(graph, list(c(3L, 2L), 1L, 1L))
compare.paths — detailed help

Title

Compare Paths Across Hop Limits

Name

compare.paths

Description

Compare Paths Across Hop Limits

Usage

compare.paths(path.result, from, to)

Arguments

Value

Data frame describing path availability and length by hop limit.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
series <- create.path.graph(dgraph(graph, lengths), h.values = 1:2)
compare.paths(series, from = 1, to = 3)
compute.geodesic.stats — detailed help

Title

Compute Geodesic Statistics for Grid Vertices

Name

compute.geodesic.stats

Description

Analyzes how the number of geodesics scales with radius for each grid vertex. This function helps determine if collapsing/clustering geodesics is necessary and provides insights into the graph structure around grid vertices.

Usage

compute.geodesic.stats(
  adj.list,
  length.list,
  min.radius = 0.2,
  max.radius = 0.5,
  n.steps = 5,
  n.packing.vertices = length(adj.list),
  max.packing.iterations = 20,
  packing.precision = 1e-04,
  verbose = FALSE
)

Arguments

Value

A list of class "geodesic_stats" containing:

radii

Numeric vector. Actual radii used in the analysis.

geodesic_rays

Matrix. Number of geodesic rays for each vertex at each radius.

composite_geodesics

Matrix. Number of composite geodesics for each vertex at each radius.

path_overlap

List of matrices. Overlap statistics for each vertex at each radius.

grid_vertices

Integer vector. The vertices selected as grid vertices.

summary

Data frame. Summary statistics for each radius.

Examples

graph <- create.graph("circle", n = 8, sampling = "uniform")
stats <- compute.geodesic.stats(graph.adjacency(graph), graph.lengths(graph), min.radius = 0.3,
    max.radius = 0.5, n.steps = 2, n.packing.vertices = 4)
stats$summary
compute.graph.diameter — detailed help

Title

Compute a Weighted Graph Diameter

Name

compute.graph.diameter

Description

Compute a Weighted Graph Diameter

Usage

compute.graph.diameter(graph, stage = "final")

Arguments

Value

A list containing the diameter and the farthest path details.

Examples

graph <- list(2L, c(1L, 3L), 2L)
weights <- list(1, c(1, 2), 2)
compute.graph.diameter(dgraph(graph, weights))$diameter
compute.graph.distance — detailed help

Title

Compute a Weighted Shortest-Path Distance

Name

compute.graph.distance

Description

Compute a Weighted Shortest-Path Distance

Usage

compute.graph.distance(graph, i, j, stage = "final")

Arguments

Value

Numeric shortest-path distance.

Examples

graph <- list(2L, c(1L, 3L), 2L)
weights <- list(1, c(1, 2), 2)
compute.graph.distance(i = 1, j = 3, graph = dgraph(graph, weights))
compute.graph.endpoint.scores — detailed help

Title

Compute Graph Endpoint Scores from a 3D Embedding

Name

compute.graph.endpoint.scores

Description

Computes endpointness diagnostics for graph vertices by selecting graph-geodesic neighborhoods and evaluating how concentrated the corresponding 3D embedding directions are. This targets terminal arm tips in an embedding rather than graph-theoretic degree-1 vertices.

For each vertex x, let u_1, , u_m be unit vectors in the embedding from x to graph-geodesic neighbors of x. The function computes:

s_{}(x) = _{i < j} u_i^u_j

s_q(x) = {u_i^u_j : i < j}

m(x) = | _i w_i u_i |

(x) = m(x),

Neighborhoods are selected in graph-geodesic space while directions are taken from the supplied 3D embedding.

Usage

compute.graph.endpoint.scores(
  adj.list,
  length.list,
  layout.3d,
  neighborhood = c("geodesic_k", "geodesic_radius"),
  k = c(10L, 20L, 30L),
  radius = NULL,
  q = 0.1,
  neighbor.weighting = c("uniform", "inverse_distance", "gaussian"),
  gaussian.sigma = NULL,
  min.neighborhood.size = 3L,
  scale.aggregate = c("mean", "median", "min", "max"),
  verbose = FALSE
)

Arguments

Value

A list with aggregated per-vertex scores, per-scale score matrices, and neighborhood diagnostics.

Examples

chain <- create.graph("chain", n = 8)
layout <- cbind(seq_len(8), 0, 0)
scores <- compute.graph.endpoint.scores(graph.adjacency(chain), graph.lengths(chain), layout,
    k = c(2, 3), min.neighborhood.size = 2)
head(scores$summary)
compute.graph.summary.pmf — detailed help

Title

Compute a graph summary as a probability mass function

Name

compute.graph.summary.pmf

Description

Converts a graph-like object into a named probability mass function (PMF) describing one selected graph summary. This provides a standardized bridge between graph objects and divergence functions such as jensen.shannon.divergence().

Supported v1 summaries are:

  • “degree_distribution”

  • “edge_weight_distribution”

  • “component_size_distribution”

  • “neighborhood_label_distribution”

“component_size_distribution” is included primarily as a diagnostic for disconnectedness / fragmentation, not as a general-purpose default stability summary.

Usage

compute.graph.summary.pmf(
  graph,
  summary = c("degree_distribution", "edge_weight_distribution",
    "component_size_distribution", "neighborhood_label_distribution"),
  labels = NULL,
  edge.attribute = "length",
  stage = "final",
  bins = NULL,
  n.bins = 20L,
  bin.method = c("auto", "fixed_width", "fixed_quantile", "explicit"),
  normalize = TRUE,
  support = NULL,
  zero.pad = TRUE,
  return.details = TRUE
)

Arguments

Value

If return.details = TRUE, a list with fields:

  • summary: summary type used.

  • pmf: named probability mass function.

  • support: support of the PMF.

  • counts: named raw-count vector before normalization.

  • metadata: list of summary-specific metadata.

Otherwise, returns the named PMF vector.

Examples

graph <- dgraph(list(c(2L, 3L), 1L, 1L))
compute.graph.summary.pmf(graph, summary = "degree_distribution")
compute.graph.summary.stability — detailed help

Title

Compute graph-summary stability across a graph sequence

Name

compute.graph.summary.stability

Description

Computes a divergence-based stability curve across consecutive graphs in a sequence. This function provides a generalized sequence-level analogue of the degree-profile Jensen-Shannon calculation currently used in compute.stability.metrics().

Usage

compute.graph.summary.stability(
  graphs,
  summary = c("degree_distribution", "edge_weight_distribution",
    "component_size_distribution", "neighborhood_label_distribution"),
  divergence = c("js"),
  labels = NULL,
  summary.args = list(),
  k.values = NULL,
  graph.type = c("geom", "isize"),
  return.details = TRUE
)

Arguments

Value

If return.details = TRUE, a list with fields:

  • summary: summary type used.

  • divergence: divergence type used.

  • k.values: full k sequence.

  • k.transition.values: k values corresponding to consecutive-graph transitions.

  • values: vector of divergence values of length length(k.values) - 1.

  • details: optional pairwise details for each transition.

Otherwise, returns only the divergence vector.

Examples

graphs <- list(
  dgraph(list(2L, c(1L, 3L), 2L)),
  dgraph(list(c(2L, 3L), c(1L, 3L), c(1L, 2L))),
  create.graph("complete", 3)
)
compute.graph.summary.stability(
  graphs,
  summary = "degree_distribution"
)$values
compute.stability.metrics — detailed help

Title

Compute Stability Metrics Across a Sequence of IkNN Graphs

Name

compute.stability.metrics

Description

Computes stability diagnostics across the pruned IkNN graphs produced by create.iknn.graphs(). Metrics include edit distances between consecutive graphs, graph-summary Jensen-Shannon divergence, edge-count diagnostics, local minima, and smoothed trend fits for plotting.

Usage

compute.stability.metrics(
  graphs,
  graph.type = c("geom", "isize"),
  summary = c("degree_distribution", "edge_weight_distribution",
    "component_size_distribution", "neighborhood_label_distribution"),
  divergence = c("js"),
  labels = NULL,
  summary.args = list()
)

Arguments

Value

An object of class “iknn_stability_metrics”.

Examples

set.seed(1)
x <- matrix(rnorm(60), ncol = 2)
graphs <- create.iknn.graphs(x, k.values = seq.int(2, 4), compute.full = TRUE,
    verbose = FALSE)
stability <- compute.stability.metrics(graphs)
stability$edit.distances
compute.vertex.geodesic.stats — detailed help

Title

Compute Geodesic Statistics for a Single Grid Vertex

Name

compute.vertex.geodesic.stats

Description

Analyzes how the number of geodesics scales with radius for a specific grid vertex.

Usage

compute.vertex.geodesic.stats(
  adj.list,
  length.list,
  grid.vertex,
  min.radius = 0.2,
  max.radius = 0.5,
  n.steps = 5,
  n.packing.vertices = length(adj.list),
  packing.precision = 1e-04
)

Arguments

Value

A data frame of class "vertex_geodesic_stats" with columns:

radius

Actual radius used.

rays

Number of geodesic rays within radius.

composite_geodesics

Number of composite geodesics.

overlap_min

Minimum overlap ratio.

overlap_p05

5th percentile overlap ratio.

overlap_p25

25th percentile overlap ratio.

overlap_median

Median overlap ratio.

overlap_p75

75th percentile overlap ratio.

overlap_p95

95th percentile overlap ratio.

overlap_max

Maximum overlap ratio.

Examples

graph <- create.graph("circle", n = 8, sampling = "uniform")
compute.vertex.geodesic.stats(graph.adjacency(graph), graph.lengths(graph),
    grid.vertex = 1, min.radius = 0.3,
    max.radius = 0.5, n.steps = 2)
convert.adjacency.list.to.adjacency.matrix — detailed help

Title

Convert an Adjacency List to an Adjacency Matrix

Name

convert.adjacency.list.to.adjacency.matrix

Description

Convert an Adjacency List to an Adjacency Matrix

Usage

convert.adjacency.list.to.adjacency.matrix(
  adj.list,
  weight.list = NULL,
  mode = "undirected",
  remove.self.loops = TRUE
)

Arguments

Value

Numeric adjacency matrix.

Examples

graph <- list(c(2L, 3L), 1L, 1L)
weights <- list(c(1, 2), 1, 2)
convert.adjacency.list.to.adjacency.matrix(graph, weights)
convert.adjacency.to.edge.matrix — detailed help

Title

Convert an Adjacency List to an Edge Matrix

Name

convert.adjacency.to.edge.matrix

Description

Convert an Adjacency List to an Edge Matrix

Usage

convert.adjacency.to.edge.matrix(adj.list, weight.list = NULL)

Arguments

Value

A list with edge.matrix and weights.

Examples

graph <- list(c(2L, 3L), 1L, 1L)
convert.adjacency.to.edge.matrix(graph)
convert.to.undirected — detailed help

Title

Convert a Directed Adjacency List to an Undirected Adjacency List

Name

convert.to.undirected

Description

Convert a Directed Adjacency List to an Undirected Adjacency List

Usage

convert.to.undirected(adj.list)

Arguments

Value

An adjacency list with reciprocal edges added and duplicate neighbors removed.

Examples

directed <- list(2L, integer(0), 1L)
convert.to.undirected(directed)
convert.weighted.adjacency.matrix.to.adjacency.list — detailed help

Title

Convert a Weighted Adjacency Matrix to Lists

Name

convert.weighted.adjacency.matrix.to.adjacency.list

Description

Convert a Weighted Adjacency Matrix to Lists

Usage

convert.weighted.adjacency.matrix.to.adjacency.list(A)

Arguments

Value

A list with adj.list and weight.list.

Examples

A <- matrix(c(0, 1, 0, 1, 0, 2, 0, 2, 0), nrow = 3)
convert.weighted.adjacency.matrix.to.adjacency.list(A)
count.edges — detailed help

Title

Count Edges in an Undirected Adjacency List

Name

count.edges

Description

Count Edges in an Undirected Adjacency List

Usage

count.edges(adj.list)

Arguments

Value

Number of undirected edges.

Examples

count.edges(list(c(2L, 3L), 1L, 1L))
create.cknn.graph — detailed help

Title

Compute a Continuous-kNN Graph

Name

create.cknn.graph

Description

Creates an undirected continuous-kNN graph using local scale distances. Let _i be the distance from observation i to its k.scale-th non-self nearest neighbor. Vertices are adjacent when

|x_i - x_j|_2 .

This is a convenience wrapper around create.rknn.graph() with type = “adaptive.radius” and radius.rule = “geomean”. It is useful as a named data-derived graph construction in geodesic reconstruction benchmarks.

Usage

create.cknn.graph(
  X,
  k.scale,
  delta = 1,
  radius.search = c("ann", "all.pairs"),
  return.timing = FALSE,
  graph.detail = c("full", "minimal"),
  prune.method = c("none", "local.geodesic", "global.geodesic.ratio"),
  max.path.edge.ratio.deviation.thld = 0.1,
  path.edge.ratio.percentile = 0.5,
  prune.tau = 1.05,
  prune.local.k = NULL,
  with.pruned.edge.stats = FALSE,
  connect.components = FALSE,
  connect.method = c("component.mst", "component.mst.ann", "global.mst"),
  bridge.k = NULL,
  bridge.k.max = NULL,
  bridge.growth = 2
)

Arguments

Value

A list inheriting from “cknn_graph” and “adaptive_radius_graph”. It contains the same lifecycle fields as create.rknn.graph() with type = “adaptive.radius”, radius_rule = “geomean”, radius_factor = delta, and graph_rule = “continuous.knn”.

Examples

X <- matrix(c(0, 1, 3), ncol = 1)
as.matrix(graph.edges(create.cknn.graph(X, k.scale = 1, delta = 1))[, c("from", "to")])
create.cmst.graph — detailed help

Title

Construct a Minimal Spanning Tree (MST) Completion Graph

Name

create.cmst.graph

Description

Constructs a completion of the Minimal Spanning Tree (MST) graph from a numeric data matrix. The graph is constructed in two steps: first, a MST is built connecting all data points using minimal total edge length; then, additional edges are added between any pair of points whose Euclidean distance is less than or equal to a quantile threshold based on the MST edge length distribution.

Usage

create.cmst.graph(
  X,
  q.thld = 0.9,
  pca.dim = 100,
  variance.explained = 0.99,
  verbose = TRUE
)

Arguments

Details

The MST completion process enhances connectivity in the original MST by adding edges between vertices that are "close" according to the distance distribution in the MST. This can be useful for creating more robust graph representations of data that maintain local structure while avoiding long-range connections.

When PCA is applied (either through pca.dim or variance.explained), the data is first centered and projected onto the leading principal components before graph construction. This can significantly reduce computation time for high-dimensional data while preserving the most important variation.

Value

A dgraph with raw (MST) and final (completed) stages. Use graph accessors to inspect topology and lengths; construction details are in metadata.

References

Gower, J. C., & Ross, G. J. S. (1969). Minimum spanning trees and single linkage cluster analysis. Applied Statistics, 18(1), 54-64.

See Also

stats::prcomp() for principal component analysis.

Examples

set.seed(123)
X <- matrix(rnorm(60), nrow = 20, ncol = 3)
graph <- create.cmst.graph(X, verbose = FALSE)
graph.order(graph)
nrow(graph.edges(graph))
create.geodesic.iknn.graph — detailed help

Title

Create a graph-geodesic iKNN graph

Name

create.geodesic.iknn.graph

Description

Each cover contains its source vertex plus its k nearest other vertices. Equal distances are resolved by ascending vertex index. Intersecting covers create edges whose lengths are shortest-path distances in the input graph.

Usage

create.geodesic.iknn.graph(graph, k, small.component = c("error", "truncate"))

Arguments

Value

A dgraph with a final stage, lengths and an overlap edge attribute. metadata$neighborhood records requested and effective sizes and the tie rule.

Examples

graph <- create.graph("chain", 3)
create.geodesic.iknn.graph(graph, k = 1)
create.graph — detailed help

Title

Create a Standard Graph

Name

create.graph

Description

Construct a standard topology or a simple geometric graph. All types return a dgraph() and use compact, 1-based adjacency indices. type is required; type names and names in … must match exactly.

Usage

create.graph(type, n = NULL, ..., labels = NULL)

Arguments

Value

A dgraph with one final stage and construction information in metadata, including type. Inspect it with graph.adjacency(), graph.lengths(), graph.edges() and graph.order().

Types and arguments

empty, complete, cycle

Only n and labels. These return topology without stored lengths. A cycle closes a chain with one edge.

chain

span = 1 connects up to span positions on each side, giving at most 2 * span neighbors. It must be an integer from 1 to n - 1; it does not use the nearest-neighbor meaning of k. Optional finite numeric x orders vertices by coordinate (ties by input position) and supplies absolute coordinate differences as lengths. Without x, lengths are one. Optional vector y requires x and is reordered with it. Metadata contains order (sorted-to-input indices), x.sorted and y.sorted.

complete_bipartite

Required sizes, two positive integers. All pairs across the two parts are connected; there are no within-part edges or stored lengths. Vertices in the first part come first.

star

Required arms, at least two positive integer edge counts. Chains of those lengths share vertex 1 as their center. Thus n = 1 + sum(arms); all-one arms give an ordinary star. Vertices are numbered along successive arms. No lengths are stored.

circle

sampling = “uniform” or “random” (default), edge.length = “arc” (default) or “chord”, and optional seed. Vertices are ordered by angle on the unit circle and consecutive vertices, including last-to-first, are connected. Arc lengths measure the shorter unit-circle arc between endpoints, even when the gap in the sampling order exceeds pi. Chords are Euclidean distances. Metadata contains angles (radians) and coordinates (x/y columns).

random

Required finite mean.degree, connected = TRUE, and optional seed. The edge count is floor(n * mean.degree / 2); ⁠0 <= mean.degree <= n - 1⁠. If connected, this count must be at least n - 1. A randomly ordered growing tree is built first, then a uniform subset of remaining pairs is added. This is not uniform sampling over connected graphs or spanning trees. If disconnected graphs are allowed, a uniform subset of all pairs is sampled. Each undirected edge receives one independent length uniform between 0.5 and 1.5. Candidate-pair storage is quadratic in n; this constructor is intended for small examples. Metadata records requested and realized mean degrees and connectivity.

Random numbers

For random and circle, seed = NULL uses and advances the caller’s current random stream. An explicit nonnegative integer seed makes the call reproducible under the current RNG kind and restores the caller’s RNG state afterwards, including an initially absent state. Uniform circle sampling consumes no random numbers. The richer geometry sampling API has its own seed/state continuation contract; see sample.synthetic.geometry().

Examples

graph.order(create.graph("empty", n = 4))
graph.edges(create.graph("complete", n = 3))
chain <- create.graph("chain", x = c(3, 1, 2), span = 1,
                      labels = c("third", "first", "second"))
graph.adjacency(chain)
graph.lengths(chain)
graph.edges(create.graph("cycle", n = 4))
graph.order(create.graph("complete_bipartite", sizes = c(2, 3)))
graph.order(create.graph("star", arms = c(2, 3, 1)))
graph.edges(create.graph("random", n = 6, mean.degree = 2, seed = 10))
circle <- create.graph("circle", n = 8, sampling = "uniform",
                       edge.length = "chord")
circle$metadata$coordinates
create.grid.graph — detailed help

Title

Create a Refined Graph with Approximately Uniform Edge Spacing

Name

create.grid.graph

Description

Create a Refined Graph with Approximately Uniform Edge Spacing

Usage

create.grid.graph(
  adj.list,
  length.list,
  grid.size,
  start.vertex = 1L,
  snap.tolerance = 0.1
)

Arguments

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

Examples

chain <- create.graph("chain", n = 3)
grid <- create.grid.graph(graph.adjacency(chain), graph.lengths(chain), grid.size = 5)
grid$metadata$grid_vertices
create.ian.graph — detailed help

Title

Construct an Iterated Adaptive Neighborhood Graph

Name

create.ian.graph

Description

Construct the initial Gabriel graph, adapt local scales and prune edges, returning graphs, affinities and diagnostics. By default, proposed bridge edges are protected so that pruning retains connectivity, and the audited retry-power numerical policy permits one checked retry after an eligible solver rejection. These are explicit variants of reference IAN.

Usage

create.ian.graph(
  X,
  distances = NULL,
  specimen.ids = NULL,
  participant.ids = NULL,
  graph = NULL,
  diagnostics = c("summary", "full"),
  backend = NULL,
  max.solves = 10000L,
  numerical.policy = "IAN evaluated-LP retry-power 0.1",
  preserve.connectivity = TRUE
)

Arguments

Details

Build the optional module once with build.ian.backend() and pass its returned path as backend. The supported build target is macOS arm64. The function itself does not compile code, download dependencies or launch an external solver. See system.file(“ian”, “README.md”, package = “dgraphs”) for the numerical contract, setup requirements and bounded qualification.

Input rows are specimens; graph vertices are unique feature profiles in first-occurrence order. Always check complete before using final_graph. Invalid R arguments or an unavailable backend raise an R error. Numerical refusal and interruption during engine execution return an incomplete result with the available diagnostics. Memory exhaustion or process termination is not a recoverable-result guarantee.

The default numerical policy is ⁠IAN evaluated-LP retry-power 0.1⁠. A rejected original return remains rejected. Its single eligible retry must itself pass strict solver success and the unchanged original-unit checks. numerical.policy=“IAN evaluated-LP 1.0” together with preserve.connectivity=FALSE selects the previous strict/reference behavior. This public default adoption changes neither policy’s implementation.

The returned top-level fields are complete, error, initial_graph, final_graph, last_valid_graph, mapping, scales, affinity, diagnostics and backend. Graphs are dgraph() objects with metric edge lengths in input distance units; affinity values are separate similarities. Mapping contains one-based representatives and member_to_profile, plus specimen, profile and participant IDs. Repeated participant IDs do not merge specimens. Error information contains kind, code and message. diagnostics$solver_history retains both accepted and rejected attempts. Backend information identifies the selected policies, source and settings. Checkpoint/resume is not exposed through this R interface.

Value

A list with complete, structured error, initial Gabriel graph, final_graph only on full completion, last_valid_graph (possibly partial), profile mapping, local scales and an affinity matrix distinct from metric edge lengths. Graph indices and mappings are one-based. Full traces retain original zero-based core indices and declare this in diagnostics. Summary diagnostics include per-solve status, acceptance, settings, residuals and iteration counts. Refusal and interruption return incomplete structured results; invalid R arguments error before native execution. Interrupts are checked at engine events; they do not interrupt an active solver call. In connectivity mode, diagnostics$connectivity contains protected.edges (one-based profile rows and IDs, first/last encounter iteration, count and first statistic), per-iteration history, and stop.reason. Iterations in this summary are one-based. Protected edges are encountered proposals, not necessarily edges that would pass the pruning criteria. Full traces also include every edge proposal and whether eligibility was tested. A complete pass with no deletion stops, including when statistical candidates remain protected. Partial results retain available protection diagnostics; final_graph remains NULL if later optimization or affinity construction fails.

See Also

build.ian.backend()

Examples

# Set this variable to the path returned by build.ian.backend().
backend <- Sys.getenv("DGRAPHS_IAN_BACKEND")
if (nzchar(backend) && file.exists(backend)) {
  X <- rbind(c(0, 0), c(1, 0), c(2, 0), c(0, 0))
  fit <- create.ian.graph(X, backend = backend,
      specimen.ids = c("alpha", "beta", "gamma", "delta"))
  stopifnot(fit$complete)
  graph.edges(fit$initial_graph)
  graph.edges(fit$final_graph)
  fit$mapping$member_to_profile # Four specimens, three unique profiles.
  fit$diagnostics$connectivity$protected.edges
}
create.iknn.graphs — detailed help

Title

Create intersection k-nearest neighbor graphs with dual pruning

Name

create.iknn.graphs

Description

For each k , builds an intersection-weighted k-NN graph and applies two pruning schemes: (1) geometric (path-to-edge ratio) and (2) intersection-size. Optionally performs PCA before graph construction.

Usage

create.iknn.graphs(
  X,
  k.values,
  max.path.edge.ratio.deviation.thld = 0.1,
  path.edge.ratio.percentile = 0.5,
  threshold.percentile = 0,
  compute.full = TRUE,
  with.isize.pruning = FALSE,
  with.edge.pruning.stats = FALSE,
  pca.dim = 100,
  variance.explained = 0.99,
  knn.metric = c("euclidean", "linf.simplex"),
  linf.tol = sqrt(.Machine$double.eps),
  verbose = TRUE,
  knn.cache.path = NULL,
  knn.cache.mode = c("none", "read", "write", "readwrite")
)

Arguments

Details

Geometric pruning uses the deviation threshold max.path.edge.ratio.deviation.thld and the filtering percentile path.edge.ratio.percentile. Intersection-size pruning currently uses a maximum alternative path length of 2.

Output behavior by flags:

  • compute.full = FALSE: both geom_pruned_graphs and isize_pruned_graphs are NULL.

  • compute.full = TRUE and with.isize.pruning = FALSE: geom_pruned_graphs is returned and isize_pruned_graphs is NULL.

Value

A list of class “iknn_graphs” with entries:

k_statistics

Matrix of per-k edge counts and reductions. (If the C++ side supplies column names, they’re preserved. Otherwise we add names consistent with what the C++ returns.)

geom_pruned_graphs

If compute.full=TRUE, list of geometrically pruned graphs (adjacency + weights); otherwise NULL.

isize_pruned_graphs

If compute.full=TRUE and with.isize.pruning=TRUE, list of intersection-size pruned graphs; otherwise NULL.

edge_pruning_stats

If with.edge.pruning.stats=TRUE, list (per k) of edge-level statistics; otherwise NULL.

Examples

# Generate sample data
X <- matrix(rnorm(100 * 5), 100, 5)

# Basic usage
res1 <- create.iknn.graphs(X, k.values = seq.int(3, 10), compute.full = FALSE)

# With custom pruning parameters
res2 <- create.iknn.graphs(X, k.values = seq.int(3, 10),
    max.path.edge.ratio.deviation.thld = 0.1,
    path.edge.ratio.percentile = 0.5, compute.full = TRUE, verbose = TRUE)

# View statistics for each k
print(res2$k_statistics)
create.iterated.iknn.graphs — detailed help

Title

Create iterated graph-geodesic iKNN graphs

Name

create.iterated.iknn.graphs

Description

Constructs G0 with create.iknn.graphs(), then constructs G1, G2, …, Gm by repeatedly applying create.geodesic.iknn.graph() to each graph in the k.values sequence. This implements the iterated nerve rule

{i,j} E(G_{t+1}) kNN_{G_t}(i) kNN_{G_t}(j) ,

with edge length

{t+1}(i,j) = d{G_t}(i,j).

Usage

create.iterated.iknn.graphs(
  X,
  k.values,
  n.iterations = 3L,
  small.component = c("error", "truncate"),
  max.path.edge.ratio.deviation.thld = 0,
  path.edge.ratio.percentile = 0.5,
  threshold.percentile = 0,
  pca.dim = 100,
  variance.explained = 0.99,
  verbose = TRUE,
  knn.cache.path = NULL,
  knn.cache.mode = c("none", "read", "write", "readwrite")
)

Arguments

Value

A list of class “iterated_iknn_graphs” with entries:

k.values

Integer vector of requested k values.

n_iterations

Number of geodesic rebuilds after G0.

initial_graphs

The “iknn_graphs” object returned by create.iknn.graphs() for G0.

graphs

Nested list named G0, G1, …; each entry is a named list of graph objects for k.values.

summary

Data frame with one row per iteration and k.

Examples

set.seed(1)
X <- matrix(rnorm(30), ncol = 2)
out <- create.iterated.iknn.graphs(X, k.values = seq.int(2, 3), n.iterations = 1,
    verbose = FALSE)
out$summary
create.maximal.packing — detailed help

Title

Create a Maximal Packing of Vertices in a Graph

Name

create.maximal.packing

Description

Creates a maximal packing of vertices based on a specified grid size. The algorithm places vertices in the graph using a separation distance that produces a vertex set packing of size approximately equal to the given grid size. A vertex packing is a set of vertices where each pair is separated by at least a specified distance.

Usage

create.maximal.packing(
  adj.list,
  length.list,
  grid.size,
  max.iterations = 20,
  precision = 0.1
)

Arguments

Details

The function computes a maximal packing by iteratively selecting vertices that are approximately grid.size apart from each other. The process starts from one of the graph’s diameter endpoints (determined automatically) and continues until no more vertices can be added to the packing without violating the distance constraint.

The returned \code{graph_diameter} represents the longest shortest path
in the graph, which provides insight into the graph's overall structure
and extent.

The \code{max_packing_radius} value indicates the minimum distance that
separates any two vertices in the packing. This value is determined
through binary search to achieve a packing of approximately the
requested size.

The function validates input parameters and ensures that the graph
structure is properly specified before computing the packing. The graph
must be undirected (symmetric adjacency) and connected.

Value

A maximal_packing result containing its graph (a dgraph), grid_vertices (packing indices), graph_diameter, and max_packing_radius (the guaranteed separation of packing vertices).

See Also

validate.maximal.packing, verify.maximal.packing

Examples

adj.list <- list(c(2), c(1, 3), c(2, 4), c(3, 5), c(4))
length.list <- list(c(1), c(1, 1), c(1, 1), c(1, 1), c(1))

result <- create.maximal.packing(adj.list, length.list, grid.size = 2)
result$grid_vertices
result$max_packing_radius
create.mknn.graph — detailed help

Title

Compute a Mutual k-Nearest Neighbor Graph with Weights

Name

create.mknn.graph

Description

Creates an undirected graph where two points are connected by an edge if and only if they are present in each other’s k-nearest neighbor (kNN) lists. The weight of each edge represents the distance between the connected vertices.

Usage

create.mknn.graph(
  X,
  k,
  prune.method = c("none", "local.geodesic", "global.geodesic.ratio"),
  max.path.edge.ratio.deviation.thld = 0.1,
  path.edge.ratio.percentile = 0.5,
  prune.tau = 1.05,
  prune.local.k = NULL,
  with.pruned.edge.stats = FALSE,
  connect.components = FALSE,
  connect.method = c("component.mst", "component.mst.ann", "global.mst"),
  bridge.k = NULL,
  bridge.k.max = NULL,
  bridge.growth = 2
)

Arguments

Details

The mutual k-nearest neighbor graph is a symmetric graph where an edge between vertices i and j exists if and only if:

  • j is among the k nearest neighbors of i, AND

  • i is among the k nearest neighbors of j

This mutual relationship ensures that the resulting graph is undirected and typically sparser than a standard k-nearest neighbor graph.

Use graph accessors for the final graph and graph.stages() to list stored raw, pruned and repaired stages. Construction details are in metadata.

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

See Also

create.mknn.graphs for creating multiple graphs with different k values, summary.mknn_graphs for summarizing graph properties

Examples

set.seed(123)
X <- matrix(rnorm(60), ncol = 2)
graph <- create.mknn.graph(X, k = 4)
graph.order(graph)
nrow(graph.edges(graph))
graph.adjacency(graph)[[1]]
create.mknn.graphs — detailed help

Title

Create Multiple Mutual kNN Graphs with Geometric Pruning

Name

create.mknn.graphs

Description

Constructs a series of mutual k-nearest neighbor (MkNN) graphs across a range of k values, with optional geometric pruning to remove redundant edges based on alternative path analysis.

Usage

create.mknn.graphs(
  X,
  k.values,
  max.path.edge.ratio.thld = 1.2,
  path.edge.ratio.percentile = 0.5,
  compute.full = FALSE,
  pca.dim = 100,
  variance.explained = 0.99,
  verbose = FALSE
)

Arguments

Details

This function performs the following steps for each k value:

  1. Mutual kNN Graph Construction: Creates a graph where edges exist only between mutually nearest neighbors.

  2. Geometric Pruning (optional): Removes edges where alternative paths exist with acceptable length ratios. An edge (i,j) is pruned if there exists a path i->k->j such that (d(i,k) + d(k,j)) / d(i,j) <= threshold.

  3. Dimensionality Reduction (optional): If the data has more than pca.dim dimensions, PCA is applied before graph construction to improve computational efficiency and reduce noise.

The geometric pruning step helps create sparser graphs by removing edges that can be well-approximated by two-hop paths, which can improve graph quality for clustering and visualization tasks.

Value

An object of class "mknn_graphs" containing:

k_statistics

A data frame with columns: k (k value), n_edges (edges before pruning), n_edges_pruned (edges after pruning), n_removed (number of removed edges), reduction_ratio (proportion of edges removed).

pruned_graphs

If compute.full=TRUE, a named list of pruned graphs for each k value. NULL otherwise.

edge_pruning_stats

A list of pruning statistics for each k value, containing edge lengths and path ratios.

The returned object also has the following attributes:

  • k.values: The requested neighborhood sizes

  • max.path.edge.ratio.thld: The pruning threshold used

  • path.edge.ratio.percentile: The percentile threshold used

  • pca: If PCA was performed, contains dimensionality reduction details

See Also

create.mknn.graph for creating a single MkNN graph, summary.mknn_graphs for summarizing the results

Examples

set.seed(123)
X <- matrix(rnorm(80), ncol = 2)
result <- create.mknn.graphs(X, k.values = seq.int(3, 4), compute.full = TRUE, verbose = FALSE)
result$k_statistics

X.high <- matrix(rnorm(120), nrow = 20, ncol = 6)
result.pca <- create.mknn.graphs(X.high, k.values = seq.int(2, 3), pca.dim = 3, verbose = FALSE)
attr(result.pca, "pca")$n_components
create.path.graph — detailed help

Title

Construct Path Graphs Across Hop Limits

Name

create.path.graph

Description

Find minimum-length routes using at most each requested number of edges. Equal-length routes prefer fewer hops. One route is stored per unordered pair and can be retrieved in either direction with get.shortest.path().

Usage

create.path.graph(graph, h.values, stage = "final")

Arguments

Details

Hop-constrained search retains a separate distance for each hop count, then selects the best route for each pair. With nonnegative lengths, limits above n - 1 need no additional search. For each source, auxiliary storage is proportional to n * min(h, n - 1); storing routes for all reachable pairs can require cubic space. Use small hop limits when possible.

Value

A named path.graph.series collection, even for one limit. Names are h_2, h_4, etc. Each member is a path.graph with a graph of reachable pairs, stored shortest.paths, and an h attribute recording the requested limit. Its graph stores route lengths and a hops edge attribute. Routes use the input graph’s vertex indices. Empty graphs and isolated vertices are preserved.

Examples

graph <- create.graph("chain", n = 5)
paths <- create.path.graph(graph, h.values = c(2, 4))
get.shortest.path(paths[["h_4"]], from = 1, to = 5)
get.shortest.path(paths[["h_4"]], from = 5, to = 1)
compare.paths(paths, from = 1, to = 5)
create.plm.graph — detailed help

Title

Create a Path Length Matrix Graph Structure

Name

create.plm.graph

Description

Create a Path Length Matrix Graph Structure

Usage

create.plm.graph(adj.list, length.list, h)

Arguments

Value

An object of class path.graph.plm.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
create.plm.graph(graph, lengths, h = 3)
create.rknn.graph — detailed help

Title

Compute a Radius-kNN Graph

Name

create.rknn.graph

Description

Creates an undirected Euclidean radius graph from a numeric data matrix. Use type = “fixed” for a fixed-radius graph, where vertices i and j are adjacent exactly when their Euclidean distance is at most radius. Use type = “adaptive.radius” for an adaptive-radius graph based on observation-specific local scale distances.

Usage

create.rknn.graph(
  X,
  type = c("fixed", "adaptive.radius"),
  radius = NULL,
  k.scale = NULL,
  radius.factor = 1,
  radius.rule = c("max", "min", "geomean"),
  radius.search = c("ann", "all.pairs"),
  return.timing = FALSE,
  graph.detail = c("full", "minimal"),
  prune.method = c("none", "local.geodesic", "global.geodesic.ratio"),
  max.path.edge.ratio.deviation.thld = 0.1,
  path.edge.ratio.percentile = 0.5,
  prune.tau = 1.05,
  prune.local.k = NULL,
  with.pruned.edge.stats = FALSE,
  connect.components = FALSE,
  connect.method = c("component.mst", "component.mst.ann", "global.mst"),
  bridge.k = NULL,
  bridge.k.max = NULL,
  bridge.growth = 2
)

Arguments

Value

A dgraph, with constructor class radius_graph for fixed radii or adaptive_radius_graph for adaptive radii. Use graph accessors for topology, lengths and retained stages; construction diagnostics are in metadata.

Examples

X <- matrix(c(0, 1, 3), ncol = 1)
as.matrix(graph.edges(create.rknn.graph(X, type = "fixed", radius = 1.1))[, c("from", "to")])
as.matrix(graph.edges(create.rknn.graph(X, type = "adaptive.radius", k.scale = 1))[, c("from",
"to")])
create.rknn.graphs — detailed help

Title

Compute Adaptive Radius-kNN Graphs Across k Values

Name

create.rknn.graphs

Description

Creates a sequence of adaptive-radius graphs by varying the k.scale parameter passed to create.rknn.graph(type = “adaptive.radius”). By default, ANN-backed construction uses the batched C++ backend while the direct all-pairs reference path uses the scalar R loop. Set backend = “r” to force the scalar loop for ANN parity checks.

Usage

create.rknn.graphs(X, k.values, ..., backend = c("auto", "cpp", "r"))

Arguments

Value

A list of class “rknn_graphs” with components:

graphs

A named list of adaptive-radius graph objects, one per k.

k_statistics

A data frame with one row per k containing edge, component, and MST-repair counts.

timing

Present only when forwarded options request graph timing; contains backend-specific construction timing rows.

Attributes include k.values and n_vertices.

See Also

create.rknn.graph()

Examples

X <- matrix(c(0, 1, 3, 4), ncol = 1)
result <- create.rknn.graphs(X, k.values = seq.int(1, 2), radius.search = "all.pairs",
    graph.detail = "minimal",
    prune.method = "none")
names(result$graphs)
result$k_statistics
create.single.iknn.graph — detailed help

Title

Create a Single Intersection-weighted k-Nearest Neighbors Graph

Name

create.single.iknn.graph

Description

Creates and prunes an intersection-weighted k-nearest neighbors (IWD-kNN) graph from input data. The graph is constructed based on feature space distances and intersection sizes between neighbor sets.

Usage

create.single.iknn.graph(
  X,
  k,
  max.path.edge.ratio.deviation.thld = 0.1,
  prune.method = c("global.geodesic", "none", "local.geodesic", "global.geodesic.ratio"),
  prune.tau = NULL,
  prune.local.k = NULL,
  path.edge.ratio.percentile = 0.5,
  threshold.percentile = 0,
  compute.full = FALSE,
  with.isize.pruning = FALSE,
  with.edge.pruning.stats = FALSE,
  pca.dim = 100,
  variance.explained = 0.99,
  knn.metric = c("euclidean", "linf.simplex"),
  linf.tol = sqrt(.Machine$double.eps),
  connect.components = FALSE,
  connect.method = c("component.mst", "component.mst.ann", "global.mst"),
  bridge.k = NULL,
  bridge.k.max = NULL,
  bridge.growth = 2,
  with.lifecycle.branches = FALSE,
  verbose = TRUE,
  knn.cache.path = NULL,
  knn.cache.mode = c("none", "read", "write", "readwrite")
)

Arguments

Details

The default accessors inspect the final graph. Use stage = “raw” or stage = “pruned” to inspect earlier stages. graph.stages() reports which repaired branches are retained; a missing stage is an error.

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

Examples

# Create sample data
set.seed(123)
X <- matrix(rnorm(100), ncol = 2)
result <- create.single.iknn.graph(X, k = 3)
summary(result)
create.sknn.graph — detailed help

Title

Compute a Symmetric k-Nearest Neighbor Graph

Name

create.sknn.graph

Description

Creates an undirected symmetric k-nearest neighbor (sKNN) graph from a numeric data matrix. An edge between vertices i and j is present when either j is among the k nearest neighbors of i, or i is among the k nearest neighbors of j.

Usage

create.sknn.graph(
  X,
  k,
  prune.edges = FALSE,
  prune.method = c("none", "local.geodesic", "global.geodesic.ratio"),
  max.path.edge.ratio.deviation.thld = 0.1,
  path.edge.ratio.percentile = 0.5,
  prune.tau = 1.05,
  prune.local.k = NULL,
  with.pruned.edge.stats = FALSE,
  connect.components = FALSE,
  connect.method = c("component.mst", "component.mst.ann", "global.mst"),
  edge.weight = c("distance"),
  neighbor.method = c("exact", "ann"),
  ann.eps = 0,
  knn.index = NULL,
  graph.detail = c("full", "minimal"),
  bridge.k = NULL,
  bridge.k.max = NULL,
  bridge.growth = 2,
  input.type = c("observations", "distances")
)

Arguments

Details

With input.type = “distances”, supplied distances determine exact neighbor rankings, every edge length, and component/global MST repair. Distance input must be finite, nonnegative, square and symmetric, with a zero diagonal. Symmetry and diagonal tolerance is 1e-12 * max(1, max(X)); accepted asymmetry is averaged and the diagonal set to zero. Row and column names, if present, must be identical and unique. Off-diagonal zeros are allowed. Triangle inequality is not tested, so symmetric dissimilarities are accepted. Ties are resolved by increasing vertex index, excluding self explicitly. ANN search/repair and pruning are unsupported for distance input and error. The series constructor validates distances and ranks neighbors once, through its largest requested k. Full lifecycle stages use these same distances.

With no nearest-neighbor ties, the sKNN edge rule is equivalent to

d_{ij} (_i, _j),

where _i is the distance from point i to its k-th non-self nearest neighbor.

If connect.components = TRUE, the graph is augmented with MST edges. The default connect.method = “component.mst” first collapses each connected component of the sKNN graph to one component vertex, weights each component pair by the shortest data-space edge between them, and adds the minimum spanning tree of this component graph. This adds exactly m - 1 bridge edges when the original sKNN graph has m connected components. connect.method = “component.mst.ann” uses ANN nearest-neighbor bridge candidates first and automatically falls back to exact component MST when the sparse candidate graph does not connect all components. The alternative connect.method = “global.mst” unions the sKNN graph with the full Euclidean MST on the data points.

neighbor.method = “exact” computes all pairwise distances and is the deterministic reference implementation. neighbor.method = “ann” uses the bundled ANN kd-tree for the Euclidean kNN search step; exact parity can differ only in nearest-neighbor tie cases. Edge weights are always returned as ordinary Euclidean distances. Exact component.mst repair uses exact pairwise bridge distances; component.mst.ann uses ANN bridge candidates before guaranteed exact fallback.

If prune.method = “local.geodesic” or prune.edges = TRUE, an experimental local-geodesic pruning stage is applied after the sKNN support is built and before optional MST connectivity repair. Candidate edges are processed longest-first. For an edge ⁠(i, j)⁠, the edge is removed only when the currently retained graph contains an alternative path from i to j, restricted to the union of their local neighborhoods, whose length is at most prune.tau times the direct edge length. prune.method = “global.geodesic.ratio” instead uses the whole graph as the alternative-path search domain and removes long edges whose shortest alternative path is within the configured geodesic-ratio threshold.

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

Examples

X <- rbind(c(0, 0), c(1, 0), c(10, 0), c(11, 0))
g <- create.sknn.graph(X, k = 1, connect.components = TRUE)
g$metadata$n_components_before
g$metadata$n_components_after
g$metadata$mst_edge_matrix
create.sknn.graphs — detailed help

Title

Compute a Series of Symmetric k-Nearest Neighbor Graphs

Name

create.sknn.graphs

Description

Constructs symmetric k-nearest neighbor graphs for several values of k while performing one bundled ANN search for observations, or one exact ranking of supplied distances, at the largest requested value. The ordered non-self neighbor matrix is sliced for each graph, so lower-k graphs use exactly the same neighbor ranking as the largest graph.

Usage

create.sknn.graphs(
  X,
  k.values,
  ...,
  input.type = c("observations", "distances")
)

Arguments

Value

A list of class “sknn_graphs” with components graphs, a named list of “sknn_graph” objects, and k_statistics, a data frame of edge and component counts. Attributes record the requested values and number of vertices.

See Also

create.sknn.graph()

Examples

set.seed(1)
X <- matrix(rnorm(60), ncol = 3)
graphs <- create.sknn.graphs(
  X,
  k.values = c(2, 4),
  graph.detail = "minimal"
)
graphs$k_statistics
create.subgraph — detailed help

Title

Extract an Induced Subgraph

Name

create.subgraph

Description

Extract an Induced Subgraph

Usage

create.subgraph(graph, vertices, stage = "final")

Arguments

Value

A dgraph with compact indices and aligned lengths and attributes. metadata$original.vertices maps its vertices back to the original graph.

Examples

graph <- create.graph("chain", 4)
sub <- create.subgraph(graph, vertices = c(4, 3))
graph.edges(sub)
sub$metadata$original.vertices
create.threshold.distance.graph — detailed help

Title

Create a Threshold Distance Graph

Name

create.threshold.distance.graph

Description

Create a Threshold Distance Graph

Usage

create.threshold.distance.graph(dist.matrix, threshold, include.names = TRUE)

Arguments

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

Examples

distances <- as.matrix(dist(matrix(c(0, 1, 3), ncol = 1)))
create.threshold.distance.graph(distances, threshold = 1.5)
detect.graph.endpoints — detailed help

Title

Detect Graph Endpoints from a 3D Embedding

Name

detect.graph.endpoints

Description

Detects terminal arm tips in a graph by:

  1. computing graph endpoint scores from the 3D embedding,

  2. optionally smoothing those scores on the graph using fit.rdgraph.regression() and refit.rdgraph.regression(),

  3. finding graph-local maxima with detect.local.extrema(),

  4. retaining only maxima that persist across neighborhood scales.

The function works with terminal regions in an embedding; returned endpoints need not be degree-1 vertices.

Usage

detect.graph.endpoints(
  adj.list,
  length.list,
  layout.3d,
  neighborhood = c("geodesic_k", "geodesic_radius"),
  k = c(10L, 20L, 30L),
  radius = NULL,
  q = 0.1,
  neighbor.weighting = c("uniform", "inverse_distance", "gaussian"),
  gaussian.sigma = NULL,
  min.neighborhood.size = 3L,
  scale.aggregate = c("mean", "median", "min", "max"),
  score.metric = c("score", "m", "s.q", "s.min"),
  smooth = FALSE,
  fitted.model = NULL,
  smooth.fit.args = NULL,
  smooth.refit.args = NULL,
  detect.max.radius = 2,
  detect.min.neighborhood.size = 2L,
  scale.stability.radius = NULL,
  min.scale.stability = 0.5,
  min.score.quantile = 0.8,
  max.endpoints = NULL,
  verbose = FALSE
)

Arguments

Value

A list with endpoint vertices, score diagnostics, optional smoothed scores, scale stability summaries, and the local-extrema fit used for endpoint calling.

Examples

chain <- create.graph("chain", n = 8)
layout <- cbind(seq_len(8), 0, 0)
endpoints <- detect.graph.endpoints(graph.adjacency(chain), graph.lengths(chain),
    layout, k = c(2,
    3), min.neighborhood.size = 2, detect.max.radius = 2, detect.min.neighborhood.size = 2,
    min.score.quantile = 0.5)
endpoints$endpoints
detect.local.extrema — detailed help

Title

Detect Local Extrema in a Graph

Name

detect.local.extrema

Description

Detect Local Extrema in a Graph

Usage

detect.local.extrema(
  adj.list,
  length.list,
  y,
  max.radius,
  min.neighborhood.size,
  detect.maxima = TRUE,
  custom.prefix = NULL
)

Arguments

Details

Summaries use the recorded detection setting for empty results. Empty objects saved by older versions lack this setting; their summaries report NA for the extrema type because it cannot be recovered from empty vectors.

Value

A local_extrema object. Its scalar logical detect.maxima component records whether maxima or minima were requested, even when no extrema are found. The per-extremum is_maxima and type vectors are empty in that case.

Examples

chain <- create.graph("chain", n = 5)
extrema <- detect.local.extrema(graph.adjacency(chain), graph.lengths(chain), y = c(1, 3, 1, 2,
    0), max.radius = 1, min.neighborhood.size = 2)
extrema$vertices
dgraph — detailed help

Title

Construct and Inspect an Undirected Metric Graph

Name

dgraph

Description

A dgraph stores an undirected simple graph, including isolated vertices. Adjacency, lengths and scalar edge attributes are validated together and sorted together. Zero lengths are edges; absent lengths remain NULL.

Usage

dgraph(adj.list, length.list = NULL, edge.attributes = list())

graph.adjacency(graph, stage = "final")

graph.lengths(graph, stage = "final")

graph.order(graph)

graph.stages(graph)

graph.edge.attribute(graph, name, stage = "final")

graph.edges(graph, stage = "final")

Arguments

Value

dgraph() returns a graph. The accessors return adjacency lists, length lists (or NULL), an ordered edge data frame, the vertex count, stage names, or the requested attribute list, respectively. Edge tables contain integer from < to, optional numeric length, and attributes.

Examples

graph <- dgraph(list(c(3L, 2L), 1L, 1L, integer()),
                list(c(0, 2), 2, 0, numeric()))
graph.order(graph)
graph.edges(graph)
graph.stages(graph)
graph.adjacency(graph)
graph.lengths(graph)
dgraphs — detailed help

Title

dgraphs: Data-Derived Graph Construction Utilities

Name

dgraphs-package

Description

Construct and analyze graphs derived from numerical observations.

Start here

These links open installed HTML guides. From the console, use vignette(“function-guide”, package = “dgraphs”) or vignette(“synthetic-geometry”, package = “dgraphs”).

Author(s)

Maintainer: Pawel Gajer pgajer@gmail.com

Authors:

Other contributors:

  • Sunil Arya (ANN library) [contributor]

  • David M. Mount (ANN library) [contributor]

  • University of Maryland (ANN library) [copyright holder]

  • Yixuan Qiu (Spectra library) [contributor, copyright holder]

  • Anna Araslanova (Spectra LOBPCG solver) [contributor, copyright holder]

  • Gael Guennebaud (Spectra linear algebra routines) [contributor, copyright holder]

  • Jitse Niesen (Spectra linear algebra routines) [contributor, copyright holder]

  • Netherlands eScience Center (Spectra eigensolver routines) [contributor, copyright holder]

  • Danil Kirsanov (Polyhedral geodesic library) [contributor, copyright holder]

See Also

create.graph(), create.sknn.graph(), create.rknn.graph(), graph.geodesic.distances(), create.path.graph(), plot.dgraph(), sample.synthetic.geometry()

Examples

graph <- create.graph("chain", n = 5)
print(graph)
graph.geodesic.distances(graph, vertices = c(1, 5))
# The endpoint distance is four unit-length edges.
.dgraphs.validate.adj.list — detailed help

Title

Validate an adjacency list

Name

.dgraphs.validate.adj.list

Description

Validate an adjacency list

Usage

.dgraphs.validate.adj.list(adj.list, allow.empty = FALSE)

Arguments

Value

The normalized adjacency list with integer neighbor vectors.

edge.diff — detailed help

Title

Compute Edge Difference Between Two Graphs

Name

edge.diff

Description

Compute Edge Difference Between Two Graphs

Usage

edge.diff(adj.list1, adj.list2)

Arguments

Value

A list containing neighbors present in graph1 but not graph2 for each vertex.

Examples

graph1 <- list(c(2L, 3L), 1L, 1L)
graph2 <- list(2L, 1L, integer(0))
edge.diff(graph1, graph2)
edge.lengths.synthetic.geometry — detailed help

Title

Exact latent-segment lengths under a synthetic geometry

Name

edge.lengths.synthetic.geometry

Description

For quadforms this integrates the induced metric along each straight latent segment. Flat quadforms reduce exactly to Euclidean distance.

Usage

edge.lengths.synthetic.geometry(geometry, from, to, tolerance = 1e-10)

Arguments

Value

A numeric vector of segment lengths.

Examples

geometry <- synthetic.quadform(1L, 1L)
edge.lengths.synthetic.geometry(geometry, matrix(0), matrix(2))
embed.quadform.surface — detailed help

Title

Lift coordinates onto a quadratic surface using Geometry Lab arithmetic

Name

embed.quadform.surface

Description

Lift coordinates onto a quadratic surface using Geometry Lab arithmetic

Usage

embed.quadform.surface(latent, coefficients)

Arguments

Value

A three-column matrix. Version-1 arithmetic preserves existing Geometry Lab cloud identities and reference meshes.

Examples

embed.quadform.surface(matrix(c(0, 1, 0, 1), ncol = 2), c(1, 0, -1))
embed.synthetic.geometry — detailed help

Title

Embed latent coordinates through a synthetic geometry

Name

embed.synthetic.geometry

Description

This deterministic operator performs no random draws. A realized frame.matrix is required for random-frame geometries.

Usage

embed.synthetic.geometry(geometry, latent, frame.matrix = NULL)

Arguments

Value

A numeric matrix of observed coordinates.

Examples

geometry <- synthetic.circle()
embed.synthetic.geometry(geometry, matrix(c(0, pi / 2), ncol = 1))
explore.graphs — detailed help

Title

Open the Graph Reconstruction Explorer

Name

explore.graphs

Description

Explore saved data-geodesic graph reconstruction benchmarks using manual graph selection, metric-based selection, saved layouts and parameter scans. This is the maintained replacement for the dggraphui application.

Usage

explore.graphs(
  project = NULL,
  launch = TRUE,
  host = "127.0.0.1",
  port = getOption("shiny.port"),
  launch.browser = interactive(),
  ...
)

Arguments

Details

The optional packages shiny, bslib, plotly and digest are required only for the explorer. The optional grip package is needed only when explicitly generating a missing weighted layout. Opening a project reads saved results; it does not reconstruct graphs, fit layouts or overwrite benchmark assets. Newly generated layouts are stored in a separate dgraphs user cache.

Project registration stores locations in the user’s dgraphs data directory, outside the installed package. Set options(dgraphs.projects_dir = …) to choose another catalog directory. Set options(dgraphs.graph_explorer_cache_dir = …) to choose the layout cache.

The default display preserves original coordinates and equal x/y/z units. Optional centering with a single scale factor preserves proportions. Per-axis normalization is labeled as distorting proportions. The displayed edge count discloses thinning above 4000 edges; saved metrics always use the complete graph and are never recomputed by display controls.

Choose Open circle demo in the app, or use the installed project below. Its two chord-weighted graphs use 12 equally spaced unit-circle points. Increasing k from 2 to 4 introduces shortcuts relative to exact shorter circle arcs. Layouts and metrics are already saved; no fitting is needed.

Value

When launch = FALSE, a shiny.appobj; otherwise the result of shiny::runApp(), invisibly.

See Also

read.graph.benchmark(), register.graph.project()

Examples

if (interactive() && all(vapply(c("shiny", "bslib", "plotly", "digest"),
                               requireNamespace, logical(1), quietly = TRUE))) {
    demo <- system.file("extdata", "graph-explorer-demo", package = "dgraphs")
    explore.graphs(demo)
}
extract.trajectory.edge.lengths — detailed help

Title

Extract Edge Lengths Along a Graph Path

Name

extract.trajectory.edge.lengths

Description

Extract Edge Lengths Along a Graph Path

Usage

extract.trajectory.edge.lengths(
  traj,
  adj.list,
  length.list,
  add.quantiles = FALSE
)

Arguments

Value

Data frame with consecutive vertex pairs and their edge lengths.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
extract.trajectory.edge.lengths(c(1, 2, 3), graph, lengths)
fermat.distances — detailed help

Title

Compute Complete or Graph-Restricted Sample Fermat Distances

Name

fermat.distances

Description

Minimize sums of powered edge lengths. Coordinate input defaults to the complete Euclidean graph, implementing the sample Fermat distance on the observed points. A symmetric kNN restriction or a supplied graph is an explicit alternative, with no automatic guarantee of the same distances.

Usage

fermat.distances(
  graph = NULL,
  p = 2,
  rooted = FALSE,
  vertices = NULL,
  stage = "final",
  points = NULL,
  graph.type = NULL,
  k = NULL,
  backend = "explicit",
  sources = NULL,
  targets = NULL,
  max.workspace.bytes = 512 * 1024^2,
  return.graph = FALSE
)

Arguments

Details

For base lengths l_e, the unrooted result is {e} l_e^p. At p = 1, complete-graph coordinate distances are Euclidean; restricted distances are ordinary graph distances. Restricting edges cannot decrease the result when retained weights agree. Taking k = n - 1 recovers the complete graph.

Groisman, Jonckheere and Sapienza define the unrooted complete-graph estimator and prove consistency after sample-size normalization under their sampling assumptions. Their Proposition 2.12 establishes a high-probability equality for a sufficiently large nearest-neighbor restriction under its stated assumptions. It does not certify arbitrary fixed k, pruned graphs, or arbitrary supplied lengths. This function applies neither sample-size normalization nor an estimated limit constant.

Both coordinate constructions evaluate all Euclidean pairs. Explicit complete graphs store quadratic adjacency. The implicit backend uses dense Dijkstra searches with linear scratch and no graph restriction: with h sources, n observations and d coordinates its worst-case time is O(hn^2d). A global numeric-range check takes O(n^2d) time. Pivot-to-all output uses O(hn) storage; full all-pairs output is still quadratic. Select pivots outside this function; no automatic pivot sampling or distance approximation is performed. Distances are computed in floating-point arithmetic. Overflow, positive powered lengths underflowing to zero, and a conservative upper bound on simple-path cost exceeding the numeric range cause errors; rescale base lengths before retrying. Multiplying lengths by a > 0 multiplies unrooted distances by a^p (rooted distances by a).

With return.graph = TRUE, one deterministic shortest-path tree is selected per source (ties need not include every minimizing path). Only paths to the requested targets contribute edges. The returned graph retains all input vertices, including unused isolated vertices. Its edge lengths are powered base lengths even when the returned distances are rooted. Thus graph geodesics reproduce the unrooted requested distances. With all sources and targets it preserves every pair; a subset guarantees only the requested pairs. The union need not be sparse. The implicit workspace estimate includes a conservative allowance for the predecessor-edge union when requested.

Value

Numeric square distance matrix, or a source-by-target matrix when sources is supplied, in requested order. Unreachable pairs are Inf. Zero-length edges are retained; duplicate points have zero distance. Point row names or graph adjacency names label the matrix. With return.graph = TRUE, return a list containing distances (this matrix), graph (a dgraph with powered base edge lengths), and metadata. Metadata records sources, targets, coverage (all_pairs or requested_pairs), p, rooted, edge.weight.type, and the backend used. Graph distances are unrooted even when the returned matrix is rooted.

References

Groisman, P., Jonckheere, M. and Sapienza, F. (2022). Nonhomogeneous Euclidean first-passage percolation and distance learning. Bernoulli, 28(1), 255–276. doi:10.3150/21-BEJ1341. See Definitions 2.1 and 2.11 and Proposition 2.12 in https://arxiv.org/html/1810.09398v2.

See Also

graph.geodesic.distances(), create.sknn.graph()

Examples

X <- matrix(c(0, 1, 2), ncol = 1)
fermat.distances(points = X, p = 2) # 0 -> 1 -> 2 costs 2, not 4
fermat.distances(points = X, p = 2, rooted = TRUE)
fermat.distances(points = X, graph.type = "sknn", k = 1)
g <- dgraph(list(2L, c(1L, 3L), 2L), list(1, c(1, 1), 1))
fermat.distances(g, vertices = c(1, 3))
fermat.knn — detailed help

Title

Find Exact Sample Fermat Nearest Neighbors

Name

fermat.knn

Description

Find nearest neighbors in the complete-graph sample Fermat distance using Euclidean neighbor pruning and truncated Dijkstra searches.

Usage

fermat.knn(points, k, p = 2, rooted = FALSE, algorithm = "kd_tree")

create.fermat.sknn.graph(
  points,
  k,
  p = 2,
  rooted = FALSE,
  algorithm = "kd_tree"
)

Arguments

Details

The unrooted distance is the minimum sum of Euclidean edge lengths raised to p, allowing paths through all observations. Rooting preserves neighbor rankings. Lemma 5.6 of McKenzie and Damelin justifies pruning to directed Euclidean neighbor lists for nearest-neighbor queries. This does not establish equality of all pairwise distances on the sparse graph. The paper counts the source among its neighbors; here k excludes it.

Equal-distance neighbors at the cutoff may be selected arbitrarily; their identities need not agree across search algorithms or permutations. Duplicate observations are retained as distinct vertices with zero distance. Exactness refers to the complete-graph target, subject to floating-point arithmetic. Extremely disparate coordinate scales should be rescaled. Nonfinite computed lengths and powered costs, and positive costs that underflow to zero, cause errors.

Candidate lists and output use O(nk) storage. After Euclidean search, binary-heap path searches take O(nk^2*log(k+1)) time with O(n+k^2) scratch. Euclidean search may be quadratic in n in high dimensions. Unlike the implicit distance backend, this function does not scan every complete-graph edge for numeric-range validation.

Value

fermat.knn() returns a list with n-by-k matrices index (1-based neighbor indices) and distance (in nondecreasing order), excluding self. create.fermat.sknn.graph() returns a dgraph formed by the union of these directed selections. Its lengths are Fermat distances, not powered direct Euclidean edges. Vertex degrees can exceed k; components are not repaired. Use graph.geodesic.distances() to sum stored lengths, rather than applying fermat.distances() with p > 1 and powering them again.

References

McKenzie, D. and Damelin, S. (2019). Power Weighted Shortest Paths for Clustering Euclidean Data. Section 5, Lemma 5.6 and Algorithm 2. https://arxiv.org/abs/1905.13345.

See Also

fermat.distances(), create.sknn.graph()

Examples

X <- cbind(c(0, 1, 2, 4), 0)
fermat.knn(X, k = 2, p = 2)
graph <- create.fermat.sknn.graph(X, k = 2)
graph.edges(graph)
geodesic.core.endpoints — detailed help

Title

Select Graph Endpoints by Core-Eccentricity Geometry

Name

geodesic.core.endpoints

Description

Select Graph Endpoints by Core-Eccentricity Geometry

Usage

geodesic.core.endpoints(
  adj.list,
  length.list,
  core.quantile = 0.1,
  endpoint.quantile = 0.9,
  use.approx.eccentricity = TRUE,
  n.landmarks = 64L,
  max.endpoints = NULL,
  seed = 1L,
  verbose = FALSE
)

Arguments

Value

A geodesic_core_endpoints list of endpoints and diagnostics.

Examples

graph <- create.graph("chain", n = 8)
endpoints <- geodesic.core.endpoints(graph.adjacency(graph), graph.lengths(graph),
    use.approx.eccentricity = FALSE)
endpoints$endpoints
geodesic.disk — detailed help

Title

Geodesic Disk in a Weighted Graph

Name

geodesic.disk

Description

Geodesic Disk in a Weighted Graph

Usage

geodesic.disk(adj.list, length.list, center.vertex, radius = NULL, n = NULL)

Arguments

Value

List with vertices, effective radius, and aligned dists.

Examples

graph <- list(2L, c(1L, 3L), 2L)
weights <- list(1, c(1, 2), 2)
geodesic.disk(graph, weights, center.vertex = 2, radius = 2)
geodesic.knn — detailed help

Title

Find Geodesic Neighbors Within a Point Cloud

Name

geodesic.knn

Description

Find Geodesic Neighbors Within a Point Cloud

Usage

geodesic.knn(
  X,
  k,
  k.graph = 5,
  graph = NULL,
  small.component = c("error", "truncate")
)

Arguments

Value

A list with nn.index and nn.dist matrices with k columns and effective.k, the number returned per row. Under explicit truncation, absent indices and distances are NA; unreachable vertices are never reported as neighbors.

See Also

geodesic.knnx(), graph.geodesic.distances()

Examples

X <- cbind(0:3, 0)
geodesic.knn(X, k = 1, k.graph = 1) # one other vertex per row
geodesic.knnx — detailed help

Title

Find Geodesic Neighbors from Grid Queries to Observations

Name

geodesic.knnx

Description

Find Geodesic Neighbors from Grid Queries to Observations

Usage

geodesic.knnx(
  X,
  X.grid,
  k,
  k.graph = 5,
  small.component = c("error", "truncate")
)

Arguments

Value

A list with combined coordinates V (grid rows first), edge pairs E in V row indices, nn.index (indices into X), nn.dist and effective.k (the number returned per grid query).

See Also

geodesic.knn()

Examples

X.grid <- as.matrix(expand.grid(x = 0:2, y = 0:2))
X <- rbind(c(0, 0), c(1.2, 0.8), c(1.8, 1.7))
geodesic.knnx(X, X.grid, k = 2)
get.shortest.path — detailed help

Title

Get Shortest Path Between Two Vertices

Name

get.shortest.path

Description

Get Shortest Path Between Two Vertices

Usage

get.shortest.path(path.result, from, to)

Arguments

Value

A list with path (vertex indices in requested direction), length and hops, or NULL when no stored route exists within this result’s hop limit. A vertex queried against itself has path from, length zero and zero hops. Routes can be retrieved in either direction.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
pg <- create.path.graph(dgraph(graph, lengths), h.values = 2)[[1L]]
get.shortest.path(pg, from = 1, to = 3)
graph.connected.components — detailed help

Title

Assign Vertices to Connected Components

Name

graph.connected.components

Description

Assign Vertices to Connected Components

Usage

graph.connected.components(graph, stage = "final")

Arguments

Value

Integer vector of component IDs, one per vertex.

Examples

graph <- dgraph(list(2L, 1L, integer()))
graph.connected.components(graph)
graph.embedding — detailed help

Title

Embed Graph in 2D or 3D Space

Name

graph.embedding

Description

Embed Graph in 2D or 3D Space

Usage

graph.embedding(
  graph,
  edge.attribute = NULL,
  transform = c("identity", "reciprocal"),
  dim = 2,
  method = c("fr", "kk"),
  verbose = FALSE,
  stage = "final"
)

Arguments

Value

Numeric layout matrix with one row per embedded vertex.

Examples

set.seed(1)
graph <- create.graph("cycle", 6)
graph.embedding(graph, dim = 2, method = "fr")
graph.geodesic.distances — detailed help

Title

Compute Graph Geodesic Distances

Name

graph.geodesic.distances

Description

Compute exact shortest-path distances on a supplied graph, or on a graph constructed from coordinates. These graph distances may approximate a continuous geometric distance; construction alone does not make them exact manifold geodesics. Supply exactly one of graph and points.

Usage

graph.geodesic.distances(
  graph = NULL,
  vertices = NULL,
  stage = "final",
  distance = c("length", "hop"),
  points = NULL,
  graph.type = NULL,
  k = NULL
)

Arguments

Details

For repeated calculations or more construction options, build a graph separately and supply it via graph. Coordinate construction uses untransformed Euclidean distances. The exact symmetric-neighbor search evaluates all pairs; MST construction uses a dense Prim search with quadratic time and linear auxiliary storage. Selected-vertex output has length(vertices)^2 entries; all-pairs output has n^2 entries.

Value

A numeric square matrix in the requested vertex order; unreachable pairs have infinite distance. Zero-length edges remain traversable. Row names from points, or adjacency labels from graph, label the matrix when present.

Examples

graph <- create.graph("chain", 5)
graph.geodesic.distances(graph, vertices = c(1, 5))
graph.geodesic.distances(create.graph("cycle", 5), distance = "hop")
X <- matrix(c(0, 0, 1, 10), ncol = 1)
graph.geodesic.distances(points = X, graph.type = "mst")
graph.geodesic.distances(points = X, graph.type = "sknn", k = 1)
graph.spectral.embedding — detailed help

Title

Embed a Connected Graph Using its Positive Laplacian Spectrum

Name

graph.spectral.embedding

Description

Embed a Connected Graph Using its Positive Laplacian Spectrum

Usage

graph.spectral.embedding(spectrum, dim = 2, scale = c("none", "inverse.sqrt"))

Arguments

Details

The spectrum object carries the eigenvalue ordering, zero-mode tolerance and component information, so embedding never discards a column by position in an arbitrary eigenvector matrix. Disconnected graphs are rejected: embed each component separately with create.subgraph() and graph.spectrum(). There is no implied distance between separate components. Singleton and empty graphs have no positive-dimensional spectral embedding.

Unscaled coordinates are a spectral representation, not original physical coordinates. On a connected graph, inverse-square-root scaling using all positive modes makes squared Euclidean distances equal to effective resistance; using fewer modes gives a truncated representation. Neither choice generally reproduces shortest-path or manifold geodesic distances. Signs and bases within tied eigenvalues can vary; choose whole tied eigenspaces when comparing embedding distances across backends.

Value

Numeric matrix with one row per vertex and columns Dim1, Dim2, and so on. Columns use the smallest dim positive eigenvalues.

See Also

graph.spectrum(), graph.embedding()

Examples

graph <- create.graph("chain", 8)
spectrum <- graph.spectrum(graph, nev = 3)
graph.spectral.embedding(spectrum, dim = 2)
graph.spectral.embedding(spectrum, dim = 3, scale = "inverse.sqrt")
graph.spectrum — detailed help

Title

Compute the Positive Spectrum of an Unweighted Graph Laplacian

Name

graph.spectrum

Description

Compute the Positive Spectrum of an Unweighted Graph Laplacian

Usage

graph.spectrum(
  graph,
  nev = NULL,
  use.R = FALSE,
  return.Laplacian = FALSE,
  return.dense = FALSE,
  tol = NULL
)

Arguments

Details

Every component contributes one zero mode, including isolated vertices. These modes are omitted from evalues and evectors; their number is determined from topology and checked against the computed spectrum. The native backend uses sparse Lanczos for partial spectra, requesting the component zero modes as well, and a dense eigensolver for the full spectrum. The R backend computes the full dense spectrum before selection. Thus a small explicit nev is preferable for large graphs. Dense solves require quadratic memory; requesting all positive modes is not a sparse operation.

Eigenvector signs and bases within repeated-eigenvalue subspaces are not unique. If nev or an embedding dimension cuts through a repeated eigenvalue, the selected subspace and embedding distances can differ between backends. Include the whole tied eigenspace for invariant comparisons.

Value

A graph_spectrum list with evalues (the requested positive eigenvalues in increasing order), evectors (one row per original vertex, one orthonormal column per eigenvalue), nullity (the exact number of connected components), components (component IDs in vertex order), and the resolved tolerance. When requested, laplacian contains L. An empty or edgeless graph has no positive modes and an n by zero eigenvector matrix when nev = NULL or nev = 0.

See Also

graph.spectral.embedding(), graph.connected.components()

Examples

graph <- create.graph("chain", 8)
spectrum <- graph.spectrum(graph, nev = 3)
spectrum$evalues
spectrum$nullity # one omitted zero mode
graph.spectral.embedding(spectrum, dim = 2)
graph.summary.divergence — detailed help

Title

Compute divergence between two graphs using a selected graph summary

Name

graph.summary.divergence

Description

Extracts one selected graph summary from two graph-like objects and computes a divergence between the resulting probability mass functions.

Currently the supported divergence is Jensen-Shannon divergence, implemented via jensen.shannon.divergence().

Usage

graph.summary.divergence(
  graph1,
  graph2,
  summary = c("degree_distribution", "edge_weight_distribution",
    "component_size_distribution", "neighborhood_label_distribution"),
  divergence = c("js"),
  labels = NULL,
  summary.args = list(),
  support = NULL,
  return.details = TRUE
)

Arguments

Value

If return.details = TRUE, a list with fields:

  • summary: summary type used.

  • divergence: divergence type used.

  • value: scalar divergence value.

  • pmf1: aligned PMF for g1.

  • pmf2: aligned PMF for g2.

  • support: aligned support.

  • metadata: summary-specific metadata for both graphs.

Otherwise, returns the scalar divergence value.

Examples

path <- dgraph(list(2L, c(1L, 3L), 2L))
triangle <- dgraph(list(c(2L, 3L), c(1L, 3L), c(1L, 2L)))
graph.summary.divergence(
  path,
  triangle,
  summary = "degree_distribution"
)
identical.vertex.set.weighted.graph.similarity — detailed help

Title

Weighted Graph Distance Between Graphs with Identical Vertex Sets

Name

identical.vertex.set.weighted.graph.similarity

Description

Weighted Graph Distance Between Graphs with Identical Vertex Sets

Usage

identical.vertex.set.weighted.graph.similarity(
  adj.list1,
  length.list1,
  adj.list2,
  length.list2,
  calculate.normalized.deviation = FALSE
)

Arguments

Value

Numeric distance-matrix deviation.

Examples

graph <- list(2L, c(1L, 3L), 2L)
weights1 <- list(1, c(1, 1), 1)
weights2 <- list(1, c(1, 2), 2)
identical.vertex.set.weighted.graph.similarity(
  graph, weights1, graph, weights2
)
inspect.path.graph — detailed help

Title

Inspect a Path Graph

Name

inspect.path.graph

Description

Inspect a Path Graph

Usage

## S3 method for class 'path.graph'
print(x, ...)

## S3 method for class 'path.graph'
summary(object, ...)

Arguments

Value

print() invisibly returns its unchanged input after printing graph counts. summary() prints and invisibly returns a named list containing n.vertices, n.paths, avg.path.length (number of vertices per stored path, or NA if no paths), and avg.degree (mean adjacency-list length).

Examples

chain <- create.graph("chain", n = 5)
paths <- create.path.graph(chain, h.values = 2)[[1L]]
print(paths)
summary(paths)
inspect.path.graph.series — detailed help

Title

Inspect a Collection of Hop-Constrained Path Graphs

Name

inspect.path.graph.series

Description

Inspect a Collection of Hop-Constrained Path Graphs

Usage

## S3 method for class 'path.graph.series'
summary(object, ...)

## S3 method for class 'path.graph.series'
print(x, ...)

Arguments

Value

summary() returns a data frame of hop limits, vertex counts, edge counts and stored route counts. print() displays up to ten rows and returns the original collection invisibly. No paths are recomputed.

Examples

paths <- create.path.graph(create.graph("chain", 6), h.values = c(1, 2, 4))
print(paths)
summary(paths)
inspect.synthetic_geometry_sample — detailed help

Title

Inspect a Synthetic Geometry Sample

Name

inspect.synthetic_geometry_sample

Description

Inspect a Synthetic Geometry Sample

Usage

## S3 method for class 'synthetic_geometry_sample'
print(x, ...)

## S3 method for class 'synthetic_geometry_sample'
summary(object, ...)

## S3 method for class 'summary.synthetic_geometry_sample'
print(x, ...)

Arguments

Value

print() returns its input invisibly. summary() returns a summary.synthetic_geometry_sample with dimensions, geometry/sampling families, coordinate ranges, observed region counts and RNG mode. State vectors remain available in the sample’s ⁠$rng⁠ without being printed.

Examples

x <- sample.synthetic.geometry(synthetic.circle(),
  synthetic.sampling.uniform.interval(0, 2*pi), n = 5, seed = 17)
print(x)
summary(x)
isometry.distance.correlations — detailed help

Title

Compute Distance Preservation Correlations

Name

isometry.distance.correlations

Description

Computes Pearson and Spearman correlations between estimated and true pairwise distances over the upper-triangular distance entries.

Usage

isometry.distance.correlations(
  D.estimated,
  D.true,
  true.tol = sqrt(.Machine$double.eps)
)

Arguments

Value

Named numeric vector with entries pearson_cor and spearman_cor.

Examples

D <- as.matrix(dist(1:4))
isometry.distance.correlations(2 * D, D)
isometry.distortion.quantiles — detailed help

Title

Compute Multiplicative Distortion Quantiles

Name

isometry.distortion.quantiles

Description

Computes quantiles of the calibrated pairwise distortion

{ij}=D{ij}/D_{ij}.

Values near 1 indicate approximately isometric distance preservation.

Usage

isometry.distortion.quantiles(
  D.estimated,
  D.true,
  probs = c(0.05, 0.5, 0.95),
  scale = TRUE,
  true.tol = sqrt(.Machine$double.eps)
)

Arguments

Value

Named numeric vector of distortion quantiles.

Examples

D <- as.matrix(dist(1:4))
isometry.distortion.quantiles(1.1 * D, D)
isometry.geodesic.diagnostics — detailed help

Title

Compute Geodesic-Isometry Diagnostics

Name

isometry.geodesic.diagnostics

Description

Computes signed and scale-regime diagnostics for comparing estimated graph geodesic distances with reference geodesic distances. Distances are first optionally calibrated by the least-squares scale from isometry.scale().

Usage

isometry.geodesic.diagnostics(
  D.estimated,
  D.true,
  scale = TRUE,
  true.tol = sqrt(.Machine$double.eps),
  band.probs = c(1/3, 2/3)
)

Arguments

Value

Named numeric vector with target-normalized graph-geodesic relative RMSE, signed residual bias, shortcut fraction, relative absolute residual quantiles, and median signed relative residuals in short/mid/long reference-distance bands. The relative-RMSE entry retains the historical name rel_geodesic_stress; it is not Kruskal’s Stress-1.

Examples

D <- as.matrix(dist(1:4))
isometry.geodesic.diagnostics(1.1 * D, D)
isometry.rel.abs.error — detailed help

Title

Compute Relative Absolute Isometry Errors

Name

isometry.rel.abs.error

Description

Computes quantiles of pairwise relative absolute errors

|D_{ij}-D_{ij}|/D_{ij}.

Usage

isometry.rel.abs.error(
  D.estimated,
  D.true,
  probs = c(0.5, 0.95),
  scale = TRUE,
  true.tol = sqrt(.Machine$double.eps)
)

Arguments

Value

Named numeric vector of relative absolute error quantiles.

Examples

D <- as.matrix(dist(1:4))
isometry.rel.abs.error(1.1 * D, D)
isometry.rel.rms.error — detailed help

Title

Compute Relative RMS Isometry Error

Name

isometry.rel.rms.error

Description

Computes the relative root-mean-square distance-matrix error after optional scalar calibration:

^{1/2}.

Usage

isometry.rel.rms.error(
  D.estimated,
  D.true,
  scale = TRUE,
  true.tol = sqrt(.Machine$double.eps)
)

Arguments

Value

Numeric scalar relative RMS error.

Examples

D <- as.matrix(dist(1:4))
isometry.rel.rms.error(2 * D, D)
isometry.scale — detailed help

Title

Compute the Optimal Isometry Calibration Scale

Name

isometry.scale

Description

Computes the least-squares scalar that aligns estimated distances to true distances:

^* = {{i<j} D{ij}^2}.

Usage

isometry.scale(D.estimated, D.true, true.tol = sqrt(.Machine$double.eps))

Arguments

Value

Numeric scalar calibration scale.

Examples

D <- as.matrix(dist(1:4))
isometry.scale(2 * D, D)
jensen.shannon.divergence — detailed help

Title

Jensen-Shannon Divergence

Name

jensen.shannon.divergence

Description

Jensen-Shannon Divergence

Usage

jensen.shannon.divergence(p, q)

Arguments

Value

Jensen-Shannon divergence using log base 2.

Examples

jensen.shannon.divergence(c(0.75, 0.25), c(0.5, 0.5))
join.graphs — detailed help

Title

Join Two Adjacency-List Graphs

Name

join.graphs

Description

Join Two Adjacency-List Graphs

Usage

join.graphs(graph1, graph2, i1, i2)

Arguments

Value

A dgraph with vertices i1 and i2 identified. Both inputs must have lengths or both omit them, and must share their edge-attribute names.

Examples

first <- dgraph(list(2L, 1L))
second <- dgraph(list(2L, 1L))
join.graphs(first, second, i1 = 2, i2 = 1)
minh.limit — detailed help

Title

Find the Minimum Hop Limit for Path Existence

Name

minh.limit

Description

Find the Minimum Hop Limit for Path Existence

Usage

minh.limit(path.result, from, to)

Arguments

Value

Minimum hop limit where the path exists, or NULL.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
series <- create.path.graph(dgraph(graph, lengths), h.values = 1:2)
minh.limit(series, from = 1, to = 3)
nerve.graph — detailed help

Title

Construct the Nerve Graph of a Cover

Name

nerve.graph

Description

Construct the Nerve Graph of a Cover

Usage

nerve.graph(covering.list, n.cores = 1)

Arguments

Value

A dgraph with no lengths and overlap cardinalities stored in the overlap edge attribute.

Examples

cover <- list(c(1, 2, 3), c(3, 4), c(5, 6))
graph.edges(nerve.graph(cover, n.cores = 1))
new.path.graph — detailed help

Title

Construct a path.graph object

Name

new.path.graph

Description

Construct a path.graph object

Usage

new.path.graph(adj.list, length.list, hop.list, shortest.paths)

Value

A list of class “path.graph” containing aligned adjacency, edge-length, and hop-count lists together with the stored shortest paths.

overlap.distribution.plot — detailed help

Title

Plot the distribution of overlap values

Name

overlap.distribution.plot

Description

Plot the distribution of overlap values

Usage

overlap.distribution.plot(x, radius_idx = NULL)

Arguments

Value

Invisibly returns NULL

path.dist — detailed help

Title

Normalized Cumulative Distance Along a Vertex Path

Name

path.dist

Description

Normalized Cumulative Distance Along a Vertex Path

Usage

path.dist(s, V)

Arguments

Value

Numeric vector of length length(s). For a positive-length path, cumulative Euclidean distances start at zero and end at one. A singleton or zero-length path returns all zeros. Empty paths and total lengths exceeding the finite numeric range are rejected.

See Also

path.length(), subdivide.path()

Examples

vertices <- rbind(c(0, 0), c(1, 0), c(1, 2))
path.dist(1:3, vertices)
path.dist(2, vertices) # a singleton has normalized distance zero
path.length — detailed help

Title

Compute Euclidean Path Length

Name

path.length

Description

Compute Euclidean Path Length

Usage

path.length(X)

Arguments

Value

Total Euclidean length of the polyline. Singleton paths and paths whose points all coincide have length zero. Empty paths and total lengths exceeding the finite numeric range are rejected.

See Also

path.dist(), subdivide.path()

Examples

path.length(rbind(c(0, 0), c(1, 0), c(1, 2)))
path.length(matrix(c(1, 2), nrow = 1)) # zero
plot.IkNNgraphs — detailed help

Title

Plot Diagnostics for Intersection k-NN Graph Analysis

Name

plot.IkNNgraphs

Description

Plot Diagnostics for Intersection k-NN Graph Analysis

Usage

## S3 method for class 'IkNNgraphs'
plot(
  x,
  type = "diag",
  diags = c("edist", "edge", "deg"),
  with.pwlm = TRUE,
  with.lmin = FALSE,
  breakpoint.col = "blue",
  lmin.col = "gray",
  mar = c(2.5, 2.5, 0.5, 0.5),
  mgp = c(2.5, 0.5, 0),
  tcl = -0.3,
  xline = 2.4,
  yline = 3.15,
  ...
)

Arguments

Value

Invisibly returns TRUE.

Examples

diagnostics <- structure(list(k.values = 2:4, edit.distances = c(0.3, 0.2),
  n.edges.in.pruned.graph = c(6, 8, 10), js.div = c(0.1, 0.05)),
  class = "IkNNgraphs")
plot(diagnostics, with.pwlm = FALSE)
plot.build_iknn_graphs_and_selectk — detailed help

Title

Plot method for build_iknn_graphs_and_selectk

Name

plot.build_iknn_graphs_and_selectk

Description

Plot method for build_iknn_graphs_and_selectk

Usage

## S3 method for class 'build_iknn_graphs_and_selectk'
plot(
  x,
  which = c("connect", "edit", "mixing"),
  connect.args = list(),
  edit.args = list(),
  mixing.args = list(),
  par.args = list(),
  ...
)

Arguments

Value

Invisibly returns x, unchanged, after producing the requested panels. If which is empty, invisibly returns NULL without plotting.

Examples

set.seed(1)
X <- matrix(rnorm(60), ncol = 2)
selected <- build.iknn.graphs.and.selectk(X, k.values = seq.int(2, 4),
    method = "edit",
    verbose = FALSE)
plot(selected, which = "connect")
plot.cst_graph_mixing_stats — detailed help

Title

Plot method for cst_graph_mixing_stats

Name

plot.cst_graph_mixing_stats

Description

Plot method for cst_graph_mixing_stats

Usage

## S3 method for class 'cst_graph_mixing_stats'
plot(
  x,
  which = c("null.homophily", "null.assortativity", "mixing.matrix", "conductance"),
  ...
)

Arguments

Value

Invisibly returns NULL after producing the requested diagnostic panels.

Examples

mixing <- structure(list(mixing.matrix = matrix(c(4, 1, 1, 4), 2,
  dimnames = list(c("A", "B"), c("A", "B")))),
  class = "cst_graph_mixing_stats")
plot(mixing, which = "mixing.matrix")
plot.dgraph — detailed help

Title

Plot a dgraph with Reusable Coordinates

Name

plot.dgraph

Description

Draw each undirected edge once and color vertices by values or explicit colors. Coordinates are computed by graph.embedding() only when absent. Layout computation remains available separately in two or three dimensions.

Usage

## S3 method for class 'dgraph'
plot(
  x,
  coordinates = NULL,
  vertex.values = NULL,
  vertex.colors = NULL,
  vertex.size = 1,
  edge.alpha = 0.2,
  color.palette = NULL,
  main = "",
  add.legend = TRUE,
  stage = "final",
  method = c("fr", "kk"),
  edge.attribute = NULL,
  transform = c("identity", "reciprocal"),
  projection = NULL,
  ...
)

Arguments

Value

Invisibly returns the two-column coordinates actually drawn. These can be supplied to subsequent calls to reuse the layout. Graphics settings are restored after plotting.

Examples

graph <- create.graph("cycle", n = 6)
xy <- plot(graph, vertex.values = 1:6)
plot(graph, coordinates = xy, vertex.values = rep(1, 6))
xyz <- graph.embedding(graph, dim = 3)
plot(graph, coordinates = xyz, projection = c(1, 3), vertex.colors = "navy")
plot.geodesic_stats — detailed help

Title

Plot Geodesic Statistics

Name

plot.geodesic_stats

Description

Creates visualizations of geodesic statistics to help understand the relationship between radius and number of geodesics.

Usage

## S3 method for class 'geodesic_stats'
plot(
  x,
  plot.type = c("summary", "heatmap", "vertex", "all"),
  selected.vertices = NULL,
  max.vertices = 10,
  ...
)

Arguments

Value

Invisibly returns NULL.

Examples

stats <- list(
  radii = c(0.2, 0.4),
  geodesic_rays = matrix(c(2, 3, 3, 4), nrow = 2, byrow = TRUE),
  composite_geodesics = matrix(c(1, 1, 1, 2), nrow = 2, byrow = TRUE),
  grid_vertices = c(5L, 9L),
  summary = data.frame(
    radius = c(0.2, 0.4),
    avg_rays = c(2.5, 3.5),
    max_rays = c(3, 4),
    composite_ratio = c(0.4, 0.5),
    avg_overlap_median = c(0.35, 0.45)
  )
)
class(stats) <- c("geodesic_stats", "list")

plot(stats, plot.type = "summary")
plot(stats, plot.type = "vertex", selected.vertices = 5)
plot.iknn_stability_metrics — detailed help

Title

Plot Method for IkNN Stability Metrics

Name

plot.iknn_stability_metrics

Description

Plot Method for IkNN Stability Metrics

Usage

## S3 method for class 'iknn_stability_metrics'
plot(x, ...)

Arguments

Value

Invisibly returns TRUE after producing the stability diagnostic plot.

Examples

set.seed(1)
X <- matrix(rnorm(60), ncol = 2)
graphs <- create.iknn.graphs(X, k.values = seq.int(2, 4), compute.full = TRUE,
    verbose = FALSE)
stability <- compute.stability.metrics(graphs)
plot(stability, with.pwlm = FALSE)
plot.vertex_geodesic_stats — detailed help

Title

Plot method for vertex_geodesic_stats objects

Name

plot.vertex_geodesic_stats

Description

Plot method for vertex_geodesic_stats objects

Usage

## S3 method for class 'vertex_geodesic_stats'
plot(x, ...)

Arguments

Value

Invisibly returns NULL

Examples

x <- data.frame(
  radius = c(0.2, 0.4, 0.6),
  rays = c(3, 5, 6),
  composite_geodesics = c(1, 2, 3),
  overlap_min = c(0.10, 0.15, 0.20),
  overlap_p05 = c(0.15, 0.20, 0.25),
  overlap_p25 = c(0.20, 0.25, 0.30),
  overlap_median = c(0.30, 0.40, 0.50),
  overlap_p75 = c(0.40, 0.50, 0.60),
  overlap_p95 = c(0.55, 0.65, 0.75),
  overlap_max = c(0.60, 0.70, 0.80),
  potential_pairs = c(3, 10, 15),
  composite_ratio = c(1/3, 0.2, 0.2),
  overlap_ratio = c(0.30, 0.40, 0.50)
)
class(x) <- c("vertex_geodesic_stats", "data.frame")
attr(x, "vertex") <- 7L

plot(x)
print.build_iknn_graphs_and_selectk — detailed help

Title

Print method for build_iknn_graphs_and_selectk

Name

print.build_iknn_graphs_and_selectk

Description

Print method for build_iknn_graphs_and_selectk

Usage

## S3 method for class 'build_iknn_graphs_and_selectk'
print(x, ...)

Arguments

Value

Invisibly returns x, unchanged, after printing its selected neighborhood sizes and trimming status.

Examples

set.seed(1)
X <- matrix(rnorm(60), ncol = 2)
selected <- build.iknn.graphs.and.selectk(X, k.values = seq.int(2, 4),
    method = "edit",
    verbose = FALSE)
print(selected)
print.dgraph — detailed help

Title

Print an Undirected Graph

Name

print.dgraph

Description

Print an Undirected Graph

Usage

## S3 method for class 'dgraph'
print(x, ...)

Arguments

Value

The unchanged graph, invisibly.

Examples

print(create.graph("empty", 3))
print.geodesic_stats — detailed help

Title

Print method for geodesic_stats objects

Name

print.geodesic_stats

Description

Prints a brief overview of the geodesic statistics.

Usage

## S3 method for class 'geodesic_stats'
print(x, ...)

Arguments

Value

The object invisibly.

Examples

graph <- create.graph("circle", n = 8, sampling = "uniform")
stats <- compute.geodesic.stats(graph.adjacency(graph), graph.lengths(graph), min.radius = 0.3,
    max.radius = 0.5, n.steps = 2, n.packing.vertices = 4)
print(stats)
print.graph.constructors — detailed help

Title

Print Graph Constructor Results

Name

print.graph.constructors

Description

Print Graph Constructor Results

Usage

## S3 method for class 'radius_graph'
print(x, ...)

## S3 method for class 'cknn_graph'
print(x, ...)

## S3 method for class 'rknn_graphs'
print(x, ...)

## S3 method for class 'adaptive_radius_graph'
print(x, ...)

## S3 method for class 'sknn_graphs'
print(x, ...)

## S3 method for class 'sknn_graph'
print(x, ...)

Arguments

Value

The input object x, invisibly and unchanged. Prints vertex and edge counts, construction parameters, and connectivity information when present; for a sequence, prints the graph count and neighborhood sizes.

Examples

X <- cbind(seq_len(8), sin(seq_len(8)))
print(create.rknn.graph(X, type = "fixed", radius = 2))
print(create.cknn.graph(X, k.scale = 2))
print(create.rknn.graph(X, type = "adaptive.radius", k.scale = 2))
print(create.rknn.graphs(X, k.values = seq.int(2, 3)))
print(create.sknn.graph(X, k = 2))
print.knn.outliers — detailed help

Title

Print Method for knn.outliers Objects

Name

print.knn.outliers

Description

Prints a summary of the outlier detection results from remove.knn.outliers.

Usage

## S3 method for class 'knn.outliers'
print(x, ...)

Arguments

Value

Invisibly returns the input object.

Examples

knn.res <- list(
  S.q = matrix(c(0, 0,
                 1, 1,
                 2, 2), ncol = 2, byrow = TRUE),
  y.q = c(1.0, 1.5, 2.0),
  nn.d = matrix(c(0.2, 0.4,
                  0.3, 0.5,
                  1.4, 1.8,
                  0.25, 0.45),
                ncol = 2, byrow = TRUE),
  d.thld = 1,
  idx = c(TRUE, TRUE, FALSE, TRUE),
  n.outliers = 1L,
  method = "qf"
)
class(knn.res) <- "knn.outliers"

knn.res
print.maximal_packing — detailed help

Title

Print Method for Maximal Packing Results

Name

print.maximal_packing

Description

Print Method for Maximal Packing Results

Usage

## S3 method for class 'maximal_packing'
print(x, ...)

Arguments

Value

Invisible copy of x

Examples

x <- list(
  graph = create.graph("chain", 4),
  graph_diameter = 3,
  max_packing_radius = 1.5,
  grid_vertices = c(1L, 4L)
)
class(x) <- "maximal_packing"

x
print.mknn_graph — detailed help

Title

Print Method for mknn_graph Objects

Name

print.mknn_graph

Description

Prints a concise summary of a mutual k-nearest neighbor graph object.

Usage

## S3 method for class 'mknn_graph'
print(x, ...)

Arguments

Value

Invisibly returns the input object.

Examples

graph <- create.mknn.graph(matrix(c(0, 1, 3, 6), ncol = 1), k = 2)
print(graph)
print.mknn_graphs — detailed help

Title

Print Method for mknn_graphs Objects

Name

print.mknn_graphs

Description

Prints a concise summary of a collection of mutual k-nearest neighbor graphs.

Usage

## S3 method for class 'mknn_graphs'
print(x, ...)

Arguments

Value

Invisibly returns the input object.

Examples

graphs <- create.mknn.graphs(matrix(c(0, 1, 3, 6, 9), ncol = 1),
                              k.values = 1:3, verbose = FALSE)
print(graphs)
print.mst_completion_graph — detailed help

Title

Print Method for MST Completion Graph Objects

Name

print.mst_completion_graph

Description

Displays a concise summary of an MST completion graph object, including basic graph statistics and parameter information.

Usage

## S3 method for class 'mst_completion_graph'
print(x, ...)

Arguments

Details

This method provides a human-readable overview of the graph structure without displaying the full adjacency lists. For detailed inspection of graph components, use graph accessors with the desired stage. summary method.

Value

Invisibly returns the input object x.

See Also

summary.mst_completion_graph for more detailed summaries, create.cmst.graph for creating MST completion graphs

Examples

X <- rbind(c(0, 0), c(1, 0), c(0, 1), c(2, 2))
graph <- create.cmst.graph(X, verbose = FALSE)
print(graph)
summary(graph)
print.packing_validation — detailed help

Title

Print Method for Packing Validation Results

Name

print.packing_validation

Description

Print Method for Packing Validation Results

Usage

## S3 method for class 'packing_validation'
print(x, ...)

Arguments

Value

Invisible copy of x

Examples

x <- list(
  valid = TRUE,
  is.maximal = TRUE,
  min.packing.distance = 2,
  max.coverage.distance = 1,
  violations = NULL,
  potential.additions = NULL
)
class(x) <- "packing_validation"

x
print.path.graph.plm — detailed help

Title

Print a Path-Length-Metric Graph

Name

print.path.graph.plm

Description

Print a Path-Length-Metric Graph

Usage

## S3 method for class 'path.graph.plm'
print(x, ...)

Arguments

Value

Invisibly returns x unchanged after printing its vertex, edge and stored-path counts and maximum path length.

Examples

graph <- list(2L, c(1L, 3L), 2L)
lengths <- list(1, c(1, 2), 2)
create.plm.graph(graph, lengths, h = 3)
print.summary.knn.outliers — detailed help

Title

Print Method for summary.knn.outliers Objects

Name

print.summary.knn.outliers

Description

Prints the summary of outlier detection results.

Usage

## S3 method for class 'summary.knn.outliers'
print(x, ...)

Arguments

Value

Invisibly returns the input object.

Examples

knn.res <- list(
  S.q = matrix(c(0, 0,
                 1, 1,
                 2, 2), ncol = 2, byrow = TRUE),
  y.q = c(1.0, 1.5, 2.0),
  nn.d = matrix(c(0.2, 0.4,
                  0.3, 0.5,
                  1.4, 1.8,
                  0.25, 0.45),
                ncol = 2, byrow = TRUE),
  d.thld = 1,
  idx = c(TRUE, TRUE, FALSE, TRUE),
  n.outliers = 1L,
  method = "qf"
)
class(knn.res) <- "knn.outliers"

summary(knn.res)
print.summary.mst_completion_graph — detailed help

Title

Print Summary of MST Completion Graph

Name

print.summary.mst_completion_graph

Description

Formats and displays the summary information for an MST completion graph in a readable format.

Usage

## S3 method for class 'summary.mst_completion_graph'
print(x, digits = 3L, ...)

Arguments

Value

Invisibly returns the input summary object.

Examples

X <- rbind(c(0, 0), c(1, 0), c(0, 1), c(2, 2))
graph <- create.cmst.graph(X, verbose = FALSE)
print(graph)
summary(graph)
quadform.gradient — detailed help

Title

Evaluate gradients of all quadforms

Name

quadform.gradient

Description

Evaluate gradients of all quadforms

Usage

quadform.gradient(geometry, latent)

Arguments

Value

For one form, an n by d matrix. For multiple forms, an n by r by d array. With no forms, an n by zero by d array.

Examples

geometry <- synthetic.quadform(1L, 2L, forms = list(matrix(1)))
quadform.gradient(geometry, matrix(c(-1, 0, 1), ncol = 1))
quadform.metric — detailed help

Title

Evaluate the induced metric of a quadform geometry

Name

quadform.metric

Description

Evaluate the induced metric of a quadform geometry

Usage

quadform.metric(geometry, latent)

Arguments

Value

For one row, a d by d matrix; otherwise an n by d by d array.

Examples

geometry <- synthetic.quadform(1L, 2L, forms = list(matrix(1)))
quadform.metric(geometry, matrix(c(0, 1), ncol = 1))
quadform_geodesics — detailed help

Title

Estimate distances on a declared quadratic graph surface

Name

quadform_geodesics

Description

Internal common interface for paired endpoint queries on F(u)=(u,u^T A u). A method must be selected explicitly.

Usage

quadform_geodesics(
  A,
  from,
  to,
  domain,
  method,
  control = list(),
  return.paths = FALSE
)

Arguments

Details

Grid edges use the native analytic lifted-segment lengths. Primitive lattice offsets up to direction_radius supply directions; radius one is the eight-neighbor stencil. Finer spacing alone does not remove its directional bias. Off-grid endpoints attach to nearest retained vertices. The optional direct connector is an explicit graph edge, not a fallback. Search uses strict binary64 comparisons; the selected path total is recomputed with the native exact accumulator.

Clairaut requires ⁠A = a I⁠ exactly. It solves radial-monotone or turning branches of the continuous surface metric, with separate flat, apex, radial and antipodal cases. Origin-centered disks use a whole-path radial envelope; other domains require conservative radial/angular section enclosures. Leaving the domain or unresolved containment returns unsupported, not a boundary-constrained replacement. Curved polar cases outside the initial numeric scope (minimum endpoint radius below 1e-100, maximum above 1e100, or twice absolute curvature times maximum radius above 1e6) are explicitly unsupported. These restrictions do not apply to flat, coincident or apex cases.

Boundary optimization uses NLopt COBYLA to vary interior vertices of a lifted domain polyline. Bounds constrain a rectangle; a quadratic inequality per vertex constrains a disk. All accepted vertices must also pass the strict floating-point domain check, independently of NLopt’s constraint status. Convexity then keeps every lifted domain segment in D. The direct connector is an explicit initial candidate. Each accepted replacement must be shorter by more than the sum of the two numerical length-error estimates. A feasible supplied initial path competes with the direct connector, rather than silently replacing it.

Optimization coordinates are centered and divided by the domain radius or largest box width. The position tolerance and initial step use these normalized units. Starts add sine-shaped normal displacements controlled by initial_bends, projected into D only to construct feasible initial guesses. Subsequent levels bisect the retained path, up to 257 vertices. Objective-evaluation or time limits, and incomplete individual searches, retain the best feasible path as partial. A position-tolerance stop is not a stationarity or global-optimality certificate. No states are saved.

Delaunay and radius references insert endpoints into either the supplied vertex set or a regular lattice clipped to D, remove exact duplicates, and sort vertices lexicographically. Delaunay uses geometry::delaunayn with Qhull options ⁠Qt Qbb Qc Qz⁠, without randomized perturbation. The package geometry is an optional dependency for Delaunay and mesh methods. Its simplices supply all one-skeleton edges. Radius graphs instead join all pairs at Euclidean domain distance at most radius. There is no direct-edge override or silent connectivity repair. Edge weights are analytic lifted straight-segment lengths, not ambient chords. Boost Dijkstra selects a graph path, whose length is recomputed with the exact accumulator. In 3D and 4D, the same analytic integral is used with higher-dimensional endpoint slopes and propagated numerical error estimates. The entire triangulation and pair preparation count toward total time, but Qhull is an indivisible call: its time allowance is checked before and after it, not enforced as an operating-system deadline.

The polyhedral method uses Kirsanov’s implementation of the Mitchell–Mount–Papadimitriou triangle-interior propagation algorithm on a two-dimensional Delaunay triangulation lifted at its vertices. Its domain is the triangulated convex hull of these points, a subset of D, not the whole disk when D is circular. The upstream small-interval cutoff is 1e-6 times edge length. Live intervals and propagation counts are bounded; user interrupts release owned intervals before propagating to R. Degenerate triangles or unresolved numerical invariants return no path. In particular, inserting very close endpoints can create angles below the mesh engine’s 1e-5-radian limit. Rejections retain the offending angle and the endpoint separation relative to mesh scale; endpoints are never merged or moved to make the triangulation pass.

For polyhedral_surface_polyline, surface_path is a path across flat mesh triangles and path is its domain projection. length measures that mesh path, not a smooth-surface path. The separate diagnostic smooth_lifted_length measures the lifted domain polyline obtained from its projection. These two numbers must not be interchanged in comparisons. Mesh length_error_estimate is missing, not zero; the algorithm’s name does not imply a rigorous certificate. Kept mesh vertices and triangles are available under backend_result$mesh when keep_mesh = TRUE.

Shooting adjusts the initial velocity of the geodesic equation using its variational equations and damped Newton iterations. Integration uses Boost’s controlled Dormand–Prince 5(4) stepper. Collocation independently solves the four-state boundary-value equations with fourth-order Lobatto collocation, a sparse analytic Jacobian and damped Newton steps. Both use the equation

u’‘=-(u’^T(2A)u’).

Coordinates are translated to the canonical first endpoint and divided by the domain-coordinate distance between endpoints. Thus endpoint tolerance is relative to that distance, not to the domain’s diameter.

A zero initial bend starts with a flat surface and continues through increasing multiples of A to the requested surface. The initial step is 1/continuation_steps; successful steps grow by 1.5 and unsuccessful steps halve. Collocation refines and checks the equation residual at each continuation stage before advancing. Nonzero bends are additional direct starts on the full surface. If delta joins the normalized endpoints and J rotates by 90 degrees, shooting starts with velocity ⁠delta + bend * J delta⁠; collocation starts with the curve ⁠a + t * delta + bend * sin(pit) J delta⁠, with its derivative. initial_nodes sets the initial collocation mesh; shooting uses adaptive integration nodes. The shortest accepted start is retained, with overlapping numerical length-error intervals resolved by start order.

ode_tolerance bounds a sampled, componentwise scaled residual of cubic Hermite state interpolation, not a rigorous solution error. Intervals are tested at fractions 0.2113248654, 0.5 and 0.7886751346. Only intervals that fail this check are bisected. Collocation resolves the enlarged system; shooting integrates from each affected interval’s left state to its midpoint, retaining the existing nodes. Shooting’s relative integration tolerance is integration_tolerance, with absolute tolerance one hundredth of it. iterations limits each Newton solve; max_evaluations counts equation evaluations across all starts, continuation and residual checks. Collocation’s Newton stopping test divides each differential-equation row by one plus the Simpson-weighted absolute right-hand side; endpoint rows retain scale one. The Newton step and backtracking merit function remain unscaled. This avoids imposing an unattainable absolute equation tolerance on steep surfaces without relaxing endpoint accuracy.

Continuous candidates are converted to lifted domain polylines. Recursive cubic Bezier control-hull checks establish containment of the interpolated domain curve using floating-point arithmetic. Midpoint and quarter-point subdivision compares lifted-connector lengths using a total allowance of path_tolerance times the direct connector length. Each accepted section emits its coarse connector; midpoint and quarter points are used for the check, not automatically added to the output. This is a refinement diagnostic, not a certified discretization bound. length_error_estimate concerns only the returned polyline’s length. Endpoint residuals are measured before fixing the returned endpoints exactly; reported residuals have the original domain-coordinate units.

A stationary path need not be the shortest path. The diagnostics retain each start’s outcome, the selected start, equation and endpoint residuals, and the direct connector length for comparison. There is no silent fallback to a different method and no boundary-following solver. A retained candidate with unresolved starts or an exhausted overall budget is partial; no usable path gives failed, or unsupported when all completed attempts leave the domain and none remains unresolved. A mixture of outside curves and unresolved starts is failed, not evidence that the geometry is unsupported. The first observed outside point is retained for each rejected start. These methods do not handle more than one quadratic form or domain dimension other than two. Nontrivial pairs require endpoint separation between 1e-100 and 1e100, maximum absolute entry of 2 * separation * A at most 2048 and maximum absolute component of 2 * A * canonical_from at most 1e6. Out-of-scope cases return unsupported; flat and coincident pairs bypass these restrictions.

For analytic_clairaut_curve, path is a sampled display of the curve, not a polyline whose length equals length. curve_parameters describe the authoritative curve; the numerical endpoint residual is retained. Parameterize it by t = t_from + s * t_span, for s between zero and one; use the retained t_span, not subtraction of rounded endpoints. With r = , its polar angle is theta_turn plus angular_sign * sign(t) * H(c, abs(t)), where H(c,t)=kc,(kt/)+ (t,c). caller_reversed indicates whether to traverse this parameterization backward to follow the caller’s endpoint order. For lifted_domain_polyline, consecutive domain points specify lifted straight segments. All numerical error estimates are nonrigorous. The historical development adapter registry is independent of this package interface and is not activated by these methods. Grid, Clairaut and continuous results are symmetric under endpoint reversal when calculation limits, rather than wall-clock timing, determine completion. A single randomized refinement run is not required to be: its internal orientation is randomized relative to the supplied endpoints. The wrapper preserves the lower-level solver’s behavior and seed semantics.

Value

A list with method, geometry, domain, resolved control, row-preserving summary, and detailed pair results. Status is “candidate”, “partial”, “unsupported” or “failed”. Summary length is the numerical distance estimate; length_error_estimate concerns numerical length evaluation, not discretization or optimization error. approximation_error is missing and global_optimality_certified is FALSE. Detailed results retain backend_result, including all six outcomes and total costs for the best-of-six strategy. A completed budget is not an accuracy certificate. User interrupts and input errors propagate.

quadform_geodesics_best_of_six — detailed help

Title

Select a path from six quadratic-surface refinement searches

Name

quadform_geodesics_best_of_six

Description

Run both refinement methods with all three neighborhood rules and return the shortest usable result. Each search starts afresh from the same seeded equal-surface-length initialization. This is a finite-budget heuristic, not a certificate of a globally shortest surface path.

Usage

quadform_geodesics_best_of_six(
  A,
  from,
  to,
  domain,
  seed = 1,
  length_scale = 1,
  initial_edges = 16L,
  candidates = 32L,
  max_epochs = 64L,
  max_vertices = 257L,
  max_edge_calls = Inf,
  max_seconds = Inf,
  cache_edges = 0L,
  rejection_cap = 1000L,
  random_orientation = TRUE,
  trace = FALSE,
  trace_limit = 1000L
)

Arguments

Details

Searches use the same seed to preserve their initialization, but may diverge in their candidate draws and visits as their paths change. They execute serially and do not change R’s random state. Parallelize independent endpoint pairs in separate R processes rather than nesting workers inside this function. No state files are saved.

Value

The selected solver result, with an additional ensemble list. ensembleresults</code>retainsallsixsolverresultsand<code>ensembleresults</code> retains all six solver results and <code>ensemblesummary records methods, rules, seeds, lengths, error estimates, statuses, round completion and costs. selected_index identifies the minimum estimated length; exact length ties prefer the earlier row. tied_indices also includes usable results whose difference from the selected length is no larger than their combined estimated errors. These estimates are not rigorous intervals. Numerical ties never cause a longer estimated path to replace the minimum. status within ensemble is “complete” when all six round budgets complete (or endpoints coincide), “partial” when at least one usable path is available but some search is incomplete, and “no_path” when none is usable. In the latter case selected_index is missing and the top-level result is the first no-path solver result. Top-level counters describe the selected search only; total cost is in ensemble$total_edge_calls, total_solver_seconds, and total_call_seconds. Input errors and unexpected R errors propagate.

quadform_geodesics_solver — detailed help

Title

Refine a path on a quadratic graph surface

Name

quadform_geodesics_solver

Description

Internal solver for the surface F(u) = (u, u^T A u) over a disk or rectangle. Initialization uses approximately equal surface-length segments.

Usage

quadform_geodesics_solver(
  A,
  from,
  to,
  domain,
  method = c("single_point", "local_network"),
  neighborhood = c("fixed_span", "neighbors", "fixed_disk"),
  seed = 1,
  length_scale = 1,
  initial_edges = 16L,
  candidates = 32L,
  max_epochs = 8L,
  plateau_epochs = 2L,
  max_vertices = 257L,
  max_edge_calls = 2e+05,
  max_seconds = Inf,
  cache_edges = 65536L,
  rejection_cap = 1000L,
  random_orientation = TRUE,
  trace = FALSE,
  trace_limit = 1000L
)

Arguments

Details

Edge lengths use a scaled analytic integral, with cancellation-free divided differences and explicit treatment of a zero crossing of the vertical tangent. Error estimates include coefficient rounding and a conservative floating-point allowance. They are not rigorous interval bounds. The legacy integrand_evaluations counter is zero because no quadrature samples are used. Both internal precision levels use the same analytic calculation; retrying cannot reduce its roundoff allowance. Returned heights evaluate the exact binary64-input quadratic form using integer arithmetic, then round once to nearest, with ties to even. A height overflowing binary64 raises an error. Path totals likewise round an exact sum of the computed edge records. Local-network search orders these sums exactly, with lexicographic path ties only for exactly equal sums. This does not make the underlying edge estimates exact surface distances. Initialization caps its cumulative tolerance at 1e-6 times the target segment length, preventing an absolute tolerance from swallowing short subdivisions. Unrepresentable subdivisions still return a direct fallback. A plateau containing sampling shortfalls or failed comparison windows ends as “incomplete_exploration”, not “local_stagnation”. Neither is an accuracy certificate. A local-network proposal exceeding max_vertices is rejected whole; a best alternative fitting that limit is not sought. The returned path is not guaranteed to be globally shortest. This internal interface supports one quadratic height over a two-dimensional domain. It requires neither Python nor runtime compilation. Use independent R processes, not concurrent C++ threads, for parallel solves.

Value

A list containing domain path and three-dimensional surface_path, estimated length and error_estimate, initialization, configuration, random-generator identity, counters, termination reason and optional trace. Status is “candidate”, “direct_fallback” or “no_path”. A calculation limit preserves the last completed path; a no-path result has missing length. state_saving is always FALSE: no files or resumable checkpoints are created. User interrupts propagate to R.

read.graph.benchmark — detailed help

Title

Read a Saved Graph Reconstruction Benchmark

Name

read.graph.benchmark

Description

Read the existing dggraphui benchmark manifest and asset tables without launching Shiny or changing any files. Asset paths relative to the run directory are resolved against that directory; absolute paths are retained.

Usage

read.graph.benchmark(project)

Arguments

Value

A list containing the manifest, dataset and graph indexes, saved layout index, metrics, diagnostics, and table summaries. This validates required index files; it does not guarantee that every referenced asset exists or that the scientific results are correct. Assets are loaded on demand by the explorer, which reports missing files.

See Also

explore.graphs(), register.graph.project()

Examples

## Not run: 
run <- read.graph.benchmark("path/to/benchmark/run")
run$summary
head(run$metrics)

## End(Not run)
register.graph.project — detailed help

Title

Remember a Graph Explorer Project

Name

register.graph.project

Description

Register an existing benchmark directory for the explorer’s project picker. Only its name and location are saved. Scientific assets stay in place.

Usage

register.graph.project(project, name, overwrite = FALSE)

Arguments

Value

The updated project catalog, invisibly, with name and path columns. Set options(dgraphs.projects_dir = …) to change its location.

See Also

explore.graphs(), read.graph.benchmark()

Examples

## Not run: 
register.graph.project("path/to/benchmark/run", name = "My graph study")
explore.graphs(project = "My graph study")

## End(Not run)
remove.knn.outliers — detailed help

Title

Remove Outliers from a State Space Using k-Nearest Neighbors

Name

remove.knn.outliers

Description

Identifies and removes outliers from a multivariate state space based on k-nearest neighbor distances. This function implements several strategies for outlier detection, all based on the principle that outliers tend to be isolated from the main data clusters and thus have larger distances to their nearest neighbors.

Usage

remove.knn.outliers(
  S,
  y = NULL,
  p = 0.98,
  dist.factor = 100,
  k = 30,
  method = "diff.dist.factor"
)

Arguments

Details

The function determines outliers by analyzing the distances between points and their k nearest neighbors. Several detection methods are available:

When k = 1:

Points are flagged as outliers if their distance to the nearest neighbor exceeds the p-th percentile threshold of all nearest neighbor distances.

"dist.factor":

Points are considered outliers if the ratio of the k-th nearest neighbor distance to the 1st nearest neighbor distance exceeds dist.factor.

"diff.dist.factor" (default):

For each point, finds the maximum jump in distance between consecutive neighbors, normalizes by the median jump across all points, and flags points as outliers if their relative jump exceeds dist.factor. This method is particularly robust as it adapts to the overall distribution of distances.

Default unnamed method:

Iteratively checks if the first nearest neighbor distance exceeds the threshold or if any consecutive difference between neighbor distances exceeds the threshold.

Value

A list of class "knn.outliers" containing the following components:

S.q

The filtered state space matrix with outliers removed.

y.q

The filtered dependent variable (if y was provided), otherwise NULL.

nn.d

A matrix of dimensions nrow(S) x k containing distances to the k nearest neighbors for each point.

d.thld

The distance threshold used for outlier detection.

idx

A logical vector indicating which points were kept (TRUE) and which were identified as outliers (FALSE).

n.outliers

The number of outliers detected.

method

The outlier detection method used.

See Also

get.knn for the k-nearest neighbor calculation, quantile for percentile calculations

Examples

# Create a sample dataset with outliers
set.seed(123)
n_normal <- 120
n_outliers <- 6

# Generate normal data
normal_data <- matrix(rnorm(n_normal * 2), ncol = 2)

# Generate outliers far from the main cluster
outliers <- cbind(rnorm(n_outliers, mean = 10, sd = 0.5),
                  rnorm(n_outliers, mean = 10, sd = 0.5))

# Combine data
S <- rbind(normal_data, outliers)
y <- c(rnorm(n_normal), rnorm(n_outliers, mean = 5))

# Remove outliers using the default method
result <- remove.knn.outliers(S, y, k = 10)

# Print summary
cat("Number of outliers detected:", result$n.outliers, "\n")
cat("Percentage of data retained:",
    round(100 * nrow(result$S.q) / nrow(S), 2), "%\n")

# Use a different method with more conservative threshold
result2 <- remove.knn.outliers(S, y, p = 0.95, method = "dist.factor", dist.factor = 5, k = 10)

# Plot the original and filtered state space
oldpar <- par(mfrow = c(1, 2))
plot(S, col = "gray", main = "Original State Space",
     xlab = "Dimension 1", ylab = "Dimension 2")
points(S[!result$idx, ], col = "red", pch = 16, cex = 1.2)

plot(result$S.q, col = "blue", pch = 16,
     main = "Filtered State Space",
     xlab = "Dimension 1", ylab = "Dimension 2")
legend("topright", legend = c("Retained", "Removed"),
       col = c("blue", "red"), pch = 16)
par(oldpar)
rm.self.loops — detailed help

Title

Remove Self-Loops from an Adjacency List

Name

rm.self.loops

Description

Remove Self-Loops from an Adjacency List

Usage

rm.self.loops(adj.list)

Arguments

Value

The adjacency list with entries equal to their vertex index removed.

Examples

rm.self.loops(list(c(1L, 2L), c(1L, 2L)))
sample.synthetic.geometry — detailed help

Title

Realize points on a synthetic geometry with explicit random-state control

Name

sample.synthetic.geometry

Description

Coordinates and sampling algorithms retain the existing version-1 draw order. With a seed or explicit state list, the caller’s RNG kinds and seed presence/value are restored on success and errors. The opt-in current-stream mode instead advances the caller’s stream. No statistical response or dataset identity is created.

Usage

sample.synthetic.geometry(
  geometry,
  sampling,
  n = NULL,
  seed = NULL,
  rng.plan = NULL
)

Arguments

Value

A synthetic_geometry_sample list containing predictors, latent, latent.mask, region, frame.matrix, the specifications, dimensions, intrinsic.dim.by.region and codimension.by.region for simplex strata, declared.regions, observed.regions, n, and sample (the original sampler payload). rng contains the effective plan, states after each draw, and final.state for explicit continuation by a caller. In current-stream mode the plan is “current”; returned state vectors are observations, not complete replay tokens for generators with hidden state. A deterministic draw can leave these vectors NULL if no seed exists. The result has no truth or response fields.

Examples

x <- sample.synthetic.geometry(synthetic.circle(),
  synthetic.sampling.uniform.interval(0, 2 * pi), n = 8, seed = 7)
dim(x$predictors)
subdivide.path — detailed help

Title

Subdivide a Path into Arc-Length Spaced Points

Name

subdivide.path

Description

Subdivide a Path into Arc-Length Spaced Points

Usage

subdivide.path(path, n.subdivision.pts)

Arguments

Details

Points are interpolated at equally spaced cumulative Euclidean distances along the input polyline. Zero-length segments are skipped. Equal spacing along the polyline does not imply equal straight-line distances between output points that straddle a corner, and an interior vertex need not appear in the output. Distances are evaluated in floating-point arithmetic; paths whose total length exceeds the finite numeric range are rejected.

Value

Numeric matrix with n.subdivision.pts rows and ncol(path) columns, preserving coordinate column names. The first and last rows are the path endpoints. A singleton or zero-length path repeats its location in every output row. Empty paths are rejected.

See Also

path.length(), path.dist()

Examples

path <- rbind(c(0, 0), c(1, 0), c(1, 2))
subdivide.path(path, n.subdivision.pts = 5)
# Arc distances 0, 0.75, 1.5, 2.25, 3 give:
# (0, 0), (0.75, 0), (1, 0.5), (1, 1.25), (1, 2).
subdivide.path(matrix(c(1, 2), nrow = 1), n.subdivision.pts = 3)
summarize.isometry.deviation — detailed help

Title

Summarize Deviation from Isometry

Name

summarize.isometry.deviation

Description

Computes the standard benchmark summary used to compare graph geodesic distances with reference geodesic distances: optimal scalar calibration, relative RMS error, relative absolute error quantiles, multiplicative distortion quantiles, and distance correlations.

Usage

summarize.isometry.deviation(
  D.estimated,
  D.true,
  scale = TRUE,
  true.tol = sqrt(.Machine$double.eps)
)

Arguments

Value

A one-row data frame.

Examples

D <- as.matrix(dist(1:4))
summarize.isometry.deviation(1.1 * D, D)
summarize_overlap_statistics — detailed help

Title

Summarize overlap statistics from geodesic_stats object

Name

summarize_overlap_statistics

Description

Summarize overlap statistics from geodesic_stats object

Usage

summarize_overlap_statistics(object)

Arguments

Value

A data frame with summary statistics for overlap at each radius

summary.IkNN — detailed help

Title

Summarize IkNN Graph Object

Name

summary.IkNN

Description

Prints a summary of an IkNN graph object, including the number of vertices, edges, and pruning statistics.

Usage

## S3 method for class 'IkNN'
summary(object, ...)

Arguments

Value

Invisibly returns NULL while printing summary information to the console

Examples

graph <- create.single.iknn.graph(matrix(c(0, 1, 3, 6), ncol = 1),
                                   k = 1, verbose = FALSE)
summary(graph)
summary.geodesic_stats — detailed help

Title

Summary method for geodesic_stats objects

Name

summary.geodesic_stats

Description

Provides a summary table of geodesic statistics with percentages and counts for different metric types.

Usage

## S3 method for class 'geodesic_stats'
summary(object, type = c("rays", "composite", "overlap"), ...)

Arguments

Value

A matrix with row for each radius and columns for each unique count value. Each cell contains a string with "percent (count)" format.

Examples

stats <- list(
  radii = c(0.2, 0.4),
  geodesic_rays = matrix(c(2, 3, 3, 4), nrow = 2, byrow = TRUE),
  composite_geodesics = matrix(c(1, 1, 1, 2), nrow = 2, byrow = TRUE),
  path_overlap = list(
    min = matrix(c(0.1, 0.2, 0.2, 0.3), nrow = 2, byrow = TRUE),
    p05 = matrix(c(0.1, 0.2, 0.2, 0.3), nrow = 2, byrow = TRUE),
    p25 = matrix(c(0.2, 0.3, 0.3, 0.4), nrow = 2, byrow = TRUE),
    median = matrix(c(0.3, 0.4, 0.4, 0.5), nrow = 2, byrow = TRUE),
    p75 = matrix(c(0.4, 0.5, 0.5, 0.6), nrow = 2, byrow = TRUE),
    p95 = matrix(c(0.5, 0.6, 0.6, 0.7), nrow = 2, byrow = TRUE),
    max = matrix(c(0.6, 0.7, 0.7, 0.8), nrow = 2, byrow = TRUE)
  )
)
class(stats) <- c("geodesic_stats", "list")

summary(stats)
summary(stats, type = "composite")
summary(stats, type = "overlap")
summary.iknn_graphs — detailed help

Title

Summarize an iknn_graphs Object

Name

summary.iknn_graphs

Description

Provides a detailed summary of an iknn_graphs object created by the create.iknn.graphs() function. The summary includes statistics for each intersection kNN graph in the sequence, displaying information about the connectivity and structure of the graphs for different k values.

Usage

## S3 method for class 'iknn_graphs'
summary(object, use.isize.pruned = FALSE, ...)

Arguments

Details

The summary function extracts and presents key statistics about the structure of each intersection kNN graph in the iknn_graphs object. All graphs share the same number of vertices (equal to the number of rows in the input data matrix), but they differ in the number of edges due to varying k values and the pruning methods applied during graph creation.

The function displays general information about the graph sequence, including the number of vertices, the range of k values, and the pruning parameters used. It then presents a tabular summary of statistics for each individual graph, showing how the graph structure changes as k increases.

For each intersection kNN graph, the following metrics are calculated:

  • Number of edges: Total number of connections in the graph

  • Mean degree: Average number of connections per vertex

  • Min/Max degree: Range of vertex connectivity

  • Density: Proportion of potential connections that are actually present

  • Sparsity: 1 - density, measuring the proportion of missing connections

Value

Invisibly returns a data frame containing statistics for each graph. The data frame has the following columns:

See Also

create.iknn.graphs for creating intersection kNN graphs.

Examples

# Create sample data
set.seed(123)
x <- matrix(rnorm(1000), ncol = 5)

# Generate intersection kNN graphs
iknn.res <- create.iknn.graphs(x, k.values = seq.int(3, 10),
    with.isize.pruning = TRUE)

# Summarize the geometrically pruned graphs
summary(iknn.res)

# Summarize the intersection-size pruned graphs
summary(iknn.res, use.isize.pruned = TRUE)
summary.iterated_iknn_graphs — detailed help

Title

Summarize Iterated Intersection k-NN Graphs

Name

summary.iterated_iknn_graphs

Description

Summarize Iterated Intersection k-NN Graphs

Usage

## S3 method for class 'iterated_iknn_graphs'
summary(object, ...)

Arguments

Value

A data frame with one row per iteration and neighborhood size, reporting vertex, edge and connected-component counts and mean, minimum and maximum degree. This is the object’s stored summary component.

Examples

set.seed(1)
X <- matrix(rnorm(30), ncol = 2)
out <- create.iterated.iknn.graphs(X, k.values = seq.int(2, 3), n.iterations = 1,
    verbose = FALSE)
summary(out)
summary.knn.outliers — detailed help

Title

Summary Method for knn.outliers Objects

Name

summary.knn.outliers

Description

Provides a detailed summary of the outlier detection results from remove.knn.outliers.

Usage

## S3 method for class 'knn.outliers'
summary(object, ...)

Arguments

Value

A list of class "summary.knn.outliers" containing summary statistics.

Examples

knn.res <- list(
  S.q = matrix(c(0, 0,
                 1, 1,
                 2, 2), ncol = 2, byrow = TRUE),
  y.q = c(1.0, 1.5, 2.0),
  nn.d = matrix(c(0.2, 0.4,
                  0.3, 0.5,
                  1.4, 1.8,
                  0.25, 0.45),
                ncol = 2, byrow = TRUE),
  d.thld = 1,
  idx = c(TRUE, TRUE, FALSE, TRUE),
  n.outliers = 1L,
  method = "qf"
)
class(knn.res) <- "knn.outliers"

summary(knn.res)
summary.local_extrema — detailed help

Title

Summarize Local Extrema

Name

summary.local_extrema

Description

Summarize Local Extrema

Usage

## S3 method for class 'local_extrema'
summary(object, ...)

## S3 method for class 'summary.local_extrema'
print(x, ...)

Arguments

Value

summary() returns a list of class summary.local_extrema with n_extrema, extrema_type, summaries of function values, neighborhood sizes and radii, and the data frame extrema_details (labels, vertex indices, values, radii and neighborhood sizes). With no extrema, numerical summaries are NA and the data frame is empty; the type is NA for legacy empty objects without detection-type metadata. print() prints this summary and invisibly returns x unchanged.

Examples

chain <- create.graph("chain", n = 5)
extrema <- detect.local.extrema(graph.adjacency(chain), graph.lengths(chain), y = c(1, 3, 1, 2,
    0), max.radius = 1, min.neighborhood.size = 2)
summary(extrema)
print(summary(extrema))
summary.mknn_graphs — detailed help

Title

Summary Method for mknn_graphs Objects

Name

summary.mknn_graphs

Description

Provides a comprehensive summary of mutual k-nearest neighbor graphs created by create.mknn.graphs, including structural statistics and connectivity information for each k value.

Usage

## S3 method for class 'mknn_graphs'
summary(object, ...)

Arguments

Details

The summary provides insights into how graph structure changes with k:

  • Connected Components: Indicates graph fragmentation. A value of 1 means the graph is fully connected.

  • Degree Statistics: Shows the distribution of vertex connectivity. Large differences between min and max degree may indicate hub vertices.

  • Density/Sparsity: Measures how many of the possible edges are present. MkNN graphs are typically very sparse.

For pruned graphs, the statistics reflect the structure after geometric pruning has been applied.

Value

Invisibly returns a data frame containing graph statistics with columns:

idx

Index of the k value (1 to number of graphs)

k

The k value used for the graph

n_components

Number of connected components

n_edges

Number of edges in the graph

mean_degree

Average vertex degree

min_degree

Minimum vertex degree

max_degree

Maximum vertex degree

density

Graph density (proportion of possible edges present)

sparsity

Graph sparsity (1 - density)

Examples

graphs <- create.mknn.graphs(matrix(c(0, 1, 3, 6, 9), ncol = 1),
                              k.values = 1:3, compute.full = TRUE, verbose = FALSE)
summary(graphs)
summary.mst_completion_graph — detailed help

Title

Summary Method for MST Completion Graph Objects

Name

summary.mst_completion_graph

Description

Computes and returns a comprehensive summary of an MST completion graph, including graph statistics, edge weight distributions, and PCA information if applicable.

Usage

## S3 method for class 'mst_completion_graph'
summary(object, ...)

Arguments

Value

An object of class summary.mst_completion_graph containing:

n_vertices

Number of vertices in the graph

n_mst_edges

Number of edges in the minimal spanning tree

n_cmst_edges

Number of edges in the completed graph

q_thld

Quantile threshold used for completion

edge_weight_summary

Five-number summary of MST edge weights

completion_threshold

The actual distance threshold used

pca_applied

Logical indicating if PCA was applied

pca_info

PCA details (if applicable)

See Also

print.summary.mst_completion_graph for printing summaries, create.cmst.graph for creating graphs

Examples

X <- rbind(c(0, 0), c(1, 0), c(0, 1), c(2, 2))
graph <- create.cmst.graph(X, verbose = FALSE)
print(graph)
summary(graph)
summary.rknn_graphs — detailed help

Title

Summarize an rknn_graphs Object

Name

summary.rknn_graphs

Description

Provides a compact table of graph characteristics for an “rknn_graphs” object created by create.rknn.graphs(). The table reports final edge counts, component-repair counts, degree summaries, and density/sparsity for each adaptive-radius k.scale value.

Usage

## S3 method for class 'rknn_graphs'
summary(object, ...)

Arguments

Value

Invisibly returns a data frame with one row per graph and columns:

See Also

create.rknn.graphs()

Examples

X <- matrix(c(0, 1, 3, 4), ncol = 1)
graphs <- create.rknn.graphs(X, k.values = seq.int(1, 2), radius.search = "all.pairs",
    graph.detail = "minimal",
    prune.method = "none")
summary(graphs)
summary.vertex_geodesic_stats — detailed help

Title

Summary method for vertex_geodesic_stats objects

Name

summary.vertex_geodesic_stats

Description

Summary method for vertex_geodesic_stats objects

Usage

## S3 method for class 'vertex_geodesic_stats'
summary(object, ...)

Arguments

Value

A summary of the vertex geodesic statistics

Examples

x <- data.frame(
  radius = c(0.2, 0.4, 0.6),
  rays = c(3, 5, 6),
  composite_geodesics = c(1, 2, 3),
  overlap_min = c(0.10, 0.15, 0.20),
  overlap_p05 = c(0.15, 0.20, 0.25),
  overlap_p25 = c(0.20, 0.25, 0.30),
  overlap_median = c(0.30, 0.40, 0.50),
  overlap_p75 = c(0.40, 0.50, 0.60),
  overlap_p95 = c(0.55, 0.65, 0.75),
  overlap_max = c(0.60, 0.70, 0.80),
  potential_pairs = c(3, 10, 15),
  composite_ratio = c(1/3, 0.2, 0.2),
  overlap_ratio = c(0.30, 0.40, 0.50)
)
class(x) <- c("vertex_geodesic_stats", "data.frame")
attr(x, "vertex") <- 7L

summary(x)
synthetic.circle — detailed help

Title

Specify a circle geometry

Name

synthetic.circle

Description

Specify a circle geometry

Usage

synthetic.circle(
  radius = 1,
  angle.range = c(0, 2 * pi),
  ambient.dim = 2L,
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.circle(radius = 2, angle.range = c(0, pi))
synthetic.helix — detailed help

Title

Specify a helix geometry

Name

synthetic.helix

Description

Specify a helix geometry

Usage

synthetic.helix(
  pitch = 0.2,
  t.range = c(0, 2 * pi),
  ambient.dim = 3L,
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.helix(pitch = 0.25, t.range = c(0, pi))
synthetic.point.line.junction — detailed help

Title

Specify a point-line junction

Name

synthetic.point.line.junction

Description

Specify a point-line junction

Usage

synthetic.point.line.junction(
  point.location,
  line.origin,
  line.direction,
  line.range
)

Arguments

Value

A two-stratum synthetic_stratified_geometry.

Examples

synthetic.point.line.junction(c(0, 0), c(0, 0), c(1, 0), c(0, 1))
synthetic.quadform — detailed help

Title

Specify a quadform geometry

Name

synthetic.quadform

Description

Specify a quadform geometry

Usage

synthetic.quadform(
  intrinsic.dim,
  ambient.dim,
  forms = list(),
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.quadform(1L, 2L, forms = list(matrix(0.5)))
synthetic.sampling.clustered — detailed help

Title

Clustered sampling specification

Name

synthetic.sampling.clustered

Description

Clustered sampling specification

Usage

synthetic.sampling.clustered(
  cluster.count,
  observations.per.cluster,
  center.lower = -1,
  center.upper = 1,
  within.sd,
  algorithm = "centers.then.gaussian.offsets.v1"
)

Arguments

Value

A fixed-size synthetic sampling component.

Examples

synthetic.sampling.clustered(3L, 5L, within.sd = 0.1)
synthetic.sampling.dirichlet.zeros — detailed help

Title

Dirichlet sampling with structural zeros

Name

synthetic.sampling.dirichlet.zeros

Description

Dirichlet sampling with structural zeros

Usage

synthetic.sampling.dirichlet.zeros(
  concentration,
  zero.fraction,
  zero.parts,
  zero.row.policy = c("first", "random"),
  count.rounding = "round",
  algorithm = "normalized.gamma.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.dirichlet.zeros(
  concentration = rep(1, 3), zero.fraction = 0.2, zero.parts = 1L
)
synthetic.sampling.gapped.uniform — detailed help

Title

Gapped-uniform sampling specification

Name

synthetic.sampling.gapped.uniform

Description

Gapped-uniform sampling specification

Usage

synthetic.sampling.gapped.uniform(
  intervals,
  allocation = c("multinomial", "fixed.proportion", "fixed.count"),
  probabilities = NULL,
  counts = NULL,
  rounding = c("largest.remainder", "floor.first.remainder.last"),
  order = c("draw", "ascending"),
  algorithm = "sequential.interval.runif.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

intervals <- rbind(c(-1, -0.25), c(0.25, 1))
synthetic.sampling.gapped.uniform(intervals, probabilities = c(0.5, 0.5))
synthetic.sampling.grid.interval — detailed help

Title

Deterministic interval-grid sampling specification

Name

synthetic.sampling.grid.interval

Description

Deterministic interval-grid sampling specification

Usage

synthetic.sampling.grid.interval(
  lower,
  upper,
  endpoints = c("exclude.lower", "exclude.upper", "include.both")
)

Arguments

Value

A deterministic synthetic sampling component.

Examples

synthetic.sampling.grid.interval(0, 2 * pi, endpoints = "exclude.lower")
synthetic.sampling.quadform.lab — detailed help

Title

Versioned quadratic-surface sampling used by Geometry Lab

Name

synthetic.sampling.quadform.lab

Description

Versioned quadratic-surface sampling used by Geometry Lab

Usage

synthetic.sampling.quadform.lab(
  domain = c("square", "disk"),
  extent = 1,
  mode = c("uniform", "area", "grid", "center", "gap"),
  gap = 0.2,
  algorithm = "geometry.lab.v1"
)

Arguments

Value

A sampling component for a canonical two-dimensional quadratic surface in three dimensions. Area sampling uses rejection sampling.

Examples

sampling <- synthetic.sampling.quadform.lab("disk", mode = "area")
surface <- synthetic.quadform(2, 3, list(diag(c(1, -1))))
sample.synthetic.geometry(surface, sampling, 30, seed = 4101)$n
synthetic.sampling.truncated.normal — detailed help

Title

Truncated-normal sampling specification

Name

synthetic.sampling.truncated.normal

Description

Truncated-normal sampling specification

Usage

synthetic.sampling.truncated.normal(
  mean,
  sd,
  lower,
  upper,
  order = c("draw", "ascending"),
  algorithm = "inverse.cdf.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.truncated.normal(0, 1, -2, 2)
synthetic.sampling.uniform.box — detailed help

Title

Uniform-box sampling specification

Name

synthetic.sampling.uniform.box

Description

Uniform-box sampling specification

Usage

synthetic.sampling.uniform.box(
  lower,
  upper,
  order = c("draw", "ascending.first.coordinate"),
  algorithm = "column.major.runif.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.uniform.box(lower = c(-1, 0), upper = c(1, 2))
synthetic.sampling.uniform.disk — detailed help

Title

Uniform-disk sampling specification

Name

synthetic.sampling.uniform.disk

Description

Uniform-disk sampling specification

Usage

synthetic.sampling.uniform.disk(radius = 1, algorithm = "radial.sqrt.v1")

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.uniform.disk(radius = 2)
synthetic.sampling.uniform.interval — detailed help

Title

Uniform-interval sampling specification

Name

synthetic.sampling.uniform.interval

Description

Uniform-interval sampling specification

Usage

synthetic.sampling.uniform.interval(
  lower,
  upper,
  order = c("draw", "ascending"),
  algorithm = "runif.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.uniform.interval(0, 1, order = "ascending")
synthetic.sampling.uniform.rectangle — detailed help

Title

Uniform-rectangle sampling specification

Name

synthetic.sampling.uniform.rectangle

Description

Uniform-rectangle sampling specification

Usage

synthetic.sampling.uniform.rectangle(
  lower,
  upper,
  algorithm = "coordinate.sequential.runif.v1"
)

Arguments

Value

A synthetic sampling component.

Examples

synthetic.sampling.uniform.rectangle(c(-1, -2), c(1, 2))
synthetic.simplex — detailed help

Title

Specify a simplex geometry

Name

synthetic.simplex

Description

Specify a simplex geometry

Usage

synthetic.simplex(parts)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.simplex(parts = 3L)
synthetic.sphere.cap — detailed help

Title

Specify a sphere-cap geometry

Name

synthetic.sphere.cap

Description

Specify a sphere-cap geometry

Usage

synthetic.sphere.cap(
  radius = 2,
  footprint.radius = 1,
  ambient.dim = 3L,
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.sphere.cap(radius = 2, footprint.radius = 1)
synthetic.stratified — detailed help

Title

Assemble a stratified geometry

Name

synthetic.stratified

Description

Assemble a stratified geometry

Usage

synthetic.stratified(strata, junctions = NULL)

Arguments

Value

A draw-free synthetic geometry component.

Examples

point <- synthetic.stratum.point("point", c(0, 0))
line <- synthetic.stratum.segment("line", c(0, 1), c(0, 0), c(1, 0))
synthetic.stratified(list(point, line))
synthetic.stratum.point — detailed help

Title

Specify a point stratum

Name

synthetic.stratum.point

Description

Specify a point stratum

Usage

synthetic.stratum.point(id, location)

Arguments

Value

A draw-free synthetic_stratum.

Examples

synthetic.stratum.point("origin", c(0, 0))
synthetic.stratum.rectangle — detailed help

Title

Specify a rectangle stratum

Name

synthetic.stratum.rectangle

Description

Specify a rectangle stratum

Usage

synthetic.stratum.rectangle(id, coordinate.ranges, origin, basis)

Arguments

Value

A draw-free synthetic_stratum.

Examples

synthetic.stratum.rectangle(
  "square", rbind(c(-1, 1), c(-1, 1)), c(0, 0), diag(2)
)
synthetic.stratum.segment — detailed help

Title

Specify a line-segment stratum

Name

synthetic.stratum.segment

Description

Specify a line-segment stratum

Usage

synthetic.stratum.segment(id, coordinate.range, origin, direction)

Arguments

Value

A draw-free synthetic_stratum.

Examples

synthetic.stratum.segment("line", c(-1, 1), c(0, 0), c(1, 0))
synthetic.torus.patch — detailed help

Title

Specify a torus-patch geometry

Name

synthetic.torus.patch

Description

Specify a torus-patch geometry

Usage

synthetic.torus.patch(
  major.radius = 1,
  minor.radius = 0.35,
  u.range = c(-pi/2, pi/2),
  v.range = c(-pi/2, pi/2),
  ambient.dim = 3L,
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.torus.patch(major.radius = 2, minor.radius = 0.5)
synthetic.trefoil — detailed help

Title

Specify a trefoil-knot geometry

Name

synthetic.trefoil

Description

This preserves the legacy gflow parameterization: x = scale * sin(t) + 2 * sin(2t), y = scale cos(t) - 2 * cos(2t), and z = -scale sin(3*t).

Usage

synthetic.trefoil(
  scale = 1,
  t.range = c(0, 2 * pi),
  ambient.dim = 3L,
  frame = c("canonical", "random.orthonormal", "supplied"),
  frame.algorithm = NULL,
  frame.matrix = NULL,
  offset = NULL
)

Arguments

Value

A synthetic geometry component.

Examples

synthetic.trefoil(scale = 0.5, t.range = c(0, pi))
validate.maximal.packing — detailed help

Title

Validate a Maximal Packing

Name

validate.maximal.packing

Description

Validates whether a given vertex packing is maximal and correctly satisfies the distance constraints. A packing is valid if all vertices are separated by at least the specified radius, and is maximal if no additional vertices can be added without violating this constraint.

Usage

validate.maximal.packing(
  adj.list,
  length.list,
  packing.vertices,
  max.packing.radius
)

Arguments

Details

This function performs two key validations:

  1. Packing Property: Verifies that all vertices in the packing are separated by at least max.packing.radius.

  2. Maximality: Verifies that no additional vertex can be added to the packing without violating the packing property.

The function uses the igraph package to compute shortest path distances between vertices using Dijkstra’s algorithm.

Value

A list with class "packing_validation" containing validation results:

Examples

adj.list <- list(c(2), c(1, 3), c(2, 4), c(3, 5), c(4))
length.list <- list(c(1), c(1, 1), c(1, 1), c(1, 1), c(1))
packing <- c(1, 3, 5)
radius <- 2

result <- validate.maximal.packing(adj.list, length.list, packing, radius)
result$valid
result$is.maximal
validate.synthetic.geometry — detailed help

Title

Validate a geometry specification or its latent coordinates

Name

validate.synthetic.geometry

Description

Validate a geometry specification or its latent coordinates

Usage

validate.synthetic.geometry(geometry, latent = NULL)

Arguments

Value

With no latent input, the unchanged geometry invisibly. Otherwise, the validated latent coordinates as a double matrix.

Examples

validate.synthetic.geometry(synthetic.circle(), matrix(c(0, pi), ncol = 1))
validate.synthetic.sampling — detailed help

Title

Validate a point-sampling specification and geometric support

Name

validate.synthetic.sampling

Description

Validate a point-sampling specification and geometric support

Usage

validate.synthetic.sampling(sampling, geometry = NULL)

Arguments

Value

The unchanged sampling specification, invisibly.

Examples

validate.synthetic.sampling(synthetic.sampling.uniform.disk(0.5),
  synthetic.sphere.cap())
verify.maximal.packing — detailed help

Title

Verify Maximal Packing Created by create.maximal.packing

Name

verify.maximal.packing

Description

A convenience function to verify the correctness of a maximal packing created using the create.maximal.packing function. This function validates both the packing property (minimum separation distance) and maximality (no vertices can be added).

Usage

verify.maximal.packing(packing.result, verbose = TRUE)

Arguments

Details

This function takes the output of create.maximal.packing and verifies two key properties:

  1. The packing vertices are all separated by at least max_packing_radius

  2. The packing is maximal (no more vertices can be added without violating the distance constraint)

When \code{verbose = TRUE}, the function prints:
\itemize{
  \item Graph diameter
  \item Packing radius used
  \item Number of vertices in the packing
  \item Minimum distance between packing vertices
  \item Maximum coverage distance
  \item Validity and maximality status
  \item Any violations or potential additions (if applicable)
}

Value

A logical value: TRUE if the packing is both valid (satisfies the distance constraint) and maximal (no vertices can be added), FALSE otherwise.

See Also

create.maximal.packing, validate.maximal.packing

Examples

adj.list <- list(c(2), c(1, 3), c(2, 4), c(3, 5), c(4))
length.list <- list(c(1), c(1, 1), c(1, 1), c(1, 1), c(1))
result <- create.maximal.packing(adj.list, length.list, grid.size = 2)

verify.maximal.packing(result, verbose = FALSE)
vertices — detailed help

Title

Extract Vertices from a Graph Result

Name

vertices

Description

Extract Vertices from a Graph Result

Usage

vertices(object, ...)

Arguments

Value

Object-specific vertex indices.

Examples

chain <- create.graph("chain", n = 5)
extrema <- detect.local.extrema(graph.adjacency(chain), graph.lengths(chain), y = c(1, 3, 1, 2,
    0), max.radius = 1, min.neighborhood.size = 2)
vertices(extrema, extrema$labels[[1]])
vertices.local_extrema — detailed help

Title

Extract a Local-Extremum Neighborhood

Name

vertices.local_extrema

Description

Extract a Local-Extremum Neighborhood

Usage

## S3 method for class 'local_extrema'
vertices(object, label, include.center = TRUE, ...)

Arguments

Value

An integer vector of one-based vertex indices in the selected extremum’s stored neighborhood, optionally excluding its center.

Examples

chain <- create.graph("chain", n = 5)
extrema <- detect.local.extrema(graph.adjacency(chain), graph.lengths(chain), y = c(1, 3, 1, 2,
    0), max.radius = 1, min.neighborhood.size = 2)
vertices(extrema, extrema$labels[[1]])
wgraph.prune.long.edges — detailed help

Title

Prune Long Edges in a Weighted Graph

Name

wgraph.prune.long.edges

Description

Prune Long Edges in a Weighted Graph

Usage

wgraph.prune.long.edges(
  adj.list,
  length.list,
  alt.path.len.ratio.thld,
  use.total.length.constraint = TRUE,
  verbose = FALSE
)

Arguments

Value

A dgraph object. Use graph.adjacency(), graph.lengths(), graph.edges() and graph.stages() to inspect its stored graph stages. Construction and diagnostic information is stored in metadata.

Examples

graph <- list(c(2L, 3L), c(1L, 3L), c(1L, 2L))
lengths <- list(c(1, 2), c(1, 1), c(2, 1))
graph.adjacency(wgraph.prune.long.edges(graph, lengths, alt.path.len.ratio.thld = 1.1))