Skip to main content

contract_vertices

Function contract_vertices 

Source
pub fn contract_vertices(
    graph: &Graph,
    mapping: &[VertexId],
) -> IgraphResult<Graph>
Expand description

Contracts vertices according to a grouping, merging edges.

Each vertex v is mapped to the group mapping[v]. All vertices in the same group are merged into a single vertex in the result graph. Edges are remapped accordingly — this typically produces self-loops (from in-group edges) and multi-edges (from multiple inter-group connections). Use crate::simplify afterwards to remove these if desired.

The number of vertices in the result equals max(mapping) + 1. To avoid orphan vertices (IDs with no corresponding input vertex), use consecutive integers starting from zero.

§Arguments

  • graph — the input graph.
  • mapping — slice of length vcount where mapping[old] = new_group.

§Errors

Returns InvalidArgument if mapping.len() != graph.vcount().

§Examples

use rust_igraph::{Graph, contract_vertices};

let mut g = Graph::with_vertices(4);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();

// Merge vertices 0+1 → group 0, vertices 2+3 → group 1
let mapping = [0, 0, 1, 1];
let cg = contract_vertices(&g, &mapping).unwrap();
assert_eq!(cg.vcount(), 2);
// Edge (0,1) → self-loop on 0, edge (1,2) → (0,1), edge (2,3) → self-loop on 1
assert_eq!(cg.ecount(), 3);