1use crate::LogIntervalArg;
10use anyhow::Result;
11use clap::Parser;
12use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
13use dsi_bitstream::prelude::*;
14use dsi_progress_logger::prelude::*;
15use lender::*;
16use std::io::Write;
17use std::path::PathBuf;
18use webgraph::traits::SequentialLabeling;
19use webgraph::utils::MmapHelper;
20
21#[derive(Parser, Debug)]
22#[command(
23 name = "arcs",
24 about = "Writes a graph in ASCII to standard output as a list of arcs.",
25 long_about = "Writes a graph in ASCII to standard output as a list of arcs. Each arc comprises a pair of nodes separated by a TAB (but the format is customizable). By default, nodes are written as numerical identifiers. The --labels option accepts a file containing the label of each node (the first string is the label of node 0, the second of node 1, and so on). The \".nodes\" file created by \"from arcs\" is compatible with --labels.",
26 next_line_help = true
27)]
28pub struct CliArgs {
29 pub basename: PathBuf,
31
32 #[arg(long, default_value_t = '\t')]
33 pub separator: char,
35
36 #[arg(long)]
37 pub labels: Option<PathBuf>,
40
41 #[clap(flatten)]
42 pub log_interval: LogIntervalArg,
43}
44
45pub fn main(args: CliArgs) -> Result<()> {
46 dispatch_endianness!(&args.basename, |E| to_csv::<E>(args))
47}
48
49pub fn to_csv<E: Endianness + 'static>(args: CliArgs) -> Result<()>
50where
51 MmapHelper<u32>: CodesReaderFactoryHelper<E>,
52{
53 let graph = webgraph::graphs::bvgraph::sequential::BvGraphSeq::with_basename(args.basename)
54 .endianness::<E>()
55 .load()?;
56 let num_nodes = graph.num_nodes();
57
58 let labels = if let Some(labels) = args.labels {
59 let mut content = std::fs::read_to_string(labels)?;
63 if content.ends_with('\n') {
64 content.pop();
65 }
66 Some(
67 content
68 .split('\n')
69 .map(|l| l.to_string())
70 .collect::<Vec<_>>(),
71 )
72 } else {
73 None
74 };
75
76 let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
78 let mut pl = progress_logger![
79 display_memory = true,
80 item_name = "nodes",
81 expected_updates = Some(num_nodes),
82 log_interval = args.log_interval.log_interval,
83 ];
84
85 pl.start("Reading BvGraph...");
86
87 if let Some(labels) = labels {
88 anyhow::ensure!(
89 labels.len() >= num_nodes,
90 "Labels file has {} lines but the graph has {} nodes",
91 labels.len(),
92 num_nodes
93 );
94 for_! ( (src, succ) in graph.iter() {
95 for dst in succ {
96 writeln!(stdout, "{}{}{}", labels[src], args.separator, labels[dst])?;
97 }
98 pl.light_update();
99 });
100 } else {
101 for_! ( (src, succ) in graph.iter() {
102 for dst in succ {
103 writeln!(stdout, "{}{}{}", src, args.separator, dst)?;
104 }
105 pl.light_update();
106 });
107 }
108
109 pl.done();
110 Ok(())
111}