webgraph-cli 0.5.0

Command line interface for the Rust port of the WebGraph framework (http://webgraph.di.unimi.it/).
Documentation
/*
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
 * SPDX-FileCopyrightText: 2026 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 */

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 {
    /// The basename of the graph.​
    pub basename: PathBuf,

    #[arg(long, default_value_t = '\t')]
    /// The separator between source and target nodes.​
    pub separator: char,

    #[arg(long)]
    /// A file containing one label per line (the first line is the label of
    /// node 0). The ".nodes" file generated by "from arcs" is compatible.​
    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 {
        // Split on newlines rather than using lines(): the file written by
        // 'from arcs --labels' terminates every label with a newline, and an
        // empty label on the last line must not be lost.
        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
    };

    // read the csv and put it inside the sort pairs
    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(())
}