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 Sebastiano Vigna
 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
 *
 * SPDX-License-Identifier: Apache-2.0 OR MIT
 */

use crate::{IntSlice, IntSliceFormat, LogIntervalArg, create_parent_dir};
use anyhow::{Result, ensure};
use clap::Parser;
use dsi_progress_logger::prelude::*;
use std::path::PathBuf;
use sux::bits::BitVec;
use sux::traits::{BitVecOps, BitVecOpsMut};
use value_traits::slices::SliceByValue;

#[derive(Parser, Debug)]
#[command(name = "comp", about = "Composes multiple permutations into a single one.", long_about = None, next_line_help = true)]
pub struct CliArgs {
    /// The filename of the resulting permutation.​
    pub dst: PathBuf,

    #[arg(num_args(1..))]
    /// Filenames of the permutations to compose (in order of application).​
    pub perms: Vec<PathBuf>,

    #[arg(long, value_enum, default_value_t)]
    /// The format of the source permutation files.​
    pub src_fmt: IntSliceFormat,

    #[arg(long, value_enum, default_value_t)]
    /// The format of the destination permutation file.​
    pub dst_fmt: IntSliceFormat,

    #[arg(long)]
    /// Skip the check that each input is a permutation.
    pub no_check: bool,

    #[clap(flatten)]
    pub log_interval: LogIntervalArg,
}

fn compose<P: SliceByValue<Value = usize>>(
    perms: &[&P],
    len: usize,
    pl: &mut ProgressLogger,
) -> Vec<usize> {
    let mut merged = Vec::with_capacity(len);
    pl.start("Combining permutations...");
    for i in 0..len {
        let mut v = i;
        for p in perms {
            v = p.index_value(v);
        }
        merged.push(v);
        pl.light_update();
    }
    pl.done();
    merged
}

pub fn main(args: CliArgs) -> Result<()> {
    create_parent_dir(&args.dst)?;

    let mut pl = progress_logger![
        display_memory = true,
        item_name = "indices",
        log_interval = args.log_interval.log_interval
    ];

    let mut perms: Vec<IntSlice> = Vec::new();
    for path in &args.perms {
        perms.push(args.src_fmt.load(path)?);
    }

    let len = perms[0].len();
    ensure!(
        perms.iter().all(|p| p.len() == len),
        "All permutations must have the same length"
    );

    // Verify that each input is a permutation of 0..len: a malformed file
    // would otherwise panic during composition (out-of-range values) or
    // silently produce a non-permutation (duplicate values). The check can
    // be skipped with --no-check.
    if !args.no_check {
        for (path, perm) in args.perms.iter().zip(&perms) {
            let mut seen: BitVec = BitVec::new(len);
            for i in 0..len {
                let v = perm.index_value(i);
                ensure!(
                    v < len,
                    "{} is not a permutation: value {v} at position {i} is out of range",
                    path.display()
                );
                ensure!(
                    !seen.get(v),
                    "{} is not a permutation: value {v} at position {i} is a duplicate",
                    path.display()
                );
                seen.set(v, true);
            }
        }
    }
    pl.expected_updates(len);

    // Dispatch on the concrete type for static dispatch in the composition
    // loop. All perms share the same variant since they are loaded with the
    // same src_fmt.
    macro_rules! compose_as {
        ($variant:ident, |$x:ident| $inner:expr) => {{
            let refs: Vec<_> = perms
                .iter()
                .map(|p| {
                    let IntSlice::$variant($x) = p else {
                        unreachable!()
                    };
                    $inner
                })
                .collect();
            compose(&refs, len, &mut pl)
        }};
    }
    let merged = match &perms[0] {
        IntSlice::Owned(_) => compose_as!(Owned, |v| v),
        #[cfg(target_pointer_width = "64")]
        IntSlice::Java(_) => compose_as!(Java, |j| j),
        IntSlice::Epserde(_) => compose_as!(Epserde, |m| m.uncase()),
        IntSlice::BitFieldVec(_) => compose_as!(BitFieldVec, |m| m.uncase()),
    };

    args.dst_fmt.store(&args.dst, &merged, None)?;

    Ok(())
}