Skip to main content

webgraph_cli/from/
arcs.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::create_parent_dir;
10use crate::*;
11use anyhow::{Context, Result};
12use clap::Parser;
13use dsi_bitstream::prelude::BE;
14use dsi_progress_logger::prelude::*;
15use rayon::prelude::ParallelSliceMut;
16use std::collections::HashMap;
17use std::io::{BufRead, Write};
18use std::path::PathBuf;
19use webgraph::prelude::*;
20
21#[derive(Parser, Debug)]
22#[command(
23    about = "Reads a list of arcs from standard input and creates a graph in the BV format.",
24    long_about = "Reads a list of arcs from standard input and creates a graph in the BV format. Each arc is \
25        a pair of numeric node identifiers separated by a TAB (but the format is \
26        customizable). If --labels is used, source and target values are treated \
27        as string labels: numerical identifiers will be assigned in appearance \
28        order, and the final list of labels will be saved in a file with the same \
29        basename as the graph and extension .nodes. Without --labels, nodes are \
30        numbered starting from zero.",
31    next_line_help = true
32)]
33pub struct CliArgs {
34    /// The basename of the graph.​
35    pub dst: PathBuf,
36
37    #[arg(long)]
38    /// The number of nodes in the graph.​
39    pub num_nodes: usize,
40
41    #[arg(long)]
42    /// The number of arcs in the graph; if specified, it will be used to
43    /// estimate the progress.​
44    pub num_arcs: Option<usize>,
45
46    #[clap(flatten)]
47    pub arcs_args: ArcsArgs,
48
49    #[clap(flatten)]
50    pub num_threads: NumThreadsArg,
51
52    #[clap(flatten)]
53    pub memory_usage: MemoryUsageArg,
54
55    #[clap(flatten)]
56    pub ca: CompressArgs,
57
58    #[clap(flatten)]
59    pub log_interval: LogIntervalArg,
60}
61
62pub fn main(args: CliArgs) -> Result<()> {
63    log::info!("Reading arcs from stdin...");
64    let stdin = std::io::stdin().lock();
65    from_csv(args, stdin)
66}
67
68pub fn from_csv(args: CliArgs, file: impl BufRead) -> Result<()> {
69    let num_nodes = args.num_nodes;
70
71    let labels = args.arcs_args.labels;
72    let separator = args.arcs_args.separator;
73    let source_column = args.arcs_args.source_column;
74    let target_column = args.arcs_args.target_column;
75    let comment = args.arcs_args.line_comment_symbol;
76    let max_arcs = args.arcs_args.max_arcs;
77    let biggest_idx = source_column.max(target_column);
78
79    let mut nodes = HashMap::new();
80    let mut num_arcs = 0usize;
81    let mut parse_error: Option<anyhow::Error> = None;
82
83    let mut lines = file.lines();
84    let mut lines_to_skip = args.arcs_args.lines_to_skip;
85    let mut line_count = 0usize;
86
87    let pairs = std::iter::from_fn(|| {
88        loop {
89            if parse_error.is_some() {
90                return None;
91            }
92            if max_arcs.is_some_and(|m| num_arcs >= m) {
93                return None;
94            }
95            let line = match lines.next()? {
96                Ok(l) => l,
97                Err(e) => {
98                    parse_error = Some(e.into());
99                    return None;
100                }
101            };
102            line_count += 1;
103
104            if line.trim().starts_with(comment) {
105                continue;
106            }
107
108            // Skipped lines are counted after ignoring comment lines, as
109            // documented.
110            if lines_to_skip > 0 {
111                lines_to_skip -= 1;
112                continue;
113            }
114
115            let vals = line.split(separator).collect::<Vec<_>>();
116            if vals.get(biggest_idx).is_none() {
117                log::warn!(
118                    "Line {}: {:?} does not have enough columns: got {} columns \
119                     but expected at least {} columns separated by {:?} \
120                     (you can change the separator using the --separator option)",
121                    line_count,
122                    line,
123                    vals.len(),
124                    biggest_idx + 1,
125                    separator,
126                );
127                continue;
128            }
129
130            let src = vals[source_column];
131            let dst = vals[target_column];
132
133            let src_id = if labels {
134                let node_id = nodes.len();
135                *nodes.entry(src.to_string()).or_insert(node_id)
136            } else {
137                match src.parse::<usize>() {
138                    Ok(v) => v,
139                    Err(_) => {
140                        parse_error = Some(anyhow::anyhow!(
141                            "Error parsing as integer source column value {:?} at line {}",
142                            src,
143                            line_count
144                        ));
145                        return None;
146                    }
147                }
148            };
149
150            let dst_id = if labels {
151                let node_id = nodes.len();
152                *nodes.entry(dst.to_string()).or_insert(node_id)
153            } else {
154                match dst.parse::<usize>() {
155                    Ok(v) => v,
156                    Err(_) => {
157                        parse_error = Some(anyhow::anyhow!(
158                            "Error parsing as integer target column value {:?} at line {}",
159                            dst,
160                            line_count
161                        ));
162                        return None;
163                    }
164                }
165            };
166
167            num_arcs += 1;
168            return Some((src_id, dst_id));
169        }
170    });
171
172    // Sort and partition arcs for parallel compression
173    let conf = ParSortedGraph::config()
174        .dedup()
175        .memory_usage(args.memory_usage.memory_usage);
176    let sorted = conf.sort_pairs(num_nodes, pairs)?;
177
178    if let Some(e) = parse_error {
179        return Err(e);
180    }
181
182    log::info!("Arcs read: {} Nodes: {}", num_arcs, num_nodes);
183    if num_arcs == 0 {
184        anyhow::bail!(
185            "No arcs read from the input! Check that the --separator={:?} value is correct \
186             and that the --source-column={:?} and --target-column={:?} values are correct.",
187            separator,
188            source_column,
189            target_column
190        );
191    }
192
193    create_parent_dir(&args.dst)?;
194
195    // Compress
196    let target_endianness = args.ca.target_endianness::<BE>();
197    let thread_pool = crate::get_thread_pool(args.num_threads.num_threads);
198    let mut pl_comp = progress_logger![
199        display_memory = true,
200        log_interval = args.log_interval.log_interval
201    ];
202    let mut builder = args
203        .ca
204        .bv_comp_conf(&args.dst)
205        .progress_logger(&mut pl_comp);
206    thread_pool.install(|| par_comp!(builder, sorted, target_endianness))?;
207
208    // Save the label-to-node-id mapping
209    if labels {
210        let nodes_file = args.dst.with_extension("nodes");
211        let mut pl = progress_logger![
212            display_memory = true,
213            item_name = "lines",
214            log_interval = args.log_interval.log_interval
215        ];
216
217        let mut file = std::fs::File::create(&nodes_file)
218            .with_context(|| format!("Could not create {}", nodes_file.display()))?;
219        let mut buf = std::io::BufWriter::new(&mut file);
220        let mut nodes = nodes.into_iter().collect::<Vec<_>>();
221        thread_pool.install(|| nodes.par_sort_by(|(_, a), (_, b)| a.cmp(b)));
222        pl.start(format!("Storing the nodes to {}...", nodes_file.display()));
223        for (node, _) in nodes {
224            buf.write_all(node.as_bytes())
225                .with_context(|| format!("Could not write to {}", nodes_file.display()))?;
226            buf.write_all(b"\n")
227                .with_context(|| format!("Could not write to {}", nodes_file.display()))?;
228            pl.light_update();
229        }
230        pl.done();
231    }
232    Ok(())
233}