Skip to main content

webgraph_cli/dist/ess/
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 */
7use crate::{IntSliceFormat, LogIntervalArg, NumThreadsArg};
8use anyhow::{Result, ensure};
9use clap::{ArgGroup, Parser, ValueEnum};
10use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
11use dsi_bitstream::prelude::*;
12use dsi_progress_logger::progress_logger;
13use std::path::PathBuf;
14use webgraph::prelude::{BvGraph, LoadModeCodesReader, Mmap};
15use webgraph::utils::MmapHelper;
16use webgraph_algo::distances::exact_sum_sweep::{
17    All, AllForward, Diameter, Level, Radius, RadiusDiameter,
18};
19
20#[derive(Parser, Debug)]
21#[command(group(
22        ArgGroup::new("symmetric or transpose")
23        .required(true)
24        .multiple(false)
25        .args(["transpose", "symmetric"]),
26))]
27#[command(name = "exact-sum-sweep", about = "Computes radius, diameter, and possibly eccentricities using the ExactSumSweep algorithm (scalar values are printed on stdout).", long_about = None, next_line_help = true)]
28pub struct CliArgs {
29    /// The items to be computed ("all-forward" computes forward eccentricities,
30    /// "all" computes both forward and backward eccentricities).​
31    #[arg(value_enum)]
32    pub level: LevelArg,
33
34    /// The basename of the graph.​
35    pub basename: PathBuf,
36
37    /// The basename of the transpose of the graph. If the graph is symmetric,
38    /// use the --symm option instead.​
39    pub transpose: Option<PathBuf>,
40
41    #[arg(short, long = "symm")]
42    /// The graph is symmetric.​
43    pub symmetric: bool,
44
45    /// Output path for the forward eccentricities.​
46    #[arg(short, long)]
47    pub forward: Option<PathBuf>,
48
49    /// Output path for the backward eccentricities.​
50    #[arg(short, long)]
51    pub backward: Option<PathBuf>,
52
53    #[arg(long, value_enum, default_value_t = IntSliceFormat::Ascii)]
54    /// The storage format for eccentricities.​
55    pub fmt: IntSliceFormat,
56
57    #[arg(long)]
58    /// Disables total-distance tie-breaking to save memory (16 bytes per node).​
59    pub no_tot: bool,
60
61    #[clap(flatten)]
62    pub num_threads: NumThreadsArg,
63
64    #[clap(flatten)]
65    pub log_interval: LogIntervalArg,
66}
67
68/// The level of exact sum sweep to compute.​
69#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
70pub enum LevelArg {
71    Radius,
72    Diameter,
73    #[clap(name = "radius-diameter")]
74    RadiusDiameter,
75    #[clap(name = "all-forward")]
76    AllForward,
77    All,
78}
79
80pub fn main(args: CliArgs) -> Result<()> {
81    // The ArgGroup guarantees that exactly one of --symm and the transpose
82    // basename is present.
83    ensure!(
84        args.forward.is_none() || matches!(args.level, LevelArg::All | LevelArg::AllForward),
85        "You can only pass --forward with --level=all or --level=all-forward, as the forward eccentricities won't be computed otherwise."
86    );
87    ensure!(
88        !(args.forward.is_none() && matches!(args.level, LevelArg::All | LevelArg::AllForward)),
89        "If --level=all or --level=all-forward, you should pass --forward to store the computed eccentricities."
90    );
91    ensure!(
92        !(args.backward.is_some() && args.level != LevelArg::All),
93        "You can only pass --backward with --level=all as the backward eccentricities won't be computed otherwise."
94    );
95    ensure!(
96        !(args.level == LevelArg::All && args.symmetric && args.backward.is_some()),
97        "You cannot pass --backward with --symm and --level=all as the eccentricities of a symmetric graph are the same in both directions."
98    );
99
100    dispatch_endianness!(&args.basename, |E| exact_sum_sweep::<E>(args))
101}
102
103pub fn exact_sum_sweep<E: Endianness>(args: CliArgs) -> Result<()>
104where
105    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
106    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek + Clone + Send + Sync,
107{
108    let graph = BvGraph::with_basename(&args.basename)
109        .endianness::<E>()
110        .load()?;
111
112    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
113    let mut pl = progress_logger![
114        display_memory = true,
115        log_interval = args.log_interval.log_interval,
116    ];
117
118    let use_tot = !args.no_tot;
119
120    // Prints radius, diameter, the related vertices, and iterations.
121    macro_rules! print_radius_diameter {
122        ($out:expr) => {{
123            println!("Radius: {}", $out.radius);
124            println!("Diameter: {}", $out.diameter);
125            println!("Radial vertex: {}", $out.radial_vertex);
126            println!("Diametral vertex: {}", $out.diametral_vertex);
127            println!("Radius iterations: {}", $out.radius_iterations);
128            println!("Diameter iterations: {}", $out.diameter_iterations);
129        }};
130    }
131
132    macro_rules! ess {
133        (symm $Level:ident) => {
134            $Level::run_symm(graph, use_tot, &mut pl)
135        };
136        ($Level:ident, $transpose:expr) => {
137            $Level::run(graph, $transpose, None, use_tot, &mut pl)
138        };
139    }
140
141    if args.symmetric {
142        match args.level {
143            LevelArg::Radius => {
144                let out = thread_pool.install(|| ess!(symm Radius));
145                println!("Radius: {}", out.radius);
146                println!("Radial vertex: {}", out.radial_vertex);
147                println!("Radius iterations: {}", out.radius_iterations);
148            }
149            LevelArg::Diameter => {
150                let out = thread_pool.install(|| ess!(symm Diameter));
151                println!("Diameter: {}", out.diameter);
152                println!("Diametral vertex: {}", out.diametral_vertex);
153                println!("Diameter iterations: {}", out.diameter_iterations);
154            }
155            LevelArg::RadiusDiameter => {
156                let out = thread_pool.install(|| ess!(symm RadiusDiameter));
157                print_radius_diameter!(out);
158            }
159            LevelArg::AllForward | LevelArg::All => {
160                let out = thread_pool.install(|| ess!(symm All));
161                print_radius_diameter!(out);
162                println!("Iterations: {}", out.iterations);
163                args.fmt
164                    .store(args.forward.as_ref().unwrap(), &out.eccentricities, None)?;
165            }
166        }
167    } else {
168        let transpose_path = args
169            .transpose
170            .as_ref()
171            .expect("You have to pass the transposed graph if the graph is not symmetric.");
172        let transpose = BvGraph::with_basename(transpose_path)
173            .endianness::<E>()
174            .load()?;
175
176        match args.level {
177            LevelArg::Radius => {
178                let out = thread_pool.install(|| ess!(Radius, transpose));
179                println!("Radius: {}", out.radius);
180                println!("Radial vertex: {}", out.radial_vertex);
181                println!("Radius iterations: {}", out.radius_iterations);
182            }
183            LevelArg::Diameter => {
184                let out = thread_pool.install(|| ess!(Diameter, transpose));
185                println!("Diameter: {}", out.diameter);
186                println!("Diametral vertex: {}", out.diametral_vertex);
187                println!("Diameter iterations: {}", out.diameter_iterations);
188            }
189            LevelArg::RadiusDiameter => {
190                let out = thread_pool.install(|| ess!(RadiusDiameter, transpose));
191                print_radius_diameter!(out);
192            }
193            LevelArg::AllForward => {
194                let out = thread_pool.install(|| ess!(AllForward, transpose));
195                print_radius_diameter!(out);
196                println!("Forward iterations: {}", out.forward_iterations);
197                args.fmt.store(
198                    args.forward.as_ref().unwrap(),
199                    &out.forward_eccentricities,
200                    None,
201                )?;
202            }
203            LevelArg::All => {
204                let out = thread_pool.install(|| ess!(All, transpose));
205                print_radius_diameter!(out);
206                println!("Forward iterations: {}", out.forward_iterations);
207                println!("All iterations: {}", out.all_iterations);
208                args.fmt.store(
209                    args.forward.as_ref().unwrap(),
210                    &out.forward_eccentricities,
211                    None,
212                )?;
213                if let Some(backward) = args.backward.as_ref() {
214                    args.fmt
215                        .store(backward, &out.backward_eccentricities, None)?;
216                }
217            }
218        }
219    }
220
221    Ok(())
222}