Skip to main content

webgraph_cli/perm/
comp.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
3 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
4 *
5 * SPDX-License-Identifier: Apache-2.0 OR MIT
6 */
7
8use crate::{IntSlice, IntSliceFormat, LogIntervalArg, create_parent_dir};
9use anyhow::{Result, ensure};
10use clap::Parser;
11use dsi_progress_logger::prelude::*;
12use std::path::PathBuf;
13use sux::bits::BitVec;
14use sux::traits::{BitVecOps, BitVecOpsMut};
15use value_traits::slices::SliceByValue;
16
17#[derive(Parser, Debug)]
18#[command(name = "comp", about = "Composes multiple permutations into a single one.", long_about = None, next_line_help = true)]
19pub struct CliArgs {
20    /// The filename of the resulting permutation.​
21    pub dst: PathBuf,
22
23    #[arg(num_args(1..))]
24    /// Filenames of the permutations to compose (in order of application).​
25    pub perms: Vec<PathBuf>,
26
27    #[arg(long, value_enum, default_value_t)]
28    /// The format of the source permutation files.​
29    pub src_fmt: IntSliceFormat,
30
31    #[arg(long, value_enum, default_value_t)]
32    /// The format of the destination permutation file.​
33    pub dst_fmt: IntSliceFormat,
34
35    #[arg(long)]
36    /// Skip the check that each input is a permutation.
37    pub no_check: bool,
38
39    #[clap(flatten)]
40    pub log_interval: LogIntervalArg,
41}
42
43fn compose<P: SliceByValue<Value = usize>>(
44    perms: &[&P],
45    len: usize,
46    pl: &mut ProgressLogger,
47) -> Vec<usize> {
48    let mut merged = Vec::with_capacity(len);
49    pl.start("Combining permutations...");
50    for i in 0..len {
51        let mut v = i;
52        for p in perms {
53            v = p.index_value(v);
54        }
55        merged.push(v);
56        pl.light_update();
57    }
58    pl.done();
59    merged
60}
61
62pub fn main(args: CliArgs) -> Result<()> {
63    create_parent_dir(&args.dst)?;
64
65    let mut pl = progress_logger![
66        display_memory = true,
67        item_name = "indices",
68        log_interval = args.log_interval.log_interval
69    ];
70
71    let mut perms: Vec<IntSlice> = Vec::new();
72    for path in &args.perms {
73        perms.push(args.src_fmt.load(path)?);
74    }
75
76    let len = perms[0].len();
77    ensure!(
78        perms.iter().all(|p| p.len() == len),
79        "All permutations must have the same length"
80    );
81
82    // Verify that each input is a permutation of 0..len: a malformed file
83    // would otherwise panic during composition (out-of-range values) or
84    // silently produce a non-permutation (duplicate values). The check can
85    // be skipped with --no-check.
86    if !args.no_check {
87        for (path, perm) in args.perms.iter().zip(&perms) {
88            let mut seen: BitVec = BitVec::new(len);
89            for i in 0..len {
90                let v = perm.index_value(i);
91                ensure!(
92                    v < len,
93                    "{} is not a permutation: value {v} at position {i} is out of range",
94                    path.display()
95                );
96                ensure!(
97                    !seen.get(v),
98                    "{} is not a permutation: value {v} at position {i} is a duplicate",
99                    path.display()
100                );
101                seen.set(v, true);
102            }
103        }
104    }
105    pl.expected_updates(len);
106
107    // Dispatch on the concrete type for static dispatch in the composition
108    // loop. All perms share the same variant since they are loaded with the
109    // same src_fmt.
110    macro_rules! compose_as {
111        ($variant:ident, |$x:ident| $inner:expr) => {{
112            let refs: Vec<_> = perms
113                .iter()
114                .map(|p| {
115                    let IntSlice::$variant($x) = p else {
116                        unreachable!()
117                    };
118                    $inner
119                })
120                .collect();
121            compose(&refs, len, &mut pl)
122        }};
123    }
124    let merged = match &perms[0] {
125        IntSlice::Owned(_) => compose_as!(Owned, |v| v),
126        #[cfg(target_pointer_width = "64")]
127        IntSlice::Java(_) => compose_as!(Java, |j| j),
128        IntSlice::Epserde(_) => compose_as!(Epserde, |m| m.uncase()),
129        IntSlice::BitFieldVec(_) => compose_as!(BitFieldVec, |m| m.uncase()),
130    };
131
132    args.dst_fmt.store(&args.dst, &merged, None)?;
133
134    Ok(())
135}