graphrs

Struct Graph

Source
pub struct Graph<T: PartialOrd + Send + Sync, A: Clone> {
    pub specs: GraphSpecs,
    /* private fields */
}
Expand description

The Graph struct represents a graph of nodes and vertices. It allows graphs to be created with support for:

  • directed and undirected edges
  • multiple edges between two nodes
  • self-loops

A Graph has two generic arguments:

  • T: Specifies the type to use for node names.
  • A: Specifies the type to use for node and edge attributes. Attributes are optional extra data that are associated with a node or an edge. For example, if nodes represent people and T is an i32 of their employee ID then the node attributes might store their first and last names.

§Example

use graphrs::{Edge, Graph, GraphSpecs, Node};

let nodes = vec![
    Node::from_name("n1"),
    Node::from_name("n2"),
    Node::from_name("n3"),
];

let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n2", "n1", 2.0),
    Edge::with_weight("n1", "n3", 3.0),
    Edge::with_weight("n2", "n3", 3.0),
];

let specs = GraphSpecs::directed();

let graph = Graph::<&str, ()>::new_from_nodes_and_edges(
    nodes,
    edges,
    specs
);

Fields§

§specs: GraphSpecs

The GraphSpecs for the graph.

Implementations§

Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn reverse(&self) -> Result<Graph<T, A>, Error>

Reverses the edges in a directed graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n3"),
    Edge::new("n2", "n3"),
]);
let graph = graph.reverse().unwrap();
assert!(graph.get_edge("n3", "n1").is_ok());
Source

pub fn set_all_edge_weights(&self, weight: f64) -> Graph<T, A>

Return a new graph with all the edge weights set to the specified value.

§Arguments
  • weight: the value to set all the edge weights to
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n3"),
    Edge::new("n2", "n3"),
]);
let new_graph = graph.set_all_edge_weights(2.0);
assert_eq!(new_graph.get_edge("n1", "n3").unwrap().weight, 2.0);
Source

pub fn to_single_edges(&self) -> Result<Graph<T, A>, Error>

Convert a multi-edge graph to a single-edge graph.

Edge weights are summed.

Edge attributes are lost.

§Examples
use graphrs::{Edge, Graph, GraphSpecs, MissingNodeStrategy, Node};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs {
    missing_node_strategy: MissingNodeStrategy::Create,
    multi_edges: true,
    ..GraphSpecs::directed()
});
graph.add_edges(vec![
    Edge::with_weight("n1", "n2", 1.1),
    Edge::with_weight("n1", "n2", 2.2),
    Edge::with_weight("n1", "n2", 3.3),
    Edge::with_weight("n1", "n3", 4.4),
]);
let new_graph = graph.to_single_edges().unwrap();
assert!(!new_graph.specs.multi_edges);
assert_eq!(new_graph.get_all_edges().len(), 2);
assert_eq!(new_graph.get_edge("n1", "n2").unwrap().weight, 6.6);
assert_eq!(new_graph.get_edge("n1", "n3").unwrap().weight, 4.4);
Source

pub fn to_undirected( &self, collapse_edge_weights_strategy: Option<ToUndirectedCollapseEdgeWeightsStrategy>, ) -> Result<Graph<T, A>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Converts a directed graph to an undirected graph.

§Examples
use graphrs::{generators};
let graph = generators::random::fast_gnp_random_graph(25, 0.25, true, Some(1)).unwrap();
let new_graph = graph.to_undirected(None).unwrap();
assert_eq!(new_graph.number_of_nodes(), 25);
assert_eq!(new_graph.number_of_edges(), 132);
Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn add_edge(&mut self, edge: Arc<Edge<T, A>>) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display, A: Clone,

Adds an edge to the Graph.

If the new edge references nodes that don’t exist the graph’s specs.missing_node_strategy determines what happens.

use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edge(Edge::new("n1", "n2"));
assert!(result.is_ok());
Source

pub fn add_edge_tuple(&mut self, u: T, v: T) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display,

Adds an edge, as a (u, v) tuple, to the Graph.

If the new edge references nodes that don’t exist the graph’s specs.missing_node_strategy determines what happens.

use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edge_tuple("n1", "n2");
assert!(result.is_ok());
Source

pub fn add_edges(&mut self, edges: Vec<Arc<Edge<T, A>>>) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display, A: Clone,

Adds new edges to a Graph, or updates existing edges, or both.

If the new edges reference nodes that don’t exist the graph’s specs.missing_node_strategy determines what happens.

§Arguments
  • edges: the new edges to add to the graph
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n3"),
]);
assert!(result.is_ok());
Source

pub fn add_edge_tuples(&mut self, edges: Vec<(T, T)>) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display, A: Clone,

Adds new edges to a Graph, or updates existing edges, or both.

If the new edges reference nodes that don’t exist the graph’s specs.missing_node_strategy determines what happens.

§Arguments
  • edges: the new edges to add to the graph
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edge_tuples(vec![
    ("n1", "n2"),
    ("n2", "n3"),
]);
assert!(result.is_ok());
Source

pub fn add_edge_tuples_weighted( &mut self, edges: Vec<(T, T, f64)>, ) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display, A: Clone,

Adds new edges to a Graph, or updates existing edges, or both.

If the new edges reference nodes that don’t exist the graph’s specs.missing_node_strategy determines what happens.

§Arguments
  • edges: the new edges to add to the graph
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edge_tuples_weighted(vec![
    ("n1", "n2", 1.0),
    ("n2", "n3", 2.6),
]);
assert!(result.is_ok());
Source

pub fn add_node(&mut self, node: Arc<Node<T, A>>)
where T: Hash + Eq + Clone + Ord, A: Clone,

Adds a node to the graph or updates the node’s attributes if the node already exists.

§Arguments

node: the new node to add to the graph

use graphrs::{Node, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::multi_directed());
graph.add_node(Node::from_name("n1"));
Source

pub fn add_nodes(&mut self, nodes: Vec<Arc<Node<T, A>>>)
where T: Hash + Eq + Clone + Ord, A: Clone,

Adds a nodes to the graph or updates the nodes’ attributes if they already exist.

§Arguments

nodes: the new nodes to add to the graph

use graphrs::{Node, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::multi_directed());
graph.add_nodes(vec![
    Node::from_name("n1"),
    Node::from_name("n2"),
]);
Source

pub fn new(specs: GraphSpecs) -> Graph<T, A>

Creates an empty graph, according to the specs.

§Arguments
  • specs: An instance of GraphSpecs that determines the characteristics and constraints of the graph.
§Examples
use graphrs::{Graph, GraphSpecs};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
Source

pub fn new_from_nodes_and_edges( nodes: Vec<Arc<Node<T, A>>>, edges: Vec<Arc<Edge<T, A>>>, specs: GraphSpecs, ) -> Result<Graph<T, A>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Create a new Graph from the specified nodes and edges.

§Arguments
  • nodes: The Node objects to add to the graph.
  • edge: The Edge objects to add to the graph.
  • specs: An instance of GraphSpecs that determines the characteristics and constraints of the graph.
§Examples
use graphrs::{Edge, Graph, GraphSpecs, Node};

let nodes = vec![
    Node::from_name("n1"),
    Node::from_name("n2"),
    Node::from_name("n3"),
];

let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n2", "n1", 2.0),
    Edge::with_weight("n1", "n3", 3.0),
    Edge::with_weight("n2", "n3", 3.0),
];

let specs = GraphSpecs::directed();

let graph = Graph::<&str, ()>::new_from_nodes_and_edges(
    nodes,
    edges,
    specs
);
Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn get_degree_for_all_nodes(&self) -> HashMap<T, usize>

Compute the degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::new("n1", "n2"),
    Edge::new("n1", "n3"),
    Edge::new("n1", "n4"),
    Edge::new("n4", "n5"),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_degree_for_all_nodes();
assert_eq!(result.get("n1").unwrap(), &3);
Source

pub fn get_in_degree_for_all_nodes(&self) -> Result<HashMap<T, usize>, Error>

Compute the in-degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::new("n1", "n2"),
    Edge::new("n1", "n3"),
    Edge::new("n1", "n5"),
    Edge::new("n4", "n5"),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_in_degree_for_all_nodes().unwrap();
assert_eq!(result.get("n5").unwrap(), &2);
Source

pub fn get_out_degree_for_all_nodes(&self) -> Result<HashMap<T, usize>, Error>

Compute the out-degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::new("n1", "n2"),
    Edge::new("n1", "n3"),
    Edge::new("n1", "n5"),
    Edge::new("n4", "n5"),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_out_degree_for_all_nodes().unwrap();
assert_eq!(result.get("n1").unwrap(), &3);
Source

pub fn get_node_degree(&self, node_name: T) -> Option<usize>

Computes the degree of a given node. The node degree is the number of edges adjacent to the node.

§Arguments
  • node_name: the name of the node to get the degree of
§Examples
use graphrs::{generators};
let graph = generators::social::karate_club_graph();
assert_eq!(graph.get_node_degree(25).unwrap(), 3);
Source

pub fn get_node_in_degree(&self, node_name: T) -> Option<usize>

Computes the in-degree of a given node. The node in-degree is the number of edges (u, v) where v is the node.

§Arguments
  • node_name: the name of the node to get the in-degree of
§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::new("n2", "n1"),
    Edge::new("n3", "n1"),
    Edge::new("n4", "n1"),
    Edge::new("n1", "n4"),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
assert_eq!(graph.get_node_in_degree("n1").unwrap(), 3);
Source

pub fn get_node_out_degree(&self, node_name: T) -> Option<usize>

Computes the out-degree of a given node. The node out-degree is the number of edges (u, v) where u is the node.

§Arguments
  • node_name: the name of the node to get the out-degree of
§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::new("n1", "n2"),
    Edge::new("n3", "n1"),
    Edge::new("n4", "n1"),
    Edge::new("n1", "n4"),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
assert_eq!(graph.get_node_out_degree("n1").unwrap(), 2);
Source

pub fn get_node_weighted_degree(&self, node_name: T) -> Option<f64>

Computes the weighted degree of a given node. The weighted degree is sum of the weights of edges adjacent to the node.

§Arguments
  • node_name: the name of the node to get the weighted degree of
§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n2", "n1", 1.0),
    Edge::with_weight("n3", "n1", 2.0),
    Edge::with_weight("n4", "n1", 3.0),
    Edge::with_weight("n1", "n4", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
assert_eq!(graph.get_node_weighted_degree("n1").unwrap(), 10.0);
Source

pub fn get_node_weighted_in_degree(&self, node_name: T) -> Option<f64>

Computes the weighted in-degree of a given node. The weighted in-degree is sum of the weights of edges into to the node.

§Arguments
  • node_name: the name of the node to get the weighted in-degree of
§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n2", "n1", 1.0),
    Edge::with_weight("n3", "n1", 2.0),
    Edge::with_weight("n4", "n1", 3.0),
    Edge::with_weight("n1", "n4", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
assert_eq!(graph.get_node_weighted_in_degree("n1").unwrap(), 6.0);
Source

pub fn get_node_weighted_out_degree(&self, node_name: T) -> Option<f64>

Computes the weighted out-degree of a given node. The weighted out-degree is sum of the weights of edges coming from the node.

§Arguments
  • node_name: the name of the node to get the weighted out-degree of
§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n3", "n1", 2.0),
    Edge::with_weight("n4", "n1", 3.0),
    Edge::with_weight("n1", "n4", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
assert_eq!(graph.get_node_weighted_out_degree("n1").unwrap(), 5.0);
Source

pub fn get_weighted_degree_for_all_nodes(&self) -> HashMap<T, f64>

Compute the weighted degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n1", "n3", 2.0),
    Edge::with_weight("n1", "n4", 3.0),
    Edge::with_weight("n4", "n5", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_weighted_degree_for_all_nodes();
assert_eq!(result.get("n1").unwrap(), &6.0);
Source

pub fn get_weighted_in_degree_for_all_nodes( &self, ) -> Result<HashMap<T, f64>, Error>

Compute the weighted in-degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n1", "n3", 2.0),
    Edge::with_weight("n1", "n5", 3.0),
    Edge::with_weight("n4", "n5", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_weighted_in_degree_for_all_nodes().unwrap();
assert_eq!(result.get("n5").unwrap(), &7.0);
Source

pub fn get_weighted_out_degree_for_all_nodes( &self, ) -> Result<HashMap<T, f64>, Error>

Compute the weighted out-degree for all nodes in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};
let edges = vec![
    Edge::with_weight("n1", "n2", 1.0),
    Edge::with_weight("n1", "n3", 2.0),
    Edge::with_weight("n1", "n5", 3.0),
    Edge::with_weight("n4", "n5", 4.0),
];
let graph: Graph<&str, ()> =
    Graph::new_from_nodes_and_edges(vec![], edges, GraphSpecs::directed_create_missing())
        .unwrap();
let result = graph.get_weighted_out_degree_for_all_nodes().unwrap();
assert_eq!(result.get("n1").unwrap(), &6.0);
Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn get_density(&self) -> f64

Returns the density of a graph.

§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
assert_eq!(graph.get_density(), 0.13903743315508021);
Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn ensure_directed(&self) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone + Send + Sync,

Returns an Err if the graph is not a directed graph.

Source

pub fn ensure_undirected(&self) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone + Send + Sync,

Returns an Err if the graph is a directed graph.

Source

pub fn ensure_not_multi_edges(&self) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone + Send + Sync,

Returns an Err if the graph is not a directed graph.

Source

pub fn ensure_weighted(&self) -> Result<(), Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns an Err if the any of the graph’s edges do not have a weight.

Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn get_adjacency_matrix_vec( &self, weighted: bool, ) -> Result<Vec<f64>, Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Gets the (adjacency matrix)[https://en.wikipedia.org/wiki/Adjacency_matrix] of the graph as a 1D vector (Vec).

This is an optional feature for crate. Enable in Cargo.toml with: graphrs = { version = "x.y.z", features = ["adjacency_matrix"] }

§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let matrix = graph.get_adjacency_matrix_vec(true).unwrap();
Source

pub fn get_adjacency_matrix_vec_vec( &self, weighted: bool, ) -> Result<Vec<Vec<f64>>, Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Gets the (adjacency matrix)[https://en.wikipedia.org/wiki/Adjacency_matrix] of the graph as a 2D vector (Vec<Vec>).

This is an optional feature for crate. Enable in Cargo.toml with: graphrs = { version = "x.y.z", features = ["adjacency_matrix"] }

§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let matrix = graph.get_adjacency_matrix_vec_vec(true).unwrap();
Source

pub fn get_adjacency_matrix_nalgebra( &self, weighted: bool, ) -> Result<DMatrix<f64>, Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Gets the (adjacency matrix)[https://en.wikipedia.org/wiki/Adjacency_matrix] of the graph as an nalgebra DMatrix<f64>.

This is an optional feature for crate. Enable in Cargo.toml with: graphrs = { version = "x.y.z", features = ["adjacency_matrix"] }

§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let matrix = graph.get_adjacency_matrix_nalgebra(true).unwrap();
Source

pub fn get_adjacency_matrix_ndarray( &self, weighted: bool, ) -> Result<Array2<f64>, Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Gets the (adjacency matrix)[https://en.wikipedia.org/wiki/Adjacency_matrix] of the graph as an ndarray Array2<f64>.

This is an optional feature for crate. Enable in Cargo.toml with: graphrs = { version = "x.y.z", features = ["adjacency_matrix"] }

§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let matrix = graph.get_adjacency_matrix_ndarray(true).unwrap();
Source

pub fn get_adjacency_matrix_sprs( &self, weighted: bool, ) -> Result<CsMat<f64>, Error>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Gets the (adjacency matrix)[https://en.wikipedia.org/wiki/Adjacency_matrix] of the graph.

For large graphs, the adjacency matrix can be very large so this method returns a sparse matrix using the “sprs” crate.false

use graphrs::generators;
let graph = generators::social::karate_club_graph();
let matrix = graph.get_adjacency_matrix_sprs(true).unwrap();
Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Performs a BFS of the graph, starting with a given node. Returns node names that the specified node_name connects to.

§Arguments
  • node_name: the starting point for the search
§Examples
use graphrs::{generators};
let graph = generators::social::karate_club_graph();
let result = graph.breadth_first_search(&0);
Source

pub fn edges_have_weight(&self) -> bool
where T: Hash + Eq + Clone + Ord, A: Clone,

Determines if all edges have a weight value.

§Returns

true if all edges have a weight value and the value isn’t NAN, false otherwise.

Source

pub fn get_all_edges(&self) -> Vec<&Arc<Edge<T, A>>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets a Vec of all the edges in the graph.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n3"),
]);
let all_edges = graph.get_all_edges();
assert_eq!(all_edges.len(), 2);
Source

pub fn get_all_nodes(&self) -> Vec<&Arc<Node<T, A>>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets a Vec of all the nodes in the graph.

§Examples
use graphrs::{Node, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::multi_undirected());
graph.add_nodes(vec![
    Node::from_name("n1"),
    Node::from_name("n2"),
]);
let all_nodes = graph.get_all_nodes();
assert_eq!(all_nodes.len(), 2);
Source

pub fn get_all_node_names(&self) -> Vec<&T>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets a Vec of all the nodes in the graph.

§Examples
use graphrs::{Node, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::multi_undirected());
graph.add_nodes(vec![
    Node::from_name("n1"),
    Node::from_name("n2"),
]);
let all_nodes = graph.get_all_node_names();
assert_eq!(all_nodes.len(), 2);
Source

pub fn get_edge(&self, u: T, v: T) -> Result<&Edge<T, A>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets the Edge between u and v nodes.

If specs.multi_edges is true then the get_edges method should be used instead.

§Arguments

u: The name of the first node of the edge. v: The name of the second node of the edge.

§Returns

If no edge exists between u and v, Err is returned.

§Examples
use graphrs::{generators};
let graph = generators::social::karate_club_graph();
let edge = graph.get_edge(0, 1);
assert!(edge.is_ok());
Source

pub fn get_edges(&self, u: T, v: T) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets the edges between u and v nodes.

If specs.multi_edges is false then the get_edge method should be used instead.

§Arguments

u: The name of the first node of the edge. v: The name of the second node of the edge.

§Returns

If no edge exists between u and v, Err is returned.

§Examples
use graphrs::{Edge, Graph, GraphSpecs, MissingNodeStrategy};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs {
    missing_node_strategy: MissingNodeStrategy::Create,
    ..GraphSpecs::multi_undirected()
});
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n1"),
]);
let edges = graph.get_edges("n1", "n2");
assert_eq!(edges.unwrap().len(), 2);
Source

pub fn get_edges_for_node( &self, name: T, ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges that connect to a specified node.

§Arguments
  • name: the node to get all adjacent edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::undirected_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n3", "n2"),
]);
let n2_edges = graph.get_edges_for_node("n2").unwrap();
assert_eq!(n2_edges.len(), 2);
Source

pub fn get_edges_for_nodes( &self, names: &[T], ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges that connect to any node in a Vec of nodes.

§Arguments
  • names: the nodes to get all edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::undirected_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n3"),
    Edge::new("n2", "n4"),
    Edge::new("n3", "n4"),
]);
let n2_edges = graph.get_edges_for_nodes(&["n1", "n2"]).unwrap();
assert_eq!(n2_edges.len(), 2);
Source

pub fn get_in_edges_for_node( &self, name: T, ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges (u, v) where v is name. Returns an Error if graph.specs.directed is false; use the get_edges_for_node for an undirected graph.

§Arguments
  • name: the node to get all in-edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n3", "n2"),
]);
let n2_in_edges = graph.get_in_edges_for_node("n2").unwrap();
assert_eq!(n2_in_edges.len(), 2);
Source

pub fn get_in_edges_for_nodes( &self, names: &[T], ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges that connect into to any node in a Vec of nodes.

§Arguments
  • names: the nodes to get all in-edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n1"),
    Edge::new("n2", "n3"),
]);
let n2_in_edges = graph.get_in_edges_for_nodes(&["n1", "n2"]).unwrap();
assert_eq!(n2_in_edges.len(), 2);
Source

pub fn get_out_edges_for_node( &self, name: T, ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges (u, v) where u is name. Returns an Error if graph.specs.directed is false; use the get_edges_for_node for an undirected graph.

§Arguments
  • name: the node to get all out-edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n2", "n1"),
    Edge::new("n2", "n3"),
]);
let n2_out_edges = graph.get_out_edges_for_node("n2").unwrap();
assert_eq!(n2_out_edges.len(), 2);
Source

pub fn get_out_edges_for_nodes( &self, names: &[T], ) -> Result<Vec<&Arc<Edge<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all edges that come out of any node in a Vec of nodes.

§Arguments
  • names: the nodes to get all out-edges for
§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n3"),
    Edge::new("n3", "n2"),
]);
let n1_out_edges = graph.get_out_edges_for_nodes(&["n2", "n3"]).unwrap();
assert_eq!(n1_out_edges.len(), 2);
Source

pub fn get_neighbor_nodes( &self, node_name: T, ) -> Result<Vec<&Arc<Node<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Returns all the nodes that connect to node_name.

§Arguments
  • node_name: The name of the node to find neighbors for.
§Returns

For an undirected graph adjacent nodes are returned. For a directed graph predecessor and successor nodes are returned.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n2", "n3"),
]);
assert!(result.is_ok());
let neighbors = graph.get_neighbor_nodes("n2");
assert_eq!(neighbors.unwrap().len(), 2);
Source

pub fn get_node(&self, name: T) -> Option<&Arc<Node<T, A>>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets the Node for the specified node name.

§Arguments
  • name: The name of the Node to return.
§Examples
use graphrs::{Node, Graph, GraphSpecs};

let mut graph: Graph<&str, i32> = Graph::new(GraphSpecs::directed());
graph.add_node(Node::from_name_and_attributes("n1", 99));
let node = graph.get_node("n1");
assert_eq!(node.unwrap().attributes.unwrap(), 99);
Source

pub fn get_predecessor_nodes( &self, node_name: T, ) -> Result<Vec<&Arc<Node<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets all u for (u, v) edges where node_name is v.

§Arguments
  • name: The name of the Node to return predecessors for.
§Returns

Returns an error if called on an undirected graph. Use get_neighbor_nodes for undirected graphs.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n3"),
    Edge::new("n2", "n3"),
]);
assert!(result.is_ok());
let predecessors = graph.get_predecessor_nodes("n3");
assert_eq!(predecessors.unwrap().len(), 2);
Source

pub fn get_predecessor_node_names(&self, node_name: T) -> Result<Vec<&T>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets all the names of u for (u, v) edges where node_name is v.

§Arguments
  • name: The name of the Node to return predecessors for.
§Returns

Returns an error if called on an undirected graph. Use get_neighbor_nodes for undirected graphs.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n3"),
    Edge::new("n2", "n3"),
]);
assert!(result.is_ok());
let predecessor_names = graph.get_predecessor_node_names("n3");
assert_eq!(predecessor_names.unwrap().len(), 2);
Source

pub fn get_predecessors_map(&self) -> &HashMap<T, HashSet<T>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets a HashMap of all the predecessor edges.

Source

pub fn get_successor_nodes( &self, node_name: T, ) -> Result<Vec<&Arc<Node<T, A>>>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets all v for (u, v) edges where node_name is u.

§Arguments
  • name: The name of the Node to return predecessors for.
§Returns

Returns an error if called on an undirected graph. Use get_neighbor_nodes for undirected graphs.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n1", "n3"),
]);
assert!(result.is_ok());
let successors = graph.get_successor_nodes("n1");
assert_eq!(successors.unwrap().len(), 2);
Source

pub fn get_successor_node_names(&self, node_name: T) -> Result<Vec<&T>, Error>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets all the names of v for (u, v) edges where node_name is u.

§Arguments
  • name: The name of the Node to return successors for.
§Returns

Returns an error if called on an undirected graph. Use get_neighbor_nodes for undirected graphs.

§Examples
use graphrs::{Edge, Graph, GraphSpecs};

let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
    Edge::new("n1", "n2"),
    Edge::new("n1", "n3"),
]);
assert!(result.is_ok());
let successor_names = graph.get_successor_node_names("n1");
assert_eq!(successor_names.unwrap().len(), 2);
Source

pub fn get_successors_map(&self) -> &HashMap<T, HashSet<T>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Gets a HashMap of all the successor edges.

Source

pub fn get_successors_or_neighbors(&self, node_name: T) -> Vec<&Arc<Node<T, A>>>
where T: Hash + Eq + Clone + Ord + Display + Send + Sync, A: Clone,

Returns successors of a node if the graph is directed.

Returns neighbors of a node if the graph is undirected.

Source

pub fn has_node(&self, node_name: &T) -> bool

Returns true if the graph contains a given node, false otherwise.

§Arguments
  • node_name: the name of the node to query for
§Examples
use graphrs::{Graph, GraphSpecs, Node};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
graph.add_node(Node::from_name("n1"));
assert!(graph.has_node(&"n1"));
Source

pub fn has_nodes(&self, node_names: &[T]) -> bool

Returns true if the graph contains all given nodes, false otherwise.

§Arguments
  • node_names: the names of the nodes to query for
§Examples
use graphrs::{Graph, GraphSpecs, Node};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
graph.add_node(Node::from_name("n1"));
assert!(!graph.has_nodes(&vec!["n1", "n2"]));
Source

pub fn number_of_nodes(&self) -> usize

Returns the number of nodes in the graph.

use graphrs::{generators};
let graph = generators::social::karate_club_graph();
assert_eq!(graph.number_of_nodes(), 34);
Source

pub fn number_of_edges(&self) -> usize

Returns the number of nodes in the graph.

use graphrs::{generators};
let graph = generators::social::karate_club_graph();
assert_eq!(graph.number_of_nodes(), 34);
Source

pub fn size(&self, weighted: bool) -> f64

Returns the number of edges or sum of all edge weights.

§Arguments
  • weighted: if true returns the sum of all edge weights, if false the number of edges
§Examples
use graphrs::{generators};
let graph = generators::social::karate_club_graph();
assert_eq!(graph.size(false), 78.0);
Source

pub fn get_node_by_index(&self, node_index: &usize) -> Option<&Arc<Node<T, A>>>
where T: Hash + Eq + Clone + Ord, A: Clone,

Source§

impl<T, A> Graph<T, A>
where T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display, A: Clone,

Source

pub fn get_ego_graph(&self, node: &T) -> Result<Graph<T, A>, Error>

Returns the 1st-degree ego network for a specific node.

§Arguments
  • node: The node to get the ego network for.
§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let subgraph = graph.get_ego_graph(&4).unwrap();
assert_eq!(subgraph.get_all_nodes().len(), 4);
Source

pub fn get_subgraph(&self, nodes: &[T]) -> Result<Graph<T, A>, Error>

Returns an induced subgraph that contains only the specified nodes and the edges between those nodes.

§Arguments
  • nodes: The nodes the subgraph must contain.
§Examples
use graphrs::generators;
let graph = generators::social::karate_club_graph();
let subgraph = graph.get_subgraph(&vec![4, 5, 6, 10, 16]).unwrap();
assert_eq!(subgraph.get_all_nodes().len(), 5);

Auto Trait Implementations§

§

impl<T, A> Freeze for Graph<T, A>

§

impl<T, A> RefUnwindSafe for Graph<T, A>

§

impl<T, A> Send for Graph<T, A>
where A: Sync + Send,

§

impl<T, A> Sync for Graph<T, A>
where A: Sync + Send,

§

impl<T, A> Unpin for Graph<T, A>
where T: Unpin,

§

impl<T, A> UnwindSafe for Graph<T, A>

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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize = _

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

unsafe fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V