use crate::LogIntervalArg;
use anyhow::Result;
use clap::Parser;
use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
use dsi_bitstream::prelude::*;
use dsi_progress_logger::prelude::*;
use lender::*;
use std::io::Write;
use std::path::PathBuf;
use webgraph::traits::SequentialLabeling;
use webgraph::utils::MmapHelper;
#[derive(Parser, Debug)]
#[command(
name = "arcs",
about = "Writes a graph in ASCII to standard output as a list of arcs.",
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.",
next_line_help = true
)]
pub struct CliArgs {
pub basename: PathBuf,
#[arg(long, default_value_t = '\t')]
pub separator: char,
#[arg(long)]
pub labels: Option<PathBuf>,
#[clap(flatten)]
pub log_interval: LogIntervalArg,
}
pub fn main(args: CliArgs) -> Result<()> {
dispatch_endianness!(&args.basename, |E| to_csv::<E>(args))
}
pub fn to_csv<E: Endianness + 'static>(args: CliArgs) -> Result<()>
where
MmapHelper<u32>: CodesReaderFactoryHelper<E>,
{
let graph = webgraph::graphs::bvgraph::sequential::BvGraphSeq::with_basename(args.basename)
.endianness::<E>()
.load()?;
let num_nodes = graph.num_nodes();
let labels = if let Some(labels) = args.labels {
let mut content = std::fs::read_to_string(labels)?;
if content.ends_with('\n') {
content.pop();
}
Some(
content
.split('\n')
.map(|l| l.to_string())
.collect::<Vec<_>>(),
)
} else {
None
};
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
let mut pl = progress_logger![
display_memory = true,
item_name = "nodes",
expected_updates = Some(num_nodes),
log_interval = args.log_interval.log_interval,
];
pl.start("Reading BvGraph...");
if let Some(labels) = labels {
anyhow::ensure!(
labels.len() >= num_nodes,
"Labels file has {} lines but the graph has {} nodes",
labels.len(),
num_nodes
);
for_! ( (src, succ) in graph.iter() {
for dst in succ {
writeln!(stdout, "{}{}{}", labels[src], args.separator, labels[dst])?;
}
pl.light_update();
});
} else {
for_! ( (src, succ) in graph.iter() {
for dst in succ {
writeln!(stdout, "{}{}{}", src, args.separator, dst)?;
}
pl.light_update();
});
}
pl.done();
Ok(())
}