Skip to main content

webgraph_cli/dist/hyperball/
mod.rs

1/*
2 * SPDX-FileCopyrightText: 2025 Tommaso Fontana
3 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
4 *
5 * SPDX-License-Identifier: Apache-2.0 OR MIT
6 */
7
8use crate::{FloatSliceFormat, GranularityArgs, LogIntervalArg, NumThreadsArg, get_thread_pool};
9use anyhow::Result;
10use clap::{ArgGroup, Args, Parser};
11use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
12use dsi_bitstream::prelude::*;
13use dsi_progress_logger::progress_logger;
14use rand::SeedableRng;
15use std::path::PathBuf;
16use webgraph::prelude::{
17    BvGraph, LoadModeCodesReader, Mmap, RandomAccessLabeling, SequentialLabeling,
18};
19use webgraph::utils::{Granularity, MmapHelper};
20use webgraph_algo::distances::hyperball::{self, HyperBallBuilder};
21
22#[derive(Args, Debug, Clone)]
23#[clap(group = ArgGroup::new("centralities"))]
24/// Centralities that can be computed with hyperball.
25///
26/// To compress the result you can use named pipes or process substitution
27/// like `--harmonic >(zstd > harmonic.zstd)`.​
28pub struct Centralities {
29    /// Storage format for centralities.​
30    #[clap(long, value_enum, default_value_t = FloatSliceFormat::Ascii)]
31    pub fmt: FloatSliceFormat,
32    #[clap(long)]
33    /// Number of decimal digits for centralities in text formats.​
34    pub precision: Option<usize>,
35
36    /// Computes the approximate sum of distances and saves them at the given path.​
37    #[clap(long)]
38    pub sum_of_distances: Option<PathBuf>,
39    /// Computes the approximate number of reachable nodes and saves them at the given path.​
40    #[clap(long)]
41    pub reachable_nodes: Option<PathBuf>,
42    /// Computes the approximate harmonic centralities and saves them at the given path.​
43    #[clap(long)]
44    pub harmonic: Option<PathBuf>,
45    /// Computes the approximate closeness centralities and saves them at the given path.​
46    #[clap(long)]
47    pub closeness: Option<PathBuf>,
48    #[clap(long)]
49    /// Computes the approximate neighborhood function and saves it at the given path.​
50    pub neighborhood_function: Option<PathBuf>,
51}
52
53impl Centralities {
54    pub const fn should_compute_sum_of_distances(&self) -> bool {
55        self.sum_of_distances.is_some() || self.closeness.is_some()
56    }
57    pub const fn should_compute_sum_of_inverse_distances(&self) -> bool {
58        self.harmonic.is_some()
59    }
60}
61
62#[derive(Parser, Debug)]
63#[command(group(
64        ArgGroup::new("symmetric or transpose")
65        .required(true)
66        .multiple(false)
67        .args(["transpose", "symmetric"]),
68))]
69#[command(
70    name = "hyperball",
71    about = "Computes centralities using HyperBall.",
72    long_about = None, next_line_help = true)]
73pub struct CliArgs {
74    /// The basename of the graph.​
75    pub basename: PathBuf,
76
77    /// The basename of the transpose of the graph. If available, HyperBall will
78    /// perform systolic iterations which will speed up the computation. If the
79    /// graph is symmetric, use the --symm option instead.​
80    pub transpose: Option<PathBuf>,
81
82    #[clap(long = "symm", short, default_value_t = false)]
83    /// The graph is symmetric (it will be used as its own transpose).​
84    pub symmetric: bool,
85
86    #[clap(short = 'm', long, default_value_t = 8)]
87    /// The base-2 logarithm of the number of registers for the HyperLogLog
88    /// cardinality estimators.​
89    pub log2m: u32,
90
91    #[clap(short, long)]
92    /// Uses an external (spill-to-disk) output store in TMPDIR, keeping only
93    /// one counter array in RAM instead of two; halves the counter memory at
94    /// the cost of extra I/O after each iteration.​
95    pub external: bool,
96
97    #[clap(short = '8', long)]
98    /// Use HyperLogLog8 (byte-sized registers with SIMD-accelerated merges);
99    /// trades ~33% extra space for significantly faster merge operations.​
100    pub hll8: bool,
101
102    #[clap(long)]
103    /// Maximum number of iterations to run.​
104    pub upper_bound: Option<usize>,
105
106    #[clap(long)]
107    /// A value that will be used to stop the computation by relative increment
108    /// if the neighborhood function is being computed. Otherwise, the
109    /// computation will stop when all estimators do not change their values.​
110    pub threshold: Option<f64>,
111
112    #[clap(flatten)]
113    pub centralities: Centralities,
114
115    #[clap(flatten)]
116    pub num_threads: NumThreadsArg,
117
118    #[clap(flatten)]
119    pub granularity: GranularityArgs,
120
121    #[clap(flatten)]
122    pub log_interval: LogIntervalArg,
123
124    #[clap(long, default_value_t = 0)]
125    /// The seed of the pseudorandom number generator used for initialization.​
126    pub seed: u64,
127}
128
129pub fn main(args: CliArgs) -> Result<()> {
130    dispatch_endianness!(&args.basename, |E| hyperball::<E>(args))
131}
132
133pub fn hyperball<E: Endianness>(args: CliArgs) -> Result<()>
134where
135    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
136    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek + Clone + Send + Sync,
137{
138    let mut pl = progress_logger![
139        display_memory = true,
140        log_interval = args.log_interval.log_interval,
141    ];
142    let thread_pool = get_thread_pool(args.num_threads.num_threads);
143
144    log::info!("Loading graph...");
145    let graph = BvGraph::with_basename(&args.basename)
146        .endianness::<E>()
147        .load()?;
148
149    log::info!("Loading DCF...");
150    let deg_cumul_func = crate::load_dcf(&args.basename, graph.num_nodes(), graph.num_arcs())?;
151
152    // As soon as we can use a more recent compiler, this can be avoided using
153    // Some(&BvGraph::with_basename(transposed_path).endianness::<E>().load()?) below.
154    let mut _transpose_loaded = None;
155
156    let transpose = if args.symmetric {
157        Some(&graph)
158    } else if let Some(transposed_path) = args.transpose {
159        log::info!("Loading transpose...");
160        _transpose_loaded = Some(
161            BvGraph::with_basename(transposed_path)
162                .endianness::<E>()
163                .load()?,
164        );
165        _transpose_loaded.as_ref()
166    } else {
167        None
168    };
169
170    /// Runs HyperBall and stores results. We use a macro because different
171    /// estimation logics produce different `HyperBall` types.
172    macro_rules! run_and_store {
173        ($hb:expr) => {{
174            let mut hb = $hb;
175
176            let rng = rand::rngs::SmallRng::seed_from_u64(args.seed);
177            thread_pool.install(|| {
178                hb.run(
179                    args.upper_bound.unwrap_or(usize::MAX),
180                    args.threshold,
181                    rng,
182                    &mut pl,
183                )
184            })?;
185
186            log::info!("Storing the results...");
187
188            macro_rules! store_centrality {
189                ($flag:ident, $method:ident, $description:expr) => {{
190                    if let Some(path) = args.centralities.$flag {
191                        log::info!("Saving {} to {}", $description, path.display());
192                        let value = hb.$method()?;
193                        args.centralities
194                            .fmt
195                            .store(path, &value, args.centralities.precision)?;
196                    }
197                }};
198            }
199
200            store_centrality!(sum_of_distances, sum_of_distances, "sum of distances");
201            store_centrality!(harmonic, harmonic_centralities, "harmonic centralities");
202            store_centrality!(closeness, closeness_centrality, "closeness centralities");
203            store_centrality!(reachable_nodes, reachable_nodes, "reachable nodes");
204            store_centrality!(
205                neighborhood_function,
206                neighborhood_function,
207                "neighborhood function"
208            );
209        }};
210    }
211
212    macro_rules! configure_and_run {
213        ($builder:expr) => {{
214            let hb = $builder
215                .granularity(
216                    args.granularity
217                        .into_granularity_or(Granularity::Nodes(hyperball::DEFAULT_GRANULARITY)),
218                )
219                .sum_of_distances(args.centralities.should_compute_sum_of_distances())
220                .sum_of_inverse_distances(
221                    args.centralities.should_compute_sum_of_inverse_distances(),
222                )
223                .build(&mut pl);
224            run_and_store!(hb);
225        }};
226    }
227
228    match (args.hll8, args.external) {
229        (false, false) => configure_and_run!(HyperBallBuilder::with_hyper_log_log(
230            &graph,
231            transpose,
232            deg_cumul_func.uncase(),
233            args.log2m,
234            None,
235        )?),
236        (false, true) => configure_and_run!(HyperBallBuilder::with_hyper_log_log_external(
237            &graph,
238            transpose,
239            deg_cumul_func.uncase(),
240            args.log2m,
241            None,
242        )?),
243        (true, false) => configure_and_run!(HyperBallBuilder::with_hyper_log_log8(
244            &graph,
245            transpose,
246            deg_cumul_func.uncase(),
247            args.log2m,
248            None,
249        )?),
250        (true, true) => configure_and_run!(HyperBallBuilder::with_hyper_log_log8_external(
251            &graph,
252            transpose,
253            deg_cumul_func.uncase(),
254            args.log2m,
255            None,
256        )?),
257    }
258
259    Ok(())
260}