1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Basic graph metrics — density and mean shortest-path length (ALGO-PR-003).
//!
//! Counterparts of:
//! - `igraph_density()` from `references/igraph/src/properties/basic_properties.c:71`
//! - `igraph_average_path_length()` from `references/igraph/src/paths/shortest_paths.c:329`
//!
//! Phase-1 minimal slice:
//! - **Density** matches upstream's default `loops = false` mode:
//! `m / (n*(n-1)/2)` for undirected, `m / (n*(n-1))` for directed.
//! Self-loops are not subtracted; if the graph has self-loops the
//! result may exceed 1 (this matches upstream — caller's responsibility).
//! - **Mean distance** matches upstream's `unconn = true` default —
//! unreachable pairs are skipped from the average. Returns `None`
//! when no connected pairs exist (graph too small or fully disconnected).
use crate::algorithms::paths::distances::distances;
use crate::core::{Graph, IgraphResult};
/// Edge density of `graph`. Counterpart of
/// `igraph_density(_, NULL_weights, _, /*loops=*/false)`.
///
/// Returns `None` when:
/// - `vcount() == 0` (matches upstream's `IGRAPH_NAN`).
/// - `vcount() == 1` and `loops=false` (no possible edges).
///
/// Self-loops in the input graph are *not* removed; they inflate the
/// numerator. Use `simplify` (when it lands) to drop them first.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, density};
///
/// // K3 (triangle) on 3 vertices, undirected: 3 edges, max = 3 → 1.0.
/// let mut g = Graph::with_vertices(3);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// g.add_edge(2, 0).unwrap();
/// assert_eq!(density(&g).unwrap(), Some(1.0));
/// ```
pub fn density(graph: &Graph) -> IgraphResult<Option<f64>> {
let n = graph.vcount();
if n == 0 || n == 1 {
return Ok(None);
}
let m = graph.ecount();
let directed = graph.is_directed();
// Sub-1 worst case for n: u32::try_from(n) is fine since n is u32 by type.
let n_f = f64::from(n);
#[allow(clippy::cast_precision_loss)]
let m_f = m as f64;
// Match upstream's float ordering exactly so f64 results agree to
// the bit. See `igraph_density()` in
// `references/igraph/src/properties/basic_properties.c:99-103`.
let result = if directed {
m_f / n_f / (n_f - 1.0)
} else {
m_f / n_f * 2.0 / (n_f - 1.0)
};
Ok(Some(result))
}
/// Mean unweighted shortest-path length over all reachable ordered pairs.
/// Counterpart of `igraph_average_path_length(_, NULL_weights, _, _, /*directed=*/true, /*unconn=*/true)`.
///
/// Returns `None` when no connected pairs exist (e.g. `vcount() < 2`,
/// or all pairs are unreachable). Edge directions matter for directed
/// graphs (uses `distances` which follows out-edges).
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, mean_distance};
///
/// // Path 0-1-2-3-4: ordered pairs at distance 1, 2, 3, 4 (4 each direction
/// // → 8, 6, 4, 2 contributions); 20 pairs total. Mean = 40/20 = 2.0.
/// let mut g = Graph::with_vertices(5);
/// for i in 0..4u32 { g.add_edge(i, i + 1).unwrap(); }
/// assert_eq!(mean_distance(&g).unwrap(), Some(2.0));
/// ```
pub fn mean_distance(graph: &Graph) -> IgraphResult<Option<f64>> {
let n = graph.vcount();
if n < 2 {
return Ok(None);
}
let mut sum: u64 = 0;
let mut count: u64 = 0;
for v in 0..n {
let d = distances(graph, v)?;
let v_us = v as usize;
for (target, &val) in d.iter().enumerate() {
if target == v_us {
continue;
}
if let Some(dist) = val {
sum += u64::from(dist);
count += 1;
}
}
}
if count == 0 {
return Ok(None);
}
#[allow(clippy::cast_precision_loss)]
let mean = (sum as f64) / (count as f64);
Ok(Some(mean))
}
/// Mean degree of the graph.
///
/// For directed graphs, returns `ecount / vcount` (the average out-degree,
/// which equals the average in-degree). For undirected graphs, returns
/// `2 * ecount / vcount`.
///
/// If `count_loops` is false, self-loop edges are excluded from the count.
///
/// Returns `None` for graphs with no vertices.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, mean_degree};
///
/// 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();
/// // 3 edges, 4 vertices, undirected → mean = 2*3/4 = 1.5
/// assert!((mean_degree(&g, true).unwrap().unwrap() - 1.5).abs() < 1e-10);
/// ```
pub fn mean_degree(graph: &Graph, count_loops: bool) -> IgraphResult<Option<f64>> {
let n = graph.vcount();
if n == 0 {
return Ok(None);
}
let mut ecount = graph.ecount();
if !count_loops {
let loop_count = crate::algorithms::properties::multiplicity::count_loops(graph)?;
ecount -= loop_count;
}
let directed = graph.is_directed();
let n_f = f64::from(n);
#[allow(clippy::cast_precision_loss)]
let m_f = ecount as f64;
let result = if directed { m_f / n_f } else { 2.0 * m_f / n_f };
Ok(Some(result))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn density_empty_graph_is_none() {
let g = Graph::with_vertices(0);
assert_eq!(density(&g).unwrap(), None);
}
#[test]
fn density_singleton_is_none() {
let g = Graph::with_vertices(1);
assert_eq!(density(&g).unwrap(), None);
}
#[test]
fn density_complete_undirected_is_one() {
let mut g = Graph::with_vertices(4);
for u in 0..4u32 {
for v in (u + 1)..4 {
g.add_edge(u, v).unwrap();
}
}
assert_eq!(density(&g).unwrap(), Some(1.0));
}
#[test]
fn density_no_edges_is_zero() {
let g = Graph::with_vertices(5);
assert_eq!(density(&g).unwrap(), Some(0.0));
}
#[test]
fn density_directed_complete_is_one() {
// Directed complete graph (no self-loops): n*(n-1) edges = max.
let mut g = Graph::new(3, true).unwrap();
for u in 0..3u32 {
for v in 0..3u32 {
if u != v {
g.add_edge(u, v).unwrap();
}
}
}
assert_eq!(density(&g).unwrap(), Some(1.0));
}
#[test]
fn density_path_5_is_2_over_10() {
// 4 edges among C(5,2)=10 possible → 0.4.
let mut g = Graph::with_vertices(5);
for i in 0..4 {
g.add_edge(i, i + 1).unwrap();
}
assert_eq!(density(&g).unwrap(), Some(0.4));
}
#[test]
fn mean_distance_n_lt_2_is_none() {
let g = Graph::with_vertices(0);
assert_eq!(mean_distance(&g).unwrap(), None);
let g = Graph::with_vertices(1);
assert_eq!(mean_distance(&g).unwrap(), None);
}
#[test]
fn mean_distance_isolated_vertices_is_none() {
let g = Graph::with_vertices(5);
assert_eq!(mean_distance(&g).unwrap(), None);
}
#[test]
fn mean_distance_path_5_is_2() {
let mut g = Graph::with_vertices(5);
for i in 0..4 {
g.add_edge(i, i + 1).unwrap();
}
assert_eq!(mean_distance(&g).unwrap(), Some(2.0));
}
#[test]
fn mean_distance_triangle_is_1() {
let mut g = Graph::with_vertices(3);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 0).unwrap();
assert_eq!(mean_distance(&g).unwrap(), Some(1.0));
}
#[test]
fn mean_distance_two_components_only_within_components() {
// {0-1-2} and {3-4}: connected pairs are within each component.
// {0-1-2}: 6 ordered pairs (0↔1=1, 0↔2=2, 1↔2=1) → sum 2*(1+2+1) = 8.
// {3-4}: 2 ordered pairs (3↔4) → sum 2.
// Total: 8 connected pairs, sum 10, mean = 10/8 = 1.25.
let mut g = Graph::with_vertices(5);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(3, 4).unwrap();
assert_eq!(mean_distance(&g).unwrap(), Some(1.25));
}
#[test]
fn mean_distance_directed_uses_out_edges() {
// 0 -> 1 -> 2: only 3 ordered reachable pairs: (0,1)=1, (0,2)=2, (1,2)=1.
// Sum = 4, count = 3, mean = 4/3.
let mut g = Graph::new(3, true).unwrap();
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
let four_thirds = 4.0_f64 / 3.0;
assert_eq!(mean_distance(&g).unwrap(), Some(four_thirds));
}
#[test]
fn mean_degree_empty_graph() {
let g = Graph::with_vertices(0);
assert_eq!(mean_degree(&g, true).unwrap(), None);
}
#[test]
fn mean_degree_no_edges() {
let g = Graph::with_vertices(5);
let md = mean_degree(&g, true).unwrap().unwrap();
assert!((md - 0.0).abs() < 1e-10);
}
#[test]
fn mean_degree_undirected_path() {
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();
// 3 edges, 4 vertices, undirected: 2*3/4 = 1.5
let md = mean_degree(&g, true).unwrap().unwrap();
assert!((md - 1.5).abs() < 1e-10);
}
#[test]
fn mean_degree_directed() {
let mut g = Graph::new(3, true).unwrap();
g.add_edge(0, 1).unwrap();
g.add_edge(0, 2).unwrap();
g.add_edge(1, 2).unwrap();
// 3 edges, 3 vertices, directed: 3/3 = 1.0
let md = mean_degree(&g, true).unwrap().unwrap();
assert!((md - 1.0).abs() < 1e-10);
}
#[test]
fn mean_degree_with_self_loops() {
let mut g = Graph::with_vertices(3);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(0, 0).unwrap(); // self-loop
// With loops: 3 edges, undirected: 2*3/3 = 2.0
let md_with = mean_degree(&g, true).unwrap().unwrap();
assert!((md_with - 2.0).abs() < 1e-10);
// Without loops: 2 edges, undirected: 2*2/3 = 4/3
let md_without = mean_degree(&g, false).unwrap().unwrap();
assert!((md_without - 4.0 / 3.0).abs() < 1e-10);
}
#[test]
fn mean_degree_complete_undirected() {
// K4: 6 edges, 4 vertices: 2*6/4 = 3.0
let mut g = Graph::with_vertices(4);
for u in 0..4u32 {
for v in (u + 1)..4 {
g.add_edge(u, v).unwrap();
}
}
let md = mean_degree(&g, true).unwrap().unwrap();
assert!((md - 3.0).abs() < 1e-10);
}
}