pub fn example_1() -> Result<RandomGraphStats>Expand description
Lesson 1: the diameter and mean degree of a random graph.
Seeds the calling thread’s default random number generator with 42 (as
the C program does, “to ensure identical results across runs”), generates
a simple undirected Erdős–Rényi G(n, m) graph with n = 1000 vertices
and m = 1000 edges, and computes its diameter (over all components, the
graph being disconnected) and its mean degree 2m / n = 2.
It translates examples/tutorial/tutorial1.c of the
first lesson,
and computes exactly the values printed by the C program with igraph
1.0.1: Diameter of a random graph with average degree 2: 23.
§C code
#include <igraph.h>
int main(void) {
igraph_int_t num_vertices = 1000;
igraph_int_t num_edges = 1000;
igraph_real_t diameter, mean_degree;
igraph_t graph;
/* Initialize the library. */
igraph_setup();
/* Ensure identical results across runs. */
igraph_rng_seed(igraph_rng_default(), 42);
igraph_erdos_renyi_game_gnm(
&graph, num_vertices, num_edges,
IGRAPH_UNDIRECTED, IGRAPH_SIMPLE_SW, IGRAPH_EDGE_UNLABELED);
igraph_diameter(
&graph, /* weights = */ NULL,
&diameter,
/* from = */ NULL, /* to = */ NULL,
/* vertex_path = */ NULL, /* edge_path = */ NULL,
IGRAPH_UNDIRECTED, /* unconn= */ true);
igraph_mean_degree(&graph, &mean_degree, IGRAPH_LOOPS);
printf("Diameter of a random graph with average degree %g: %g\n",
mean_degree, diameter);
igraph_destroy(&graph);
return 0;
}§Rust translation
The body of this function, step by step (no igraph_setup() and no
igraph_destroy() are needed):
use igraph::prelude::*;
let (num_vertices, num_edges) = (1000, 1000);
// Ensure identical results across runs.
rng::seed(42)?;
let graph = Graph::erdos_renyi_game_gnm(
num_vertices,
num_edges,
false, // undirected
EdgeTypeSw::Simple,
false, // unlabeled edges
)?;
let diameter = graph.diameter()?; // unweighted, over all components
let mean_degree = graph.mean_degree(true)?; // loops counted
println!("Diameter of a random graph with average degree {mean_degree}: {diameter}");
assert_eq!(diameter, 23.0);
assert_eq!(mean_degree, 2.0);
// ... which is what `example_1` returns.
let stats = igraph::tutorial::example_1()?;
assert_eq!((stats.diameter, stats.mean_degree), (diameter, mean_degree));
assert_eq!(
stats.to_string(),
"Diameter of a random graph with average degree 2: 23"
);§Errors
Propagates the errors of the igraph calls (none are expected).