Skip to main content

webgraph_cli/check/
symm.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;
10use dsi_bitstream::prelude::*;
11use dsi_progress_logger::prelude::*;
12use lender::prelude::*;
13use std::path::PathBuf;
14use std::process::exit;
15use webgraph::prelude::*;
16
17#[derive(Parser, Debug)]
18#[command(
19    name = "symm",
20    about = "Checks that a graph is symmetric (AKA undirected).",
21    long_about = "Checks that a graph is symmetric (AKA undirected) by comparing it with its transpose, computed on the fly using parallel sorting. Optionally checks for the absence of loops.",
22    next_line_help = true
23)]
24pub struct CliArgs {
25    /// The basename of the graph.​
26    pub basename: PathBuf,
27
28    #[arg(long)]
29    /// Also check that the graph has no loops (i.e., that the graph is simple).​
30    pub simple: bool,
31
32    #[clap(flatten)]
33    pub num_threads: NumThreadsArg,
34
35    #[clap(flatten)]
36    pub memory_usage: MemoryUsageArg,
37
38    #[clap(flatten)]
39    pub log_interval: LogIntervalArg,
40}
41
42pub fn main(args: CliArgs) -> Result<()> {
43    dispatch_endianness!(&args.basename, |E| check_symm::<E>(args))
44}
45
46pub fn check_symm<E: Endianness>(args: CliArgs) -> Result<()>
47where
48    MmapHelper<u32>: CodesReaderFactoryHelper<E>,
49    for<'a> LoadModeCodesReader<'a, E, Mmap>: BitSeek + Clone + Send + Sync,
50{
51    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
52
53    let has_ef =
54        std::fs::metadata(args.basename.with_extension(EF_EXTENSION)).is_ok_and(|x| x.is_file());
55
56    if !has_ef {
57        log::warn!(SEQ_PROC_WARN![], args.basename.display());
58    }
59
60    let check_simple = args.simple;
61
62    if has_ef {
63        let graph =
64            webgraph::graphs::bvgraph::random_access::BvGraph::with_basename(&args.basename)
65                .endianness::<E>()
66                .load()?;
67
68        // Transpose the graph in parallel and compare
69        thread_pool.install(|| {
70            let mut pl = progress_logger![
71                display_memory = true,
72                log_interval = args.log_interval.log_interval
73            ];
74            let transposed = webgraph::transform::transpose_par(
75                &graph,
76                args.memory_usage.memory_usage,
77                &mut pl,
78            )?;
79            compare(&graph, &transposed, check_simple)
80        })
81    } else {
82        let graph =
83            webgraph::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.basename)
84                .endianness::<E>()
85                .load()?;
86
87        // Transpose sequentially
88        let mut pl = progress_logger![
89            display_memory = true,
90            log_interval = args.log_interval.log_interval
91        ];
92        let transposed =
93            webgraph::transform::transpose_seq(graph, args.memory_usage.memory_usage, &mut pl)?;
94
95        // Reload the graph for comparison (transpose consumed it)
96        let graph =
97            webgraph::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.basename)
98                .endianness::<E>()
99                .load()?;
100
101        compare(&graph, &transposed, check_simple)
102    }
103}
104
105/// Compares a graph with its transpose, checking for symmetry and optionally
106/// for the absence of self-loops.
107fn compare<G0, G1>(graph: &G0, transpose: &G1, check_simple: bool) -> Result<()>
108where
109    G0: SequentialGraph,
110    G1: SequentialGraph,
111    for<'a> G0::Lender<'a>: SortedLender,
112    for<'a> G1::Lender<'a>: SortedLender,
113{
114    if check_simple {
115        log::info!("Checking symmetry and absence of self-loops...");
116    } else {
117        log::info!("Checking symmetry...");
118    }
119
120    if graph.num_nodes() != transpose.num_nodes() {
121        eprintln!(
122            "Number of nodes differ: {} vs {}",
123            graph.num_nodes(),
124            transpose.num_nodes()
125        );
126        exit(1);
127    }
128
129    let mut g_iter = graph.iter();
130    let mut t_iter = transpose.iter();
131
132    while let Some((node, succ)) = g_iter.next() {
133        let (_t_node, t_succ) = t_iter.next().expect("transposed graph has fewer nodes");
134
135        let mut s_iter = succ.into_iter();
136        let mut t_s_iter = t_succ.into_iter();
137
138        loop {
139            match (s_iter.next(), t_s_iter.next()) {
140                (Some(s), Some(t)) => {
141                    if check_simple && s == node {
142                        eprintln!("Node {} has a self-loop", node);
143                        exit(1);
144                    }
145                    if s != t {
146                        eprintln!(
147                            "Graph is not symmetric: node {} has successor {} but transpose has {}",
148                            node, s, t
149                        );
150                        exit(1);
151                    }
152                }
153                (None, None) => break,
154                (Some(_), None) => {
155                    eprintln!(
156                        "Graph is not symmetric: node {} has more successors than its transpose",
157                        node
158                    );
159                    exit(1);
160                }
161                (None, Some(_)) => {
162                    eprintln!(
163                        "Graph is not symmetric: node {} has fewer successors than its transpose",
164                        node
165                    );
166                    exit(1);
167                }
168            }
169        }
170    }
171
172    log::info!("Graph is symmetric.");
173    if check_simple {
174        log::info!("Graph has no self-loops.");
175    }
176    Ok(())
177}