Skip to main content

webgraph_cli/transform/
map.rs

1/*
2 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR MIT
5 */
6
7use crate::*;
8use anyhow::Result;
9use dsi_bitstream::{dispatch::factory::CodesReaderFactoryHelper, prelude::*};
10use dsi_progress_logger::prelude::*;
11use std::path::PathBuf;
12use value_traits::slices::SliceByValue;
13use webgraph::prelude::*;
14
15#[derive(Parser, Debug)]
16#[command(name = "map", about = "Maps a graph in the BV format through an arbitrary function on nodes, deduplicating arcs.", long_about = None, next_line_help = true)]
17pub struct CliArgs {
18    /// The basename of the source graph.​
19    pub src: PathBuf,
20    /// The basename of the mapped graph.​
21    pub dst: PathBuf,
22
23    /// The path to the map to apply to the graph.​
24    pub map: PathBuf,
25
26    #[arg(long, value_enum, default_value_t)]
27    /// The format of the map file.​
28    pub fmt: IntSliceFormat,
29
30    #[arg(long)]
31    /// The number of nodes of the resulting graph; if not specified, it is
32    /// computed as one plus the maximum value in the map; if specified, it must
33    /// be strictly greater than the maximum value in the map.​
34    pub num_nodes: Option<usize>,
35
36    #[arg(short, long)]
37    /// Uses the sequential algorithm (does not need offsets).​
38    pub sequential: bool,
39
40    #[clap(flatten)]
41    pub num_threads: NumThreadsArg,
42
43    #[clap(flatten)]
44    pub memory_usage: MemoryUsageArg,
45
46    #[clap(flatten)]
47    pub ca: CompressArgs,
48
49    #[arg(long, conflicts_with = "sequential")]
50    /// Uses the degree cumulative function to balance work by arcs rather than
51    /// by nodes; the DCF must have been pre-built with `webgraph build dcf`.​
52    pub dcf: bool,
53
54    #[clap(flatten)]
55    pub log_interval: LogIntervalArg,
56}
57
58pub fn main(args: CliArgs) -> Result<()> {
59    create_parent_dir(&args.dst)?;
60
61    dispatch_endianness!(&args.src, |E| {
62        if args.sequential {
63            map_seq::<E>(args)
64        } else {
65            map_par::<E>(args)
66        }
67    })
68}
69
70/// Computes the number of nodes of the mapped graph.
71fn mapped_num_nodes<P: SliceByValue<Value = usize>>(
72    node_map: &P,
73    cli_num_nodes: Option<usize>,
74) -> Result<usize> {
75    let max_mapped = (0..node_map.len())
76        .map(|i| node_map.index_value(i))
77        .max()
78        .unwrap_or(0);
79    match cli_num_nodes {
80        Some(n) => {
81            anyhow::ensure!(
82                n > max_mapped,
83                "The specified number of nodes ({}) is not strictly greater than the maximum mapped node ({})",
84                n,
85                max_mapped,
86            );
87            Ok(n)
88        }
89        None => Ok(max_mapped + 1),
90    }
91}
92
93/// Parallel version of [`map_seq`].
94pub fn map_par<E: Endianness>(args: CliArgs) -> Result<()>
95where
96    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
97    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek + Clone + Send + Sync,
98{
99    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
100    let log_interval = args.log_interval.log_interval;
101    let target_endianness = args.ca.target_endianness::<E>();
102    let builder = args.ca.bv_comp_conf(&args.dst);
103
104    let loaded = args.fmt.load(&args.map)?;
105    let cli_num_nodes = args.num_nodes;
106    let memory_usage = args.memory_usage.memory_usage;
107
108    dispatch_int_slice!(loaded, |node_map| {
109        let num_nodes = mapped_num_nodes(&node_map, cli_num_nodes)?;
110
111        let graph = webgraph::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
112            .endianness::<E>()
113            .load()?;
114
115        let par_graph = crate::par_graph(
116            graph,
117            &args.src,
118            args.dcf,
119            thread_pool.current_num_threads(),
120        )?;
121
122        thread_pool.install(|| {
123            log::info!("Mapping graph with memory usage {}", memory_usage);
124            let mut pl = progress_logger![display_memory = true, log_interval = log_interval];
125            let start = std::time::Instant::now();
126            let sorted = webgraph::transform::map_par(
127                &par_graph,
128                &node_map,
129                num_nodes,
130                memory_usage,
131                &mut pl,
132            )?;
133            log::info!(
134                "Mapped the graph. It took {:.3} seconds",
135                start.elapsed().as_secs_f64()
136            );
137
138            let mut builder = builder.progress_logger(&mut pl);
139            par_comp!(builder, sorted, target_endianness)
140        })?;
141
142        Ok(())
143    })
144}
145
146/// Sequential version of [`map_par`].
147pub fn map_seq<E: Endianness>(args: CliArgs) -> Result<()>
148where
149    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
150{
151    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
152    let log_interval = args.log_interval.log_interval;
153    let target_endianness = args.ca.target_endianness::<E>();
154    let builder = args.ca.bv_comp_conf(&args.dst);
155
156    let loaded = args.fmt.load(&args.map)?;
157    let cli_num_nodes = args.num_nodes;
158    let memory_usage = args.memory_usage.memory_usage;
159
160    dispatch_int_slice!(loaded, |node_map| {
161        let num_nodes = mapped_num_nodes(&node_map, cli_num_nodes)?;
162
163        let seq_graph = webgraph::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.src)
164            .endianness::<E>()
165            .load()?;
166
167        log::info!("Mapping graph with memory usage {}", memory_usage);
168        let mut pl = progress_logger![display_memory = true, log_interval = log_interval];
169        let start = std::time::Instant::now();
170        let sorted =
171            webgraph::transform::map_seq(&seq_graph, &node_map, num_nodes, memory_usage, &mut pl)?;
172        log::info!(
173            "Mapped the graph. It took {:.3} seconds",
174            start.elapsed().as_secs_f64()
175        );
176
177        let mut builder = builder.progress_logger(&mut pl);
178        thread_pool.install(|| par_comp!(builder, sorted, target_endianness))?;
179
180        Ok(())
181    })
182}