Skip to main content

webgraph_cli/perm/
bfs.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
3 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
4 *
5 * SPDX-License-Identifier: Apache-2.0 OR MIT
6 */
7
8use crate::{IntSliceFormat, LogIntervalArg, create_parent_dir};
9use anyhow::Result;
10use clap::Parser;
11use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
12use dsi_bitstream::prelude::*;
13use dsi_progress_logger::prelude::*;
14use std::path::PathBuf;
15use webgraph::prelude::*;
16
17#[derive(Parser, Debug)]
18#[command(name = "bfs", about = "Computes the permutation induced by a breadth-first visit.", long_about = None, next_line_help = true)]
19pub struct CliArgs {
20    /// The basename of the graph.​
21    pub basename: PathBuf,
22
23    /// The filename of the permutation.​
24    pub perm: PathBuf,
25
26    #[arg(long, value_enum, default_value_t)]
27    /// The format of the permutation file.​
28    pub fmt: IntSliceFormat,
29
30    #[clap(flatten)]
31    pub log_interval: LogIntervalArg,
32}
33
34pub fn main(args: CliArgs) -> Result<()> {
35    create_parent_dir(&args.perm)?;
36
37    dispatch_endianness!(&args.basename, |E| bfs::<E>(args))
38}
39
40pub fn bfs<E: Endianness + 'static + Send + Sync>(args: CliArgs) -> Result<()>
41where
42    MemoryFactory<E, MmapHelper<u32>>: CodesReaderFactoryHelper<E>,
43    for<'a> LoadModeCodesReader<'a, E, LoadMmap>: BitSeek,
44{
45    // load the graph
46    let graph = BvGraph::with_basename(&args.basename)
47        .mode::<LoadMmap>()
48        .flags(MemoryFlags::TRANSPARENT_HUGE_PAGES | MemoryFlags::RANDOM_ACCESS)
49        .endianness::<E>()
50        .load()?;
51
52    let mut pl = progress_logger![
53        display_memory = true,
54        item_name = "nodes",
55        expected_updates = Some(graph.num_nodes()),
56        log_interval = args.log_interval.log_interval,
57    ];
58
59    // create the permutation
60    let mut perm = vec![0; graph.num_nodes()];
61    pl.start("Computing BFS permutation...");
62    let mut visit = webgraph::visits::breadth_first::Seq::new(&graph);
63    for (i, event) in visit.into_iter().enumerate() {
64        perm[event.node] = i;
65        pl.light_update();
66    }
67    pl.done();
68
69    args.fmt.store(&args.perm, &perm, None)?;
70
71    Ok(())
72}