Skip to main content

webgraph_cli/transform/
symmetrize.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Inria
3 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
4 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR MIT
7 */
8
9use crate::*;
10use anyhow::Result;
11use dsi_bitstream::{dispatch::factory::CodesReaderFactoryHelper, prelude::*};
12use dsi_progress_logger::prelude::*;
13use std::path::PathBuf;
14use webgraph::prelude::*;
15
16#[derive(Parser, Debug)]
17#[command(name = "symmetrize", about = "Symmetrizes a graph in the BV format by adding missing reverse arcs, optionally removing self-loops and applying a permutation.", long_about = None, next_line_help = true)]
18pub struct CliArgs {
19    /// The basename of the graph.​
20    pub src: PathBuf,
21    /// The basename of the symmetrized graph.​
22    pub dst: PathBuf,
23
24    #[arg(long)]
25    /// Remove self-loops from the result.​
26    pub no_loops: bool,
27
28    #[arg(long)]
29    /// The basename of a pre-computed transposed version of the source graph,
30    /// which will be used to speed up the symmetrization.​
31    pub transpose: Option<PathBuf>,
32
33    #[arg(short, long)]
34    /// Uses the sequential algorithm (does not need offsets).​
35    pub sequential: bool,
36
37    #[clap(flatten)]
38    pub num_threads: NumThreadsArg,
39
40    #[clap(flatten)]
41    pub memory_usage: MemoryUsageArg,
42
43    #[clap(flatten)]
44    pub ca: CompressArgs,
45
46    #[arg(long)]
47    /// The path to an optional permutation to apply to the graph.​
48    pub permutation: Option<PathBuf>,
49
50    #[arg(long, value_enum, default_value_t)]
51    /// The format of the permutation file.​
52    pub fmt: IntSliceFormat,
53
54    #[arg(long, conflicts_with = "sequential", requires = "permutation")]
55    /// Uses the degree cumulative function to balance work by arcs rather than
56    /// by nodes; the DCF must have been pre-built with `webgraph build dcf`.​
57    pub dcf: bool,
58
59    #[clap(flatten)]
60    pub log_interval: LogIntervalArg,
61}
62
63/// Compresses the union of a graph and its transpose, possibly removing
64/// self-loops.
65macro_rules! compress_union {
66    ($graph:expr, $graph_t:expr, $no_loops:expr, $builder:expr, $thread_pool:expr, $target_endianness:expr, $log_interval:expr) => {{
67        let (graph, graph_t) = ($graph, $graph_t);
68        anyhow::ensure!(
69            graph_t.num_nodes() == graph.num_nodes(),
70            "The number of nodes in the graph and its transpose do not match! {} != {}",
71            graph.num_nodes(),
72            graph_t.num_nodes()
73        );
74        let mut pl = progress_logger![display_memory = true, log_interval = $log_interval];
75        let mut builder = $builder.progress_logger(&mut pl);
76        if $no_loops {
77            let union = NoSelfLoopsGraph(UnionGraph(graph, graph_t));
78            $thread_pool.install(|| par_comp!(builder, &union, $target_endianness))?;
79        } else {
80            let union = UnionGraph(graph, graph_t);
81            $thread_pool.install(|| par_comp!(builder, &union, $target_endianness))?;
82        }
83    }};
84}
85
86pub fn main(args: CliArgs) -> Result<()> {
87    create_parent_dir(&args.dst)?;
88
89    dispatch_endianness!(&args.src, |E| {
90        if args.sequential {
91            symmetrize_seq::<E>(args)
92        } else {
93            symmetrize_par::<E>(args)
94        }
95    })
96}
97
98/// Parallel version of [`symmetrize_seq`].
99pub fn symmetrize_par<E: Endianness>(args: CliArgs) -> Result<()>
100where
101    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
102    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek + Clone + Send + Sync,
103{
104    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
105    let no_loops = args.no_loops;
106    let log_interval = args.log_interval.log_interval;
107    let target_endianness = args.ca.target_endianness::<E>();
108    let builder = args.ca.bv_comp_conf(&args.dst);
109
110    match (args.permutation, args.transpose) {
111        // Load the transposed graph and use it to directly compress the graph
112        // without doing any sorting
113        (None, Some(t_path)) => {
114            log::info!("Transposed graph provided, using it to symmetrize the graph");
115            compress_union!(
116                BvGraph::with_basename(&args.src).endianness::<E>().load()?,
117                BvGraph::with_basename(&t_path).endianness::<E>().load()?,
118                no_loops,
119                builder,
120                thread_pool,
121                target_endianness,
122                log_interval
123            );
124        }
125        // apply the permutation, don't care if the transposed graph is already computed
126        // as we cannot really exploit it
127        (Some(perm_path), None | Some(_)) => {
128            log::info!("Permutation provided, applying it to the graph");
129
130            let loaded = args.fmt.load(perm_path)?;
131            let memory_usage = args.memory_usage.memory_usage;
132
133            dispatch_int_slice!(loaded, |perm| {
134                // We split the BvGraph directly and apply the permutation
135                // inline rather than wrapping it in a PermutedGraph and
136                // calling symmetrize_par. PermutedGraph's SplitLabeling
137                // uses split::seq::Iter, which advances sequentially to
138                // each cutpoint; it cannot use split::ra::Iter because
139                // PermutedGraph does not implement RandomAccessLabeling
140                // (that would require the inverse permutation).
141                let graph =
142                    webgraph::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
143                        .endianness::<E>()
144                        .load()?;
145                let num_nodes = graph.num_nodes();
146
147                let cp = crate::cutpoints(
148                    &args.src,
149                    num_nodes,
150                    graph.get_num_arcs(),
151                    args.dcf,
152                    thread_pool.current_num_threads(),
153                )?;
154
155                thread_pool.install(|| {
156                    let mut pl =
157                        progress_logger![display_memory = true, log_interval = log_interval];
158                    let conf = ParSortedGraph::config()
159                        .dedup()
160                        .memory_usage(memory_usage)
161                        .progress_logger(&mut pl);
162
163                    let pairs: Vec<_> = graph
164                        .split_iter_at(cp)
165                        .map(|iter| {
166                            iter.into_pairs().flat_map(move |(src, dst)| {
167                                let ps = perm.index_value(src);
168                                let pd = perm.index_value(dst);
169                                if ps != pd {
170                                    Some((ps, pd)).into_iter().chain(Some((pd, ps)))
171                                } else if !no_loops {
172                                    Some((ps, pd)).into_iter().chain(None)
173                                } else {
174                                    None.into_iter().chain(None)
175                                }
176                            })
177                        })
178                        .collect();
179
180                    let sorted = conf.par_sort_pair_iters(num_nodes, pairs)?;
181                    let mut builder = builder.progress_logger(&mut pl);
182                    par_comp!(builder, sorted, target_endianness)
183                })
184            })?;
185        }
186        // Compute the transpose on the fly
187        (None, None) => {
188            log::info!(
189                "No permutation or transposed graph provided, computing the transpose on the fly"
190            );
191
192            let graph = webgraph::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
193                .endianness::<E>()
194                .load()?;
195
196            macro_rules! symmetrize_and_compress {
197                ($no_loops:expr) => {
198                    thread_pool.install(|| {
199                        let mut pl =
200                            progress_logger![display_memory = true, log_interval = log_interval];
201                        let sorted = webgraph::transform::symmetrize_sorted_par::<$no_loops, _>(
202                            &graph,
203                            args.memory_usage.memory_usage,
204                            &mut pl,
205                        )?;
206                        let mut builder = builder.progress_logger(&mut pl);
207                        par_comp!(builder, sorted, target_endianness)
208                    })?
209                };
210            }
211            if no_loops {
212                symmetrize_and_compress!(true);
213            } else {
214                symmetrize_and_compress!(false);
215            }
216        }
217    }
218
219    Ok(())
220}
221
222/// Sequential version of [`symmetrize_par`].
223pub fn symmetrize_seq<E: Endianness>(args: CliArgs) -> Result<()>
224where
225    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
226    for<'a> LoadModeCodesReader<'a, E, Mmap>: Clone + Send + Sync,
227{
228    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
229    let no_loops = args.no_loops;
230    let log_interval = args.log_interval.log_interval;
231    let memory_usage = args.memory_usage.memory_usage;
232    let target_endianness = args.ca.target_endianness::<E>();
233    let builder = args.ca.bv_comp_conf(&args.dst);
234
235    // Symmetrizes sequentially a graph and compresses the result.
236    macro_rules! symmetrize_and_compress {
237        ($graph:expr) => {{
238            let mut pl = progress_logger![display_memory = true, log_interval = log_interval];
239            if no_loops {
240                let sorted =
241                    webgraph::transform::symmetrize_seq::<true>($graph, memory_usage, &mut pl)?;
242                let mut builder = builder.progress_logger(&mut pl);
243                thread_pool.install(|| par_comp!(builder, sorted, target_endianness))
244            } else {
245                let sorted =
246                    webgraph::transform::symmetrize_seq::<false>($graph, memory_usage, &mut pl)?;
247                let mut builder = builder.progress_logger(&mut pl);
248                thread_pool.install(|| par_comp!(builder, sorted, target_endianness))
249            }
250        }};
251    }
252
253    match (args.permutation, args.transpose) {
254        (None, Some(t_path)) => {
255            log::info!("Transposed graph provided, using it to symmetrize the graph");
256            compress_union!(
257                BvGraphSeq::with_basename(&args.src)
258                    .endianness::<E>()
259                    .load()?,
260                BvGraphSeq::with_basename(&t_path)
261                    .endianness::<E>()
262                    .load()?,
263                no_loops,
264                builder,
265                thread_pool,
266                target_endianness,
267                log_interval
268            );
269        }
270        (Some(perm_path), None | Some(_)) => {
271            log::info!("Permutation provided, applying it to the graph");
272
273            let loaded = args.fmt.load(perm_path)?;
274
275            dispatch_int_slice!(loaded, |perm| {
276                let seq_graph = BvGraphSeq::with_basename(&args.src)
277                    .endianness::<E>()
278                    .load()?;
279                symmetrize_and_compress!(&PermutedGraph::new(&seq_graph, perm))
280            })?;
281        }
282        (None, None) => {
283            log::info!(
284                "No permutation or transposed graph provided, computing the transpose on the fly"
285            );
286
287            let seq_graph = BvGraphSeq::with_basename(&args.src)
288                .endianness::<E>()
289                .load()?;
290            symmetrize_and_compress!(&seq_graph)?;
291        }
292    }
293
294    Ok(())
295}