Skip to main content

webgraph_cli/analyze/
stats.rs

1/*
2 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR MIT
5 */
6
7use crate::LogIntervalArg;
8use anyhow::{Result, ensure};
9use clap::Parser;
10use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
11use dsi_bitstream::prelude::*;
12use dsi_progress_logger::prelude::*;
13use lender::*;
14use std::io::Write;
15use std::path::PathBuf;
16use value_traits::slices::SliceByValue;
17use webgraph::prelude::*;
18
19#[derive(Parser, Debug)]
20#[command(
21    name = "stats",
22    about = "Computes statistical data of a graph.",
23    long_about = "Computes statistical data of a graph: outdegree and indegree \
24        distributions, average gap, average locality, dangling/terminal nodes, \
25        successor delta statistics, and optionally SCC-related statistics. \
26        The graph is scanned sequentially, so only the indegree array (one \
27        counter per node) is allocated.",
28    next_line_help = true
29)]
30pub struct CliArgs {
31    /// The basename of the graph.​
32    pub basename: PathBuf,
33
34    /// The basename for result files (default: same as graph basename).​
35    pub results_basename: Option<PathBuf>,
36
37    #[arg(short = 's', long)]
38    /// Save per-node indegrees and outdegrees.​
39    pub save_degrees: bool,
40
41    #[arg(long, value_enum, default_value_t = crate::IntSliceFormat::Ascii)]
42    /// Format for per-node indegrees and outdegrees.​
43    pub degrees_fmt: crate::IntSliceFormat,
44
45    #[arg(long)]
46    /// Path to sizes of strongly connected components (as produced by webgraph-sccs --sizes).​
47    pub scc_sizes: Option<PathBuf>,
48
49    #[arg(long, value_enum, default_value_t = crate::IntSliceFormat::Ascii)]
50    /// Format of the sizes of strongly connected components.​
51    pub scc_sizes_fmt: crate::IntSliceFormat,
52
53    #[clap(flatten)]
54    pub log_interval: LogIntervalArg,
55}
56
57pub fn main(args: CliArgs) -> Result<()> {
58    dispatch_endianness!(&args.basename, |E| stats::<E>(args))
59}
60
61pub fn stats<E: Endianness + 'static>(args: CliArgs) -> Result<()>
62where
63    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
64{
65    let graph = BvGraphSeq::with_basename(&args.basename)
66        .endianness::<E>()
67        .load()?;
68
69    let num_nodes = graph.num_nodes();
70    ensure!(
71        num_nodes > 0,
72        "Cannot compute statistics for a graph with no nodes"
73    );
74    let results_basename = args.results_basename.as_ref().unwrap_or(&args.basename);
75
76    let mut outdegree_count: Vec<u64> = Vec::new();
77    let mut indegree = vec![0usize; num_nodes];
78    let mut outdegrees: Vec<usize> = if args.save_degrees {
79        Vec::with_capacity(num_nodes)
80    } else {
81        Vec::new()
82    };
83
84    let mut max_outdegree: usize = 0;
85    let mut max_outdegree_node: usize = 0;
86    let mut min_outdegree: usize = usize::MAX;
87    let mut min_outdegree_node: usize = 0;
88    let mut dangling: u64 = 0;
89    let mut terminal: u64 = 0;
90    let mut loops: u64 = 0;
91    let mut num_arcs: u64 = 0;
92    let mut num_gaps: u64 = 0;
93    let mut tot_loc: u128 = 0;
94    let mut tot_gap: u128 = 0;
95
96    // Statistics for the gap width of successor lists (exponentially binned).
97    let mut successor_delta_stats = [0u64; 64];
98
99    let mut pl = progress_logger![
100        display_memory = true,
101        item_name = "node",
102        expected_updates = Some(num_nodes),
103        log_interval = args.log_interval.log_interval,
104    ];
105    pl.start("Scanning...");
106
107    for_!((node, successors) in graph.iter() {
108        let succ: Vec<usize> = successors.collect();
109        let d = succ.len();
110
111        if args.save_degrees {
112            outdegrees.push(d);
113        }
114
115        if d > 1 {
116            tot_gap += (succ[d - 1] - succ[0]) as u128;
117            tot_gap += (succ[0] as i64 - node as i64).to_nat() as u128;
118            num_gaps += d as u64;
119        }
120
121        for &s in &succ {
122            tot_loc += s.abs_diff(node) as u128;
123
124            if s != node {
125                let delta = node.abs_diff(s);
126                successor_delta_stats[delta.ilog2() as usize] += 1;
127            } else {
128                loops += 1;
129            }
130
131            indegree[s] += 1;
132        }
133
134        if d == 0 {
135            dangling += 1;
136            terminal += 1;
137        }
138
139        if d == 1 && succ[0] == node {
140            terminal += 1;
141        }
142
143        if d < min_outdegree {
144            min_outdegree = d;
145            min_outdegree_node = node;
146        }
147
148        if d > max_outdegree {
149            max_outdegree = d;
150            max_outdegree_node = node;
151        }
152
153        num_arcs += d as u64;
154
155        if d >= outdegree_count.len() {
156            outdegree_count.resize(d + 1, 0);
157        }
158        outdegree_count[d] += 1;
159
160        pl.light_update();
161    });
162
163    pl.done();
164
165    if args.save_degrees {
166        args.degrees_fmt.store(
167            results_basename.with_extension("outdegrees"),
168            &outdegrees,
169            Some(max_outdegree),
170        )?;
171        args.degrees_fmt.store(
172            results_basename.with_extension("indegrees"),
173            &indegree,
174            None,
175        )?;
176    }
177
178    // Write .stats properties file
179    let stats_path = results_basename.with_extension("stats");
180    let mut p = std::io::BufWriter::new(std::fs::File::create(&stats_path)?);
181
182    writeln!(p, "nodes={}", num_nodes)?;
183    writeln!(p, "arcs={}", num_arcs)?;
184    writeln!(p, "loops={}", loops)?;
185    writeln!(
186        p,
187        "successoravggap={:.3}",
188        tot_gap as f64 / num_gaps.max(1) as f64
189    )?;
190    writeln!(
191        p,
192        "avglocality={:.3}",
193        tot_loc as f64 / num_arcs.max(1) as f64
194    )?;
195    writeln!(p, "minoutdegree={}", min_outdegree)?;
196    writeln!(p, "maxoutdegree={}", max_outdegree)?;
197    writeln!(p, "minoutdegreenode={}", min_outdegree_node)?;
198    writeln!(p, "maxoutdegreenode={}", max_outdegree_node)?;
199    writeln!(p, "dangling={}", dangling)?;
200    writeln!(p, "terminal={}", terminal)?;
201    writeln!(
202        p,
203        "percdangling={}",
204        100.0 * dangling as f64 / num_nodes as f64
205    )?;
206    writeln!(p, "avgoutdegree={}", num_arcs as f64 / num_nodes as f64)?;
207
208    // Successor log-delta statistics
209    let l = successor_delta_stats
210        .iter()
211        .rposition(|&x| x != 0)
212        .unwrap_or(0);
213
214    let mut tot_log_delta = 0u128;
215    let mut num_delta = 0u64;
216    let delta_str: String = (0..=l)
217        .map(|i| {
218            let count = successor_delta_stats[i];
219            num_delta += count;
220            let g: u64 = 1 << i; // 2^i
221            tot_log_delta += (((g * 3 + 1).ilog2() - 1) as u64 * count) as u128;
222            count.to_string()
223        })
224        .collect::<Vec<_>>()
225        .join(",");
226
227    writeln!(p, "successorlogdeltastats={}", delta_str)?;
228    writeln!(
229        p,
230        "successoravglogdelta={}",
231        if num_delta == 0 {
232            "0".to_string()
233        } else {
234            format!("{:.3}", tot_log_delta as f64 / (num_delta * 2) as f64)
235        }
236    )?;
237
238    // Write outdegree distribution
239    {
240        let path = results_basename.with_extension("outdegree");
241        let mut w = std::io::BufWriter::new(std::fs::File::create(&path)?);
242        for &count in &outdegree_count {
243            writeln!(w, "{}", count)?;
244        }
245    }
246
247    // Compute and write indegree statistics
248    let mut indegree_count: Vec<u64> = Vec::new();
249    let mut max_indegree: usize = 0;
250    let mut max_indegree_node: usize = 0;
251    let mut min_indegree = usize::MAX;
252    let mut min_indegree_node: usize = 0;
253
254    // Iterate in reverse to match the Java behavior for tie-breaking on
255    // min/max indegree nodes (last node wins for min, first for max when
256    // iterating backwards).
257    for i in (0..num_nodes).rev() {
258        let d = indegree[i];
259        if d >= indegree_count.len() {
260            indegree_count.resize(d + 1, 0);
261        }
262        if d < min_indegree {
263            min_indegree = d;
264            min_indegree_node = i;
265        }
266        if d > max_indegree {
267            max_indegree = d;
268            max_indegree_node = i;
269        }
270        indegree_count[d] += 1;
271    }
272
273    {
274        let path = results_basename.with_extension("indegree");
275        let mut w = std::io::BufWriter::new(std::fs::File::create(&path)?);
276        for &count in &indegree_count {
277            writeln!(w, "{}", count)?;
278        }
279    }
280
281    writeln!(p, "minindegree={}", min_indegree)?;
282    writeln!(p, "maxindegree={}", max_indegree)?;
283    writeln!(p, "minindegreenode={}", min_indegree_node)?;
284    writeln!(p, "maxindegreenode={}", max_indegree_node)?;
285    writeln!(p, "avgindegree={}", num_arcs as f64 / num_nodes as f64)?;
286
287    // SCC statistics (optional)
288    if let Some(scc_sizes_path) = args.scc_sizes {
289        let int_slice = args.scc_sizes_fmt.load(&scc_sizes_path)?;
290        dispatch_int_slice!(int_slice, |sizes| {
291            let mut scc_sizes: Vec<usize> =
292                (0..sizes.len()).map(|i| sizes.index_value(i)).collect();
293            scc_sizes.sort_unstable();
294
295            let m = scc_sizes.len();
296            ensure!(m > 0, "The SCC sizes file is empty");
297            let max_size = scc_sizes[m - 1];
298            let min_size = scc_sizes[0];
299
300            writeln!(p, "sccs={}", m)?;
301            writeln!(p, "maxsccsize={}", max_size)?;
302            writeln!(
303                p,
304                "percmaxscc={}",
305                100.0 * max_size as f64 / num_nodes as f64
306            )?;
307            writeln!(p, "minsccsize={}", min_size)?;
308            writeln!(
309                p,
310                "percminscc={}",
311                100.0 * min_size as f64 / num_nodes as f64
312            )?;
313
314            // Write SCC size distribution (descending size, with counts)
315            let scc_distr_path = results_basename.with_extension("sccdistr");
316            let mut pw = std::io::BufWriter::new(std::fs::File::create(&scc_distr_path)?);
317
318            let mut current = max_size;
319            let mut count: usize = 0;
320            for i in (0..scc_sizes.len()).rev() {
321                if scc_sizes[i] != current {
322                    writeln!(pw, "{}\t{}", current, count)?;
323                    current = scc_sizes[i];
324                    count = 0;
325                }
326                count += 1;
327            }
328            writeln!(pw, "{}\t{}", current, count)?;
329        });
330    }
331
332    Ok(())
333}