Skip to main content

webgraph_cli/
sccs.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::{
8    IntSliceFormat, LogIntervalArg, build_info, get_thread_pool, num_threads_parser, timed,
9};
10use anyhow::Result;
11use clap::Parser;
12use dsi_bitstream::prelude::factory::CodesReaderFactoryHelper;
13use dsi_bitstream::prelude::*;
14use dsi_progress_logger::progress_logger;
15use std::path::PathBuf;
16use webgraph::prelude::*;
17
18#[derive(Parser, Debug)]
19#[command(name = "webgraph-sccs", version=build_info::version_string(), max_term_width = 100, next_line_help = true, after_help = include_str!("common_env.txt"))]
20/// Computes the strongly connected components of a graph.​
21pub struct Cli {
22    #[clap(flatten)]
23    args: CliArgs,
24}
25
26#[derive(Parser, Debug)]
27pub struct CliArgs {
28    /// The basename of the graph.​
29    pub basename: PathBuf,
30
31    /// Output path for the strongly connected components.​
32    pub sccs: PathBuf,
33
34    #[arg(short = 's', long)]
35    /// Computes the sizes of the strongly connected components and stores them
36    /// at the given path.​
37    pub sizes: Option<PathBuf>,
38
39    #[arg(short, long)]
40    /// Renumbers components in decreasing-size order (implicitly, computes sizes).​
41    pub renumber: bool,
42
43    #[arg(short = 'j', long, default_value_t = rayon::current_num_threads().max(1), value_parser = num_threads_parser)]
44    /// The number of threads to use to compute the sizes of the components.​
45    pub num_threads: usize,
46
47    #[arg(long, value_enum, default_value_t = IntSliceFormat::Ascii)]
48    /// The storage format for components and component sizes.​
49    pub fmt: IntSliceFormat,
50
51    #[clap(flatten)]
52    pub log_interval: LogIntervalArg,
53}
54
55pub fn cli_main<I, T>(args: I) -> Result<()>
56where
57    I: IntoIterator<Item = T>,
58    T: Into<std::ffi::OsString> + Clone,
59{
60    timed(|| main(Cli::parse_from(args).args))
61}
62
63pub fn main(args: CliArgs) -> Result<()> {
64    dispatch_endianness!(&args.basename, |E| sccs::<E>(args))
65}
66
67pub fn sccs<E: Endianness>(args: CliArgs) -> Result<()>
68where
69    MemoryFactory<E, MmapHelper<u32>>: CodesReaderFactoryHelper<E>,
70    for<'a> LoadModeCodesReader<'a, E, LoadMmap>: BitSeek,
71{
72    log::info!("Loading the graph from {}", args.basename.display());
73    let graph = BvGraph::with_basename(&args.basename)
74        .mode::<LoadMmap>()
75        .flags(MemoryFlags::TRANSPARENT_HUGE_PAGES | MemoryFlags::RANDOM_ACCESS)
76        .endianness::<E>()
77        .load()?;
78
79    let mut pl = progress_logger![
80        expected_updates = Some(graph.num_nodes()),
81        log_interval = args.log_interval.log_interval
82    ];
83
84    let mut sccs = webgraph_algo::sccs::tarjan(graph, &mut pl);
85    log::info!(
86        "Found {} strongly connected components",
87        sccs.num_components()
88    );
89
90    if args.renumber {
91        log::info!("Renumbering components by decreasing size");
92        let component_sizes = if args.num_threads == 1 {
93            log::debug!("Using sequential algorithm");
94            sccs.sort_by_size()
95        } else {
96            let thread_pool = get_thread_pool(args.num_threads);
97            log::debug!("Using parallel algorithm with {} threads", args.num_threads);
98            thread_pool.install(|| sccs.par_sort_by_size())
99        };
100        if let Some(sizes_path) = &args.sizes {
101            let max = component_sizes.first().copied();
102            args.fmt.store(sizes_path, &component_sizes, max)?;
103        }
104    } else if let Some(sizes_path) = &args.sizes {
105        log::info!("Computing the sizes of the components");
106        let sizes = sccs.compute_sizes();
107        args.fmt.store(sizes_path, &sizes, None)?;
108    };
109
110    args.fmt.store(
111        &args.sccs,
112        sccs.components(),
113        Some(sccs.num_components() - 1),
114    )?;
115
116    Ok(())
117}