petgraph::graphmap

Struct GraphMap

Source
pub struct GraphMap<N, E, Ty, S = RandomState>
where S: BuildHasher,
{ /* private fields */ }
Expand description

GraphMap<N, E, Ty> is a graph datastructure using an associative array of its node weights N.

It uses an combined adjacency list and sparse adjacency matrix representation, using O(|V| + |E|) space, and allows testing for edge existence in constant time.

GraphMap is parameterized over:

  • Associated data N for nodes and E for edges, called weights.
  • The node weight N must implement Copy and will be used as node identifier, duplicated into several places in the data structure. It must be suitable as a hash table key (implementing Eq + Hash). The node type must also implement Ord so that the implementation can order the pair (a, b) for an edge connecting any two nodes a and b.
  • E can be of arbitrary type.
  • Edge type Ty that determines whether the graph edges are directed or undirected.

You can use the type aliases UnGraphMap and DiGraphMap for convenience.

GraphMap does not allow parallel edges, but self loops are allowed.

Depends on crate feature graphmap (default).

Implementations§

Source§

impl<N, E, Ty, S> GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source

pub fn new() -> Self
where S: Default,

Create a new GraphMap

Source

pub fn with_capacity(nodes: usize, edges: usize) -> Self
where S: Default,

Create a new GraphMap with estimated capacity.

Source

pub fn with_capacity_and_hasher(nodes: usize, edges: usize, hasher: S) -> Self
where S: Clone,

Create a new GraphMap with estimated capacity, and specified hasher.

Source

pub fn capacity(&self) -> (usize, usize)

Return the current node and edge capacity of the graph.

Source

pub fn is_directed(&self) -> bool

Whether the graph has directed edges.

Source

pub fn from_edges<I>(iterable: I) -> Self
where I: IntoIterator, I::Item: IntoWeightedEdge<E, NodeId = N>, S: Default,

Create a new GraphMap from an iterable of edges.

Node values are taken directly from the list. Edge weights E may either be specified in the list, or they are filled with default values.

Nodes are inserted automatically to match the edges.

use petgraph::graphmap::UnGraphMap;

// Create a new undirected GraphMap.
// Use a type hint to have `()` be the edge weight type.
let gr = UnGraphMap::<_, ()>::from_edges(&[
    (0, 1), (0, 2), (0, 3),
    (1, 2), (1, 3),
    (2, 3),
]);
Source

pub fn node_count(&self) -> usize

Return the number of nodes in the graph.

Source

pub fn edge_count(&self) -> usize

Return the number of edges in the graph.

Source

pub fn clear(&mut self)

Remove all nodes and edges

Source

pub fn add_node(&mut self, n: N) -> N

Add node n to the graph.

Source

pub fn remove_node(&mut self, n: N) -> bool

Return true if node n was removed.

Computes in O(V) time, due to the removal of edges with other nodes.

Source

pub fn contains_node(&self, n: N) -> bool

Return true if the node is contained in the graph.

Source

pub fn add_edge(&mut self, a: N, b: N, weight: E) -> Option<E>

Add an edge connecting a and b to the graph, with associated data weight. For a directed graph, the edge is directed from a to b.

Inserts nodes a and/or b if they aren’t already part of the graph.

Return None if the edge did not previously exist, otherwise, the associated data is updated and the old value is returned as Some(old_weight).

// Create a GraphMap with directed edges, and add one edge to it
use petgraph::graphmap::DiGraphMap;

let mut g = DiGraphMap::new();
g.add_edge("x", "y", -1);
assert_eq!(g.node_count(), 2);
assert_eq!(g.edge_count(), 1);
assert!(g.contains_edge("x", "y"));
assert!(!g.contains_edge("y", "x"));
Source

pub fn remove_edge(&mut self, a: N, b: N) -> Option<E>

Remove edge from a to b from the graph and return the edge weight.

Return None if the edge didn’t exist.

// Create a GraphMap with undirected edges, and add and remove an edge.
use petgraph::graphmap::UnGraphMap;

let mut g = UnGraphMap::new();
g.add_edge("x", "y", -1);

let edge_data = g.remove_edge("y", "x");
assert_eq!(edge_data, Some(-1));
assert_eq!(g.edge_count(), 0);
Source

pub fn contains_edge(&self, a: N, b: N) -> bool

Return true if the edge connecting a with b is contained in the graph.

Source

pub fn nodes(&self) -> Nodes<'_, N>

Return an iterator over the nodes of the graph.

Iterator element type is N.

Source

pub fn neighbors(&self, a: N) -> Neighbors<'_, N, Ty>

Return an iterator of all nodes with an edge starting from a.

  • Directed: Outgoing edges from a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is N.

Source

pub fn neighbors_directed( &self, a: N, dir: Direction, ) -> NeighborsDirected<'_, N, Ty>

Return an iterator of all neighbors that have an edge between them and a, in the specified direction. If the graph’s edges are undirected, this is equivalent to .neighbors(a).

  • Directed, Outgoing: All edges from a.
  • Directed, Incoming: All edges to a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is N.

Source

pub fn edges(&self, a: N) -> Edges<'_, N, E, Ty, S>

Return an iterator of target nodes with an edge starting from a, paired with their respective edge weights.

  • Directed: Outgoing edges from a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is (N, N, &E).

Source

pub fn edges_directed( &self, a: N, dir: Direction, ) -> EdgesDirected<'_, N, E, Ty, S>

Return an iterator of target nodes with an edge starting from a, paired with their respective edge weights.

  • Directed, Outgoing: All edges from a.
  • Directed, Incoming: All edges to a.
  • Undirected, Outgoing: All edges connected to a, with a being the source of each edge.
  • Undirected, Incoming: All edges connected to a, with a being the target of each edge.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is (N, N, &E).

Source

pub fn edge_weight(&self, a: N, b: N) -> Option<&E>

Return a reference to the edge weight connecting a with b, or None if the edge does not exist in the graph.

Source

pub fn edge_weight_mut(&mut self, a: N, b: N) -> Option<&mut E>

Return a mutable reference to the edge weight connecting a with b, or None if the edge does not exist in the graph.

Source

pub fn all_edges(&self) -> AllEdges<'_, N, E, Ty>

Return an iterator over all edges of the graph with their weight in arbitrary order.

Iterator element type is (N, N, &E)

Source

pub fn all_edges_mut(&mut self) -> AllEdgesMut<'_, N, E, Ty>

Return an iterator over all edges of the graph in arbitrary order, with a mutable reference to their weight.

Iterator element type is (N, N, &mut E)

Source

pub fn into_graph<Ix>(self) -> Graph<N, E, Ty, Ix>
where Ix: IndexType,

Return a Graph that corresponds to this GraphMap.

  1. Note that node and edge indices in the Graph have nothing in common with the GraphMaps node weights N. The node weights N are used as node weights in the resulting Graph, too.
  2. Note that the index type is user-chosen.

Computes in O(|V| + |E|) time (average).

Panics if the number of nodes or edges does not fit with the resulting graph’s index type.

Source

pub fn from_graph<Ix>(graph: Graph<N, E, Ty, Ix>) -> Self
where Ix: IndexType, E: Clone, S: Default,

Creates a GraphMap that corresponds to the given Graph.

Warning: Nodes with the same weight are merged and only the last parallel edge is kept. Node and edge indices of the Graph are lost. Only use this function if the node weights are distinct and there are no parallel edges.

Computes in O(|V| + |E|) time (average).

Trait Implementations§

Source§

impl<N, E, Ty> Build for GraphMap<N, E, Ty>
where Ty: EdgeType, N: NodeTrait,

Source§

fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId

Source§

fn add_edge( &mut self, a: Self::NodeId, b: Self::NodeId, weight: Self::EdgeWeight, ) -> Option<Self::EdgeId>

Add a new edge. If parallel edges (duplicate) are not allowed and the edge already exists, return None.
Source§

fn update_edge( &mut self, a: Self::NodeId, b: Self::NodeId, weight: Self::EdgeWeight, ) -> Self::EdgeId

Add or update the edge from a to b. Return the id of the affected edge.
Source§

impl<N: Clone, E: Clone, Ty: Clone, S> Clone for GraphMap<N, E, Ty, S>
where S: BuildHasher + Clone,

Source§

fn clone(&self) -> GraphMap<N, E, Ty, S>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<N, E, Ty> Create for GraphMap<N, E, Ty>
where Ty: EdgeType, N: NodeTrait,

Source§

fn with_capacity(nodes: usize, edges: usize) -> Self

Source§

impl<N, E, Ty, S> Data for GraphMap<N, E, Ty, S>
where N: Copy + PartialEq, Ty: EdgeType, S: BuildHasher,

Source§

impl<N: Eq + Hash + Debug, E: Debug, Ty: EdgeType, S: BuildHasher> Debug for GraphMap<N, E, Ty, S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<N, E, Ty, S> Default for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher + Default,

Create a new empty GraphMap.

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<N, E, Ty, S> EdgeCount for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

fn edge_count(&self) -> usize

Return the number of edges in the graph.
Source§

impl<N, E, Ty, S> EdgeIndexable for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

fn edge_bound(&self) -> usize

Return an upper bound of the edge indices in the graph (suitable for the size of a bitmap).
Source§

fn to_index(&self, ix: Self::EdgeId) -> usize

Convert a to an integer index.
Source§

fn from_index(&self, ix: usize) -> Self::EdgeId

Convert i to an edge index. i must be a valid value in the graph.
Source§

impl<N, E, Ty, Item, S> Extend<Item> for GraphMap<N, E, Ty, S>
where Item: IntoWeightedEdge<E, NodeId = N>, N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Extend the graph from an iterable of edges.

Nodes are inserted automatically to match the edges.

Source§

fn extend<I>(&mut self, iterable: I)
where I: IntoIterator<Item = Item>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<N, E, Ty> FromElements for GraphMap<N, E, Ty>
where Ty: EdgeType, N: NodeTrait,

Source§

fn from_elements<I>(iterable: I) -> Self
where Self: Sized, I: IntoIterator<Item = Element<Self::NodeWeight, Self::EdgeWeight>>,

Source§

impl<N, E, Ty, Item, S> FromIterator<Item> for GraphMap<N, E, Ty, S>
where Item: IntoWeightedEdge<E, NodeId = N>, N: NodeTrait, Ty: EdgeType, S: BuildHasher + Default,

Create a new GraphMap from an iterable of edges.

Source§

fn from_iter<I>(iterable: I) -> Self
where I: IntoIterator<Item = Item>,

Creates a value from an iterator. Read more
Source§

impl<N, E, Ty, S> GetAdjacencyMatrix for GraphMap<N, E, Ty, S>
where N: Copy + Ord + Hash, Ty: EdgeType, S: BuildHasher,

The GraphMap keeps an adjacency matrix internally.

Source§

type AdjMatrix = ()

The associated adjacency matrix type
Source§

fn adjacency_matrix(&self)

Create the adjacency matrix
Source§

fn is_adjacent(&self, _: &(), a: N, b: N) -> bool

Return true if there is an edge from a to b, false otherwise. Read more
Source§

impl<N, E, Ty, S> GraphBase for GraphMap<N, E, Ty, S>
where N: Copy + PartialEq, S: BuildHasher,

Source§

type NodeId = N

node identifier
Source§

type EdgeId = (N, N)

edge identifier
Source§

impl<N, E, Ty, S> GraphProp for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

type EdgeType = Ty

The kind of edges in the graph.
Source§

fn is_directed(&self) -> bool

Source§

impl<N, E, Ty, S> Index<(N, N)> for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Index GraphMap by node pairs to access edge weights.

Source§

type Output = E

The returned type after indexing.
Source§

fn index(&self, index: (N, N)) -> &E

Performs the indexing (container[index]) operation. Read more
Source§

impl<N, E, Ty, S> IndexMut<(N, N)> for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Index GraphMap by node pairs to access edge weights.

Source§

fn index_mut(&mut self, index: (N, N)) -> &mut E

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a, N, E: 'a, Ty, S> IntoEdgeReferences for &'a GraphMap<N, E, Ty, S>
where N: NodeTrait + 'a, Ty: EdgeType, S: BuildHasher,

Source§

impl<'a, N, E: 'a, Ty, S> IntoEdges for &'a GraphMap<N, E, Ty, S>
where N: NodeTrait + 'a, Ty: EdgeType, S: BuildHasher,

Source§

type Edges = Edges<'a, N, E, Ty, S>

Source§

fn edges(self, a: Self::NodeId) -> Self::Edges

Source§

impl<'a, N, E: 'a, Ty, S> IntoEdgesDirected for &'a GraphMap<N, E, Ty, S>
where N: NodeTrait + 'a, Ty: EdgeType, S: BuildHasher,

Source§

type EdgesDirected = EdgesDirected<'a, N, E, Ty, S>

Source§

fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected

Source§

impl<'a, N, E, Ty, S> IntoNeighbors for &'a GraphMap<N, E, Ty, S>
where N: Copy + Ord + Hash + 'a, Ty: EdgeType, S: BuildHasher,

Source§

type Neighbors = Neighbors<'a, N, Ty>

Source§

fn neighbors(self, n: Self::NodeId) -> Self::Neighbors

Return an iterator of the neighbors of node a.
Source§

impl<'a, N, E, Ty, S> IntoNeighborsDirected for &'a GraphMap<N, E, Ty, S>
where N: Copy + Ord + Hash + 'a, Ty: EdgeType, S: BuildHasher,

Source§

impl<'a, N, E: 'a, Ty, S> IntoNodeIdentifiers for &'a GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

impl<'a, N, E, Ty, S> IntoNodeReferences for &'a GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

impl<N, E, Ty, S> NodeCount for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

impl<N, E, Ty, S> NodeIndexable for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Source§

fn node_bound(&self) -> usize

Return an upper bound of the node indices in the graph (suitable for the size of a bitmap).
Source§

fn to_index(&self, ix: Self::NodeId) -> usize

Convert a to an integer index.
Source§

fn from_index(&self, ix: usize) -> Self::NodeId

Convert i to a node index. i must be a valid value in the graph.
Source§

impl<N, E, Ty, S> Visitable for GraphMap<N, E, Ty, S>
where N: Copy + Ord + Hash, Ty: EdgeType, S: BuildHasher,

Source§

type Map = HashSet<N>

The associated map type
Source§

fn visit_map(&self) -> HashSet<N>

Create a new visitor map
Source§

fn reset_map(&self, map: &mut Self::Map)

Reset the visitor map (and resize to new size of graph if needed)
Source§

impl<N, E, Ty, S> NodeCompactIndexable for GraphMap<N, E, Ty, S>
where N: NodeTrait, Ty: EdgeType, S: BuildHasher,

Auto Trait Implementations§

§

impl<N, E, Ty, S> Freeze for GraphMap<N, E, Ty, S>
where S: Freeze,

§

impl<N, E, Ty, S> RefUnwindSafe for GraphMap<N, E, Ty, S>

§

impl<N, E, Ty, S> Send for GraphMap<N, E, Ty, S>
where S: Send, Ty: Send, N: Send, E: Send,

§

impl<N, E, Ty, S> Sync for GraphMap<N, E, Ty, S>
where S: Sync, Ty: Sync, N: Sync, E: Sync,

§

impl<N, E, Ty, S> Unpin for GraphMap<N, E, Ty, S>
where S: Unpin, Ty: Unpin, N: Unpin, E: Unpin,

§

impl<N, E, Ty, S> UnwindSafe for GraphMap<N, E, Ty, S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.