Skip to main content

webgraph_cli/
lib.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Inria
3 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
4 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR MIT
7 */
8
9#![doc = include_str!("../README.md")]
10#![deny(unstable_features)]
11#![deny(trivial_casts)]
12#![deny(unconditional_recursion)]
13#![deny(clippy::empty_loop)]
14#![deny(unreachable_code)]
15#![deny(unreachable_pub)]
16#![deny(unreachable_patterns)]
17#![deny(unused_macro_rules)]
18#![deny(unused_doc_comments)]
19#![allow(clippy::type_complexity)]
20
21use anyhow::{Context, Result, anyhow, bail, ensure};
22use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
23use dsi_bitstream::dispatch::Codes;
24use dsi_bitstream::traits::Endianness;
25use epserde::deser::{Deserialize, Flags, MemCase};
26use epserde::ser::Serialize;
27use num_traits::{FromBytes, ToBytes};
28use std::fmt::Display;
29use std::fs::File;
30use std::io::{BufRead, BufReader, BufWriter, Read, Write};
31use std::path::Path;
32use std::str::FromStr;
33use std::time::Duration;
34use std::time::SystemTime;
35use sux::bits::BitFieldVec;
36use sux::utils::PrimitiveUnsignedExt;
37use value_traits::slices::SliceByValue;
38use webgraph::graphs::par_graphs::ParGraph;
39#[cfg(target_pointer_width = "64")]
40use webgraph::prelude::JavaPermutation;
41use webgraph::prelude::{BvCompConf, CompFlags, DCF, DEG_CUMUL_EXTENSION, SequentialLabeling};
42use webgraph::traits::{IntoParLenders, NodeLabelsLender};
43use webgraph::utils::{Granularity, MemoryUsage};
44
45macro_rules! SEQ_PROC_WARN {
46    () => {"Processing the graph sequentially: for parallel processing please build the Elias–Fano offsets list using 'webgraph build ef {}'"}
47}
48
49#[cfg(not(any(feature = "le_bins", feature = "be_bins")))]
50compile_error!("At least one of the features `le_bins` or `be_bins` must be enabled.");
51
52/// Dispatches on the endianness of the graph with basename `$basename`,
53/// evaluating `$body` with `$E` bound to the corresponding [`Endianness`]
54/// type.
55///
56/// The enclosing function must return a [`Result`], as the macro returns an
57/// error if the endianness cannot be read or is not supported by the binary.
58///
59/// [`Endianness`]: dsi_bitstream::traits::Endianness
60macro_rules! dispatch_endianness {
61    ($basename:expr, |$E:ident| $body:expr) => {
62        match ::webgraph::prelude::get_endianness($basename)?.as_str() {
63            #[cfg(feature = "be_bins")]
64            e if e
65                == <::dsi_bitstream::traits::BE as ::dsi_bitstream::traits::Endianness>::NAME =>
66            {
67                type $E = ::dsi_bitstream::traits::BE;
68                $body
69            }
70            #[cfg(feature = "le_bins")]
71            e if e
72                == <::dsi_bitstream::traits::LE as ::dsi_bitstream::traits::Endianness>::NAME =>
73            {
74                type $E = ::dsi_bitstream::traits::LE;
75                $body
76            }
77            e => ::anyhow::bail!("Unknown endianness: {}", e),
78        }
79    };
80}
81
82/// Calls [`par_comp`] dispatching on a runtime endianness string.
83///
84/// The macro returns a [`Result`] with the output of the call if the endianness
85/// is recognized, and an error otherwise.
86///
87/// # Arguments
88///
89/// * `config` - the [`BvCompConf`] to call [`par_comp`] on;
90///
91/// * `graph` - an implementation of [`IntoParLenders`] with `Label = usize`;
92///
93/// * `endianness` - a string specifying the endianness type to use for the call;
94///   it must implement `AsRef<str>`, and must be equal to the name of one of the
95///   endianness types supported by the binary.
96///
97/// [`par_comp`]: webgraph::prelude::BvCompConf::par_comp
98/// [`BvCompConf`]: webgraph::prelude::BvCompConf
99/// [`IntoParLenders`]: webgraph::prelude::IntoParLenders
100#[macro_export]
101macro_rules! par_comp {
102    ($config:expr, $graph:expr, $endianness:expr) => {
103        // Dispatch to a helper function so that each endianness gets its
104        // own monomorphization without the `impl Trait` reference appearing
105        // in multiple arms of a single `match` (which would cause the
106        // borrow checker to require `'static`).
107        $crate::__par_comp_dispatch(&mut $config, $graph, $endianness.as_str())
108    };
109}
110
111/// Implementation detail of [`par_comp!`]. Dispatches to the correct
112/// endianness-specific [`par_comp`].
113///
114/// [`par_comp`]: webgraph::prelude::BvCompConf::par_comp
115pub fn __par_comp_dispatch<
116    PL: dsi_progress_logger::ProgressLog,
117    G: for<'a> IntoParLenders<ParLender: NodeLabelsLender<'a, Label = usize>>,
118>(
119    config: &mut webgraph::prelude::BvCompConf<PL>,
120    graph: G,
121    endianness: &str,
122) -> anyhow::Result<u64> {
123    use dsi_bitstream::prelude::Endianness;
124    #[cfg(feature = "be_bins")]
125    if endianness == dsi_bitstream::prelude::BE::NAME {
126        return config.par_comp::<dsi_bitstream::prelude::BE, _>(graph);
127    }
128    #[cfg(feature = "le_bins")]
129    if endianness == dsi_bitstream::prelude::LE::NAME {
130        return config.par_comp::<dsi_bitstream::prelude::LE, _>(graph);
131    }
132    anyhow::bail!("Unknown endianness: {}", endianness)
133}
134
135pub mod build_info {
136    include!(concat!(env!("OUT_DIR"), "/built.rs"));
137
138    pub fn version_string() -> String {
139        format!(
140            "{}
141git info: {} {} {}
142build info: built on {} for {} with {}",
143            PKG_VERSION,
144            GIT_VERSION.unwrap_or(""),
145            GIT_COMMIT_HASH.unwrap_or(""),
146            match GIT_DIRTY {
147                None => "",
148                Some(true) => "(dirty)",
149                Some(false) => "(clean)",
150            },
151            BUILD_DATE,
152            TARGET,
153            RUSTC_VERSION
154        )
155    }
156}
157
158/// Enum for instantaneous codes.
159///
160/// It is used to implement [`ValueEnum`] here instead of in [`dsi_bitstream`].
161///
162/// For CLI ergonomics and compatibility, these codes must be the same as those
163/// appearing in [`CompFlags::code_from_str`].​
164#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
165pub enum PrivCode {
166    Unary,
167    Gamma,
168    Delta,
169    Omega,
170    Zeta1,
171    Zeta2,
172    Zeta3,
173    Zeta4,
174    Zeta5,
175    Zeta6,
176    Zeta7,
177    Pi1,
178    Pi2,
179    Pi3,
180    Pi4,
181}
182
183impl From<PrivCode> for Codes {
184    fn from(value: PrivCode) -> Self {
185        match value {
186            PrivCode::Unary => Codes::Unary,
187            PrivCode::Gamma => Codes::Gamma,
188            PrivCode::Delta => Codes::Delta,
189            PrivCode::Omega => Codes::Omega,
190            PrivCode::Zeta1 => Codes::Zeta(1),
191            PrivCode::Zeta2 => Codes::Zeta(2),
192            PrivCode::Zeta3 => Codes::Zeta(3),
193            PrivCode::Zeta4 => Codes::Zeta(4),
194            PrivCode::Zeta5 => Codes::Zeta(5),
195            PrivCode::Zeta6 => Codes::Zeta(6),
196            PrivCode::Zeta7 => Codes::Zeta(7),
197            PrivCode::Pi1 => Codes::Pi(1),
198            PrivCode::Pi2 => Codes::Pi(2),
199            PrivCode::Pi3 => Codes::Pi(3),
200            PrivCode::Pi4 => Codes::Pi(4),
201        }
202    }
203}
204
205/// Shared CLI arguments for reading files containing arcs.​
206#[derive(Args, Debug)]
207pub struct ArcsArgs {
208    #[arg(long, default_value_t = '#')]
209    /// Ignore lines that start with this symbol.​
210    pub line_comment_symbol: char,
211
212    #[arg(long, default_value_t = 0)]
213    /// Number of lines to skip, ignoring comment lines.​
214    pub lines_to_skip: usize,
215
216    #[arg(long)]
217    /// Maximum number of lines to parse, after skipping and ignoring comment
218    /// lines.​
219    pub max_arcs: Option<usize>,
220
221    #[arg(long, default_value_t = '\t')]
222    /// The column separator.​
223    pub separator: char,
224
225    #[arg(long, default_value_t = 0)]
226    /// The index of the column containing the source node of an arc.​
227    pub source_column: usize,
228
229    #[arg(long, default_value_t = 1)]
230    /// The index of the column containing the target node of an arc.​
231    pub target_column: usize,
232
233    #[arg(long, default_value_t = false)]
234    /// Treat source and target values as string labels rather than numeric
235    /// node identifiers.​
236    pub labels: bool,
237}
238
239/// Parses the number of threads from a string.
240///
241/// This function is meant to be used with `#[arg(...,  value_parser =
242/// num_threads_parser)]`.
243pub fn num_threads_parser(arg: &str) -> Result<usize> {
244    let num_threads = arg.parse::<usize>()?;
245    ensure!(num_threads > 0, "Number of threads must be greater than 0");
246    Ok(num_threads)
247}
248
249/// Shared CLI arguments for commands that specify a number of threads.​
250#[derive(Args, Debug)]
251pub struct NumThreadsArg {
252    #[arg(short = 't', long, default_value_t = rayon::current_num_threads().max(1), value_parser = num_threads_parser)]
253    /// The number of threads to use.​
254    pub num_threads: usize,
255}
256
257/// Shared CLI arguments for commands that specify a granularity.​
258#[derive(Args, Debug)]
259pub struct GranularityArgs {
260    #[arg(long, conflicts_with("node_granularity"))]
261    /// The tentative number of arcs used to define the size of a parallel job
262    /// (advanced option).​
263    pub arc_granularity: Option<u64>,
264
265    #[arg(long, conflicts_with("arc_granularity"))]
266    /// The tentative number of nodes used to define the size of a parallel job
267    /// (advanced option).​
268    pub node_granularity: Option<usize>,
269}
270
271impl GranularityArgs {
272    pub fn into_granularity(&self) -> Granularity {
273        self.into_granularity_or(Granularity::default())
274    }
275
276    pub fn into_granularity_or(&self, default: Granularity) -> Granularity {
277        match (self.arc_granularity, self.node_granularity) {
278            (Some(_), Some(_)) => unreachable!(),
279            (Some(arc_granularity), None) => Granularity::Arcs(arc_granularity),
280            (None, Some(node_granularity)) => Granularity::Nodes(node_granularity),
281            (None, None) => default,
282        }
283    }
284}
285
286/// Shared CLI arguments for commands that specify a memory usage.
287///
288/// Accepts a plain number, a number with a suffix, a percentage, or the
289/// special value `auto`. If the value ends with `b` or `B` it is interpreted
290/// as a number of bytes; otherwise, it is interpreted as a number of
291/// elements. The available SI and NIST multipliers are k, M, G, T, P, ki,
292/// Mi, Gi, Ti, and Pi. A trailing `%` interprets the value as a percentage of
293/// the available memory. The value `auto` uses a non-linear formula that
294/// behaves like 50% of RAM on small machines but grows sub-linearly on large
295/// ones, capped at 1 TiB (256 MiB on 32-bit platforms); see
296/// [`MemoryUsage::default`] for details. The default is `auto`.​
297#[derive(Args, Debug)]
298pub struct MemoryUsageArg {
299    #[clap(short = 'm', long = "memory-usage", value_parser = memory_usage_parser, default_value = "auto")]
300    /// The memory usage for batches (a number of elements with an optional
301    /// SI/NIST suffix; append "b"/"B" for bytes, "%" for a percentage of
302    /// available memory, or "auto" for a non-linear default).​
303    pub memory_usage: MemoryUsage,
304}
305
306/// Formats for storing and loading slices of floats.​
307#[derive(Debug, Clone, Copy, Default, ValueEnum)]
308pub enum FloatSliceFormat {
309    /// Java-compatible format: a sequence of big-endian floats (32 or 64 bits).​
310    Java,
311    /// A sequence of floats (32 or 64 bits) serialized using ε-serde.​
312    Epserde,
313    /// ASCII format, one float per line.​
314    #[default]
315    Ascii,
316    /// A JSON array.​
317    Json,
318}
319
320impl FloatSliceFormat {
321    /// Stores a slice of floats in the specified `path` using the format defined by
322    /// `self`.
323    ///
324    /// If the result is a textual format, that is, ASCII or JSON, `precision`
325    /// will be used to round the float values to the specified number of
326    /// decimal digits. If `None`, [zmij] formatting will be used.
327    ///
328    /// [zmij]: https://crates.io/crates/zmij
329    pub fn store<F>(
330        &self,
331        path: impl AsRef<Path>,
332        values: &[F],
333        precision: Option<usize>,
334    ) -> Result<()>
335    where
336        F: ToBytes + Display + epserde::ser::Serialize + Copy + zmij::Float,
337        for<'a> &'a [F]: epserde::ser::Serialize,
338    {
339        let path = path.as_ref();
340        let path_display = path.display();
341        let mut file = create_file(path)?;
342
343        match self {
344            FloatSliceFormat::Epserde => store_epserde(values, &mut file, path)?,
345            FloatSliceFormat::Java => store_java(values, &mut file, path)?,
346            FloatSliceFormat::Ascii => {
347                log::info!("Storing in ASCII format at {}", path_display);
348                let mut buf = zmij::Buffer::new();
349                for word in values.iter() {
350                    match precision {
351                        None => writeln!(file, "{}", buf.format(*word)),
352                        Some(precision) => writeln!(file, "{word:.precision$}"),
353                    }
354                    .with_context(|| format!("Could not write slice to {}", path_display))?;
355                }
356            }
357            FloatSliceFormat::Json => {
358                log::info!("Storing in JSON format at {}", path_display);
359                let mut buf = zmij::Buffer::new();
360                write!(file, "[")?;
361                for word in values.iter().take(values.len().saturating_sub(1)) {
362                    match precision {
363                        None => write!(file, "{}, ", buf.format(*word)),
364                        Some(precision) => write!(file, "{word:.precision$}, "),
365                    }
366                    .with_context(|| format!("Could not write slice to {}", path_display))?;
367                }
368                if let Some(last) = values.last() {
369                    match precision {
370                        None => write!(file, "{}", buf.format(*last)),
371                        Some(precision) => write!(file, "{last:.precision$}"),
372                    }
373                    .with_context(|| format!("Could not write slice to {}", path_display))?;
374                }
375                write!(file, "]")?;
376            }
377        }
378
379        Ok(())
380    }
381
382    /// Loads float values from the specified `path` using the format defined
383    /// by `self`.
384    pub fn load<F>(&self, path: impl AsRef<Path>) -> Result<Vec<F>>
385    where
386        F: FromBytes + FromStr + Copy + serde::de::DeserializeOwned,
387        <F as FromBytes>::Bytes: for<'a> TryFrom<&'a [u8]>,
388        <F as FromStr>::Err: std::error::Error + Send + Sync + 'static,
389        Vec<F>: epserde::deser::Deserialize,
390    {
391        let path = path.as_ref();
392        let path_display = path.display();
393
394        match self {
395            FloatSliceFormat::Epserde => {
396                log::info!("Loading ε-serde format from {}", path_display);
397                Ok(unsafe {
398                    <Vec<F>>::load_full(path)
399                        .with_context(|| format!("Could not load slice from {}", path_display))?
400                })
401            }
402            FloatSliceFormat::Java => {
403                log::info!("Loading Java format from {}", path_display);
404                let file = std::fs::File::open(path)
405                    .with_context(|| format!("Could not open {}", path_display))?;
406                let file_len = file.metadata()?.len() as usize;
407                let byte_size = size_of::<F>();
408                ensure!(
409                    file_len % byte_size == 0,
410                    "File size ({}) is not a multiple of {} bytes",
411                    file_len,
412                    byte_size
413                );
414                let n = file_len / byte_size;
415                let mut reader = BufReader::new(file);
416                let mut result = Vec::with_capacity(n);
417                let mut buf = vec![0u8; byte_size];
418                for i in 0..n {
419                    reader.read_exact(&mut buf).with_context(|| {
420                        format!("Could not read value at index {i} from {}", path_display)
421                    })?;
422                    let bytes = buf.as_slice().try_into().map_err(|_| {
423                        anyhow!("Could not convert bytes at index {i} in {}", path_display)
424                    })?;
425                    result.push(F::from_be_bytes(&bytes));
426                }
427                Ok(result)
428            }
429            FloatSliceFormat::Ascii => load_ascii(path),
430            FloatSliceFormat::Json => load_json(path),
431        }
432    }
433}
434
435/// How to store slices of integers.​
436#[derive(Debug, Clone, Copy, Default, ValueEnum)]
437pub enum IntSliceFormat {
438    #[cfg(target_pointer_width = "64")]
439    /// Java-compatible format: a sequence of big-endian 64-bit integers; available only on 64-bit platforms.​
440    Java,
441    /// A sequence of usize serialized using ε-serde.​
442    Epserde,
443    /// A BitFieldVec stored using ε-serde: it stores each element using
444    /// ⌊log₂(max)⌋ + 1 bits, and it requires to allocate the `BitFieldVec` in RAM
445    /// before serializing it.​
446    BitFieldVec,
447    /// ASCII format, one integer per line.​
448    #[default]
449    Ascii,
450    /// A JSON array.​
451    Json,
452}
453
454/// Loaded integer slice, returned by [`IntSliceFormat::load`].
455///
456/// Depending on the format, the data may be backed by a memory-mapped file
457/// (Java, ε-serde, and [`BitFieldVec`]) or fully loaded into memory (ASCII,
458/// JSON).
459///
460/// This enum implements [`SliceByValue`] with `Value = usize`, so it can
461/// be used directly wherever a [`SliceByValue`] is expected. However, each
462/// access goes through enum dispatch, which may be undesirable in
463/// performance-critical code.
464///
465/// For native, dispatch-free access, match on the variants and use each
466/// inner type directly—they all implement [`SliceByValue<Value = usize>`]:
467///
468/// ```ignore
469/// match args.fmt.load(&path)? {
470///     IntSlice::Owned(v) => do_transform(&v, ...),
471///     IntSlice::Java(j) => do_transform(&j, ...),
472///     IntSlice::Epserde(m) => do_transform(m.uncase(), ...),
473///     IntSlice::BitFieldVec(m) => do_transform(m.uncase(), ...),
474/// }
475/// ```
476///
477/// This incurs one monomorphization of `do_transform` per arm; arms that
478/// share the same inner type can be merged to reduce monomorphization cost.
479pub enum IntSlice {
480    /// Fully loaded into memory (ASCII, JSON).
481    Owned(Box<[usize]>),
482    #[cfg(target_pointer_width = "64")]
483    /// Memory-mapped Java big-endian format (64-bit only).
484    Java(JavaPermutation),
485    /// Memory-mapped ε-serde serialized slice.
486    Epserde(MemCase<Box<[usize]>>),
487    /// Memory-mapped ε-serde serialized [`BitFieldVec`].
488    BitFieldVec(MemCase<sux::bits::BitFieldVec>),
489}
490
491impl SliceByValue for IntSlice {
492    type Value = usize;
493
494    unsafe fn get_value_unchecked(&self, index: usize) -> usize {
495        match self {
496            IntSlice::Owned(v) => unsafe { *v.get_unchecked(index) },
497            #[cfg(target_pointer_width = "64")]
498            IntSlice::Java(j) => unsafe { j.get_value_unchecked(index) },
499            IntSlice::Epserde(m) => unsafe { *m.uncase().get_unchecked(index) },
500            IntSlice::BitFieldVec(m) => unsafe { m.uncase().get_value_unchecked(index) },
501        }
502    }
503
504    fn len(&self) -> usize {
505        match self {
506            IntSlice::Owned(v) => v.len(),
507            #[cfg(target_pointer_width = "64")]
508            IntSlice::Java(j) => j.len(),
509            IntSlice::Epserde(m) => m.uncase().len(),
510            IntSlice::BitFieldVec(m) => m.uncase().len(),
511        }
512    }
513}
514
515/// Dispatches on an [`IntSlice`], binding the concrete inner
516/// [`SliceByValue`] type to `$var` and evaluating `$body` for each variant.
517///
518/// The bound types are `&Box<[usize]>` (Owned and Epserde),
519/// `&JavaPermutation` (Java, 64-bit only), and `&BitFieldVec`
520/// (BitFieldVec). All bound types are `Sized`.
521#[macro_export]
522macro_rules! dispatch_int_slice {
523    ($slice:expr, |$var:ident| $body:expr) => {
524        match $slice {
525            $crate::IntSlice::Owned(ref __v) => {
526                let $var = __v;
527                $body
528            }
529            #[cfg(target_pointer_width = "64")]
530            $crate::IntSlice::Java(ref __j) => {
531                let $var = __j;
532                $body
533            }
534            $crate::IntSlice::Epserde(ref __m) => {
535                let $var = __m.uncase();
536                $body
537            }
538            $crate::IntSlice::BitFieldVec(ref __m) => {
539                let $var = __m.uncase();
540                $body
541            }
542        }
543    };
544}
545
546impl IntSliceFormat {
547    /// Stores a slice of `usize` in the specified `path` using the format
548    /// defined by `self`.
549    ///
550    /// `max` is the maximum value of the slice. If it is not provided, it will
551    /// be computed from the data.
552    pub fn store(&self, path: impl AsRef<Path>, data: &[usize], max: Option<usize>) -> Result<()> {
553        let mut buf = create_file(path.as_ref())?;
554
555        debug_assert_eq!(
556            max,
557            max.map(|_| { data.iter().copied().max().unwrap_or(0) }),
558            "The wrong maximum value was provided for the slice"
559        );
560
561        match self {
562            IntSliceFormat::Epserde => store_epserde(data, &mut buf, path.as_ref())?,
563            IntSliceFormat::BitFieldVec => {
564                log::info!(
565                    "Storing in BitFieldVec format at {}",
566                    path.as_ref().display()
567                );
568                let max = max.unwrap_or_else(|| {
569                    data.iter()
570                        .copied()
571                        .max()
572                        .unwrap_or_else(|| panic!("Empty slice"))
573                });
574                let bit_width = max.bit_len() as usize;
575                log::info!("Using {} bits per element", bit_width);
576                let mut bit_field_vec = BitFieldVec::with_capacity(bit_width, data.len());
577                bit_field_vec.extend(data.iter().copied());
578
579                unsafe {
580                    bit_field_vec.store(&path).with_context(|| {
581                        format!("Could not write slice to {}", path.as_ref().display())
582                    })
583                }?;
584            }
585            #[cfg(target_pointer_width = "64")]
586            IntSliceFormat::Java => store_java(data, &mut buf, path.as_ref())?,
587            IntSliceFormat::Ascii => {
588                log::info!("Storing in ASCII format at {}", path.as_ref().display());
589                for word in data.iter() {
590                    writeln!(buf, "{}", word).with_context(|| {
591                        format!("Could not write slice to {}", path.as_ref().display())
592                    })?;
593                }
594            }
595            IntSliceFormat::Json => {
596                log::info!("Storing in JSON format at {}", path.as_ref().display());
597                serde_json::to_writer(&mut buf, data).with_context(|| {
598                    format!("Could not write slice to {}", path.as_ref().display())
599                })?;
600            }
601        };
602
603        Ok(())
604    }
605
606    /// Loads integer values from the specified `path` using the format defined
607    /// by `self`, returning an [`IntSlice`].
608    ///
609    /// The ε-serde-based formats (Epserde, BitFieldVec) and the Java format
610    /// use memory mapping; ASCII and JSON are fully loaded into memory.
611    pub fn load(&self, path: impl AsRef<Path>) -> Result<IntSlice> {
612        let path = path.as_ref();
613        let path_display = path.display();
614
615        match self {
616            IntSliceFormat::Epserde => {
617                log::info!("Loading ε-serde format from {}", path_display);
618                let mem_case = unsafe {
619                    <Box<[usize]>>::mmap(path, Flags::RANDOM_ACCESS)
620                        .with_context(|| format!("Could not load slice from {}", path_display))?
621                };
622                Ok(IntSlice::Epserde(mem_case))
623            }
624            IntSliceFormat::BitFieldVec => {
625                log::info!("Loading BitFieldVec format from {}", path_display);
626                let mem_case = unsafe {
627                    <BitFieldVec>::mmap(path, Flags::RANDOM_ACCESS)
628                        .with_context(|| format!("Could not load slice from {}", path_display))?
629                };
630                Ok(IntSlice::BitFieldVec(mem_case))
631            }
632            #[cfg(target_pointer_width = "64")]
633            IntSliceFormat::Java => {
634                log::info!("Loading Java format from {}", path_display);
635                let perm = JavaPermutation::mmap(path, mmap_rs::MmapFlags::RANDOM_ACCESS)
636                    .with_context(|| format!("Could not load slice from {}", path_display))?;
637                Ok(IntSlice::Java(perm))
638            }
639            IntSliceFormat::Ascii => Ok(IntSlice::Owned(load_ascii(path)?.into())),
640            IntSliceFormat::Json => Ok(IntSlice::Owned(load_json(path)?.into())),
641        }
642    }
643}
644
645/// Creates a buffered file at `path`, creating also its parent directories.
646fn create_file(path: &Path) -> Result<BufWriter<File>> {
647    create_parent_dir(path)?;
648    let file = File::create(path)
649        .with_context(|| format!("Could not create slice at {}", path.display()))?;
650    Ok(BufWriter::new(file))
651}
652
653/// Stores a slice using ε-serde.
654fn store_epserde<T>(values: &[T], file: &mut BufWriter<File>, path: &Path) -> Result<()>
655where
656    for<'a> &'a [T]: Serialize,
657{
658    log::info!("Storing in ε-serde format at {}", path.display());
659    unsafe { values.serialize(file) }
660        .with_context(|| format!("Could not write slice to {}", path.display()))?;
661    Ok(())
662}
663
664/// Stores a slice in Java format (big-endian values).
665fn store_java<T: ToBytes>(values: &[T], file: &mut BufWriter<File>, path: &Path) -> Result<()> {
666    log::info!("Storing in Java format at {}", path.display());
667    for value in values {
668        file.write_all(value.to_be_bytes().as_ref())
669            .with_context(|| format!("Could not write slice to {}", path.display()))?;
670    }
671    Ok(())
672}
673
674/// Loads values from an ASCII file containing one value per line, skipping
675/// empty lines.
676fn load_ascii<T: FromStr>(path: &Path) -> Result<Vec<T>>
677where
678    T::Err: Display,
679{
680    log::info!("Loading ASCII format from {}", path.display());
681    let file = File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
682    BufReader::new(file)
683        .lines()
684        .enumerate()
685        .filter(|(_, line)| line.as_ref().map_or(true, |l| !l.trim().is_empty()))
686        .map(|(i, line)| {
687            let line = line
688                .with_context(|| format!("Error reading line {} of {}", i + 1, path.display()))?;
689            line.trim()
690                .parse::<T>()
691                .map_err(|e| anyhow!("Error parsing line {} of {}: {}", i + 1, path.display(), e))
692        })
693        .collect()
694}
695
696/// Loads values from a JSON array.
697fn load_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Vec<T>> {
698    log::info!("Loading JSON format from {}", path.display());
699    let file = File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
700    serde_json::from_reader(BufReader::new(file))
701        .with_context(|| format!("Could not parse JSON from {}", path.display()))
702}
703
704/// Parses a batch size.
705///
706/// This function accepts `auto` (which uses the non-linear default from
707/// [`MemoryUsage::default`]), a number (possibly followed by a SI or NIST
708/// multiplier k, M, G, T, P, ki, Mi, Gi, Ti, or Pi), or a percentage
709/// (followed by a `%`) that is interpreted as a percentage of the physical
710/// RAM. If the value ends with a `b` or `B` it is interpreted as a number of
711/// bytes, otherwise as a number of elements.
712pub fn memory_usage_parser(arg: &str) -> anyhow::Result<MemoryUsage> {
713    const PREF_SYMS: [(&str, u64); 10] = [
714        ("ki", 1 << 10),
715        ("mi", 1 << 20),
716        ("gi", 1 << 30),
717        ("ti", 1 << 40),
718        ("pi", 1 << 50),
719        ("k", 1E3 as u64),
720        ("m", 1E6 as u64),
721        ("g", 1E9 as u64),
722        ("t", 1E12 as u64),
723        ("p", 1E15 as u64),
724    ];
725    let arg = arg.trim().to_ascii_lowercase();
726    ensure!(!arg.is_empty(), "empty string");
727
728    if arg == "auto" {
729        return Ok(MemoryUsage::default());
730    }
731
732    if arg.ends_with('%') {
733        let perc = arg[..arg.len() - 1].parse::<f64>()?;
734        ensure!((0.0..=100.0).contains(&perc), "percentage out of range");
735        return Ok(MemoryUsage::from_perc(perc));
736    }
737
738    let num_digits = arg
739        .chars()
740        .take_while(|c| c.is_ascii_digit() || *c == '.')
741        .count();
742
743    let number = arg[..num_digits].parse::<f64>()?;
744    let suffix = &arg[num_digits..].trim();
745
746    if suffix.is_empty() {
747        let value = number as usize;
748        ensure!(value > 0, "batch size must be greater than zero");
749        return Ok(MemoryUsage::BatchSize(value));
750    }
751
752    let prefix = suffix.strip_suffix('b').unwrap_or(suffix);
753    let multiplier = PREF_SYMS
754        .iter()
755        .find(|(x, _)| *x == prefix)
756        .map(|(_, m)| m)
757        .ok_or(anyhow!("invalid suffix {}", suffix))?;
758
759    let value = (number * (*multiplier as f64)) as usize;
760    ensure!(value > 0, "batch size must be greater than zero");
761
762    if suffix.ends_with('b') {
763        Ok(MemoryUsage::MemorySize(value))
764    } else {
765        Ok(MemoryUsage::BatchSize(value))
766    }
767}
768
769/// Parses the value of `--max-ref-count`: a nonnegative integer, or -1 for
770/// an infinite recursion depth.
771pub fn max_ref_count_parser(arg: &str) -> anyhow::Result<isize> {
772    let value = arg.parse::<isize>()?;
773    ensure!(
774        value >= -1,
775        "the maximum reference count must be nonnegative, or -1 for infinite recursion depth"
776    );
777    Ok(value)
778}
779
780/// Shared CLI arguments for compression.​
781#[derive(Args, Debug, Clone)]
782pub struct CompressArgs {
783    /// The endianness of the graph to write [default: same as source].​
784    #[clap(short = 'E', long)]
785    pub endianness: Option<String>,
786
787    /// The compression window.​
788    #[clap(short = 'w', long, default_value_t = 7)]
789    pub compression_window: usize,
790    /// The minimum interval length.​
791    #[clap(short = 'i', long, default_value_t = 4)]
792    pub min_interval_length: usize,
793    /// The maximum recursion depth for references (-1 for infinite recursion depth).​
794    #[clap(short = 'r', long, default_value_t = 3, allow_hyphen_values = true, value_parser = max_ref_count_parser)]
795    pub max_ref_count: isize,
796
797    #[arg(value_enum)]
798    #[clap(long, default_value = "gamma")]
799    /// The code to use for outdegrees.​
800    pub outdegrees: PrivCode,
801
802    #[arg(value_enum)]
803    #[clap(long, default_value = "unary")]
804    /// The code to use for reference offsets.​
805    pub references: PrivCode,
806
807    #[arg(value_enum)]
808    #[clap(long, default_value = "gamma")]
809    /// The code to use for blocks.​
810    pub blocks: PrivCode,
811
812    #[arg(value_enum)]
813    #[clap(long, default_value = "zeta3")]
814    /// The code to use for residuals.​
815    pub residuals: PrivCode,
816
817    /// Use Zuckerli's reference selection algorithm (slower, more memory,
818    /// but better compression and decoding speed).​
819    #[clap(long)]
820    pub bvgraphz: bool,
821
822    /// Number of nodes per chunk with --bvgraphz.​
823    #[clap(long, default_value = "10000")]
824    pub chunk_size: usize,
825}
826
827impl CompressArgs {
828    /// Returns a [`BvCompConf`] writing a graph with basename `dst` using the
829    /// compression parameters specified by these arguments.
830    pub fn bv_comp_conf(&self, dst: impl AsRef<Path>) -> BvCompConf {
831        let conf = BvCompConf::new(dst).comp_flags(self.into());
832        if self.bvgraphz {
833            conf.chunk_size(self.chunk_size)
834        } else {
835            conf
836        }
837    }
838
839    /// Returns the name of the endianness of the graph to write: the one
840    /// specified by these arguments, if any, or that of `E`.
841    pub fn target_endianness<E: Endianness>(&self) -> String {
842        self.endianness.clone().unwrap_or_else(|| E::NAME.into())
843    }
844}
845
846impl From<CompressArgs> for CompFlags {
847    fn from(value: CompressArgs) -> Self {
848        (&value).into()
849    }
850}
851
852impl From<&CompressArgs> for CompFlags {
853    fn from(value: &CompressArgs) -> Self {
854        CompFlags {
855            outdegrees: value.outdegrees.into(),
856            references: value.references.into(),
857            blocks: value.blocks.into(),
858            intervals: PrivCode::Gamma.into(),
859            residuals: value.residuals.into(),
860            min_interval_length: value.min_interval_length,
861            compression_window: value.compression_window,
862            max_ref_count: match value.max_ref_count {
863                -1 => usize::MAX,
864                max_ref_count => {
865                    assert!(
866                        max_ref_count >= 0,
867                        "max_ref_count cannot be negative, except for -1, which means infinite recursion depth, but got {}",
868                        max_ref_count
869                    );
870                    value.max_ref_count as usize
871                }
872            },
873        }
874    }
875}
876
877/// Creates a [`ThreadPool`] with the given number of threads.
878///
879/// [`ThreadPool`]: rayon::ThreadPool
880pub fn get_thread_pool(num_threads: usize) -> rayon::ThreadPool {
881    let thread_pool = rayon::ThreadPoolBuilder::new()
882        .num_threads(num_threads)
883        .build()
884        .expect("Failed to create thread pool");
885    log::info!("Using {} threads", thread_pool.current_num_threads());
886    thread_pool
887}
888
889/// Creates all parent directories of the given file path.
890pub fn create_parent_dir(file_path: impl AsRef<Path>) -> Result<()> {
891    // ensure that the dst directory exists
892    if let Some(parent_dir) = file_path.as_ref().parent() {
893        std::fs::create_dir_all(parent_dir).with_context(|| {
894            format!(
895                "Failed to create the directory {:?}",
896                parent_dir.to_string_lossy()
897            )
898        })?;
899    }
900    Ok(())
901}
902
903/// Computes cutpoints for splitting a graph into `num_parts` chunks for
904/// parallel compression.
905///
906/// If `use_dcf` is true, loads the DCF file for the given basename and uses
907/// [`dcf_cutpoints`] to balance by arc count. Otherwise, falls back to
908/// [`uniform_cutpoints`] by node count.
909///
910/// [`dcf_cutpoints`]: webgraph::traits::split::dcf_cutpoints
911/// [`uniform_cutpoints`]: webgraph::traits::split::uniform_cutpoints
912pub fn cutpoints(
913    basename: &Path,
914    num_nodes: usize,
915    num_arcs: Option<u64>,
916    use_dcf: bool,
917    num_parts: usize,
918) -> Result<Vec<usize>> {
919    use webgraph::traits::split::{dcf_cutpoints, uniform_cutpoints};
920
921    if use_dcf {
922        let num_arcs = num_arcs.context("The number of arcs is required to use the DCF")?;
923        let dcf = load_dcf(basename, num_nodes, num_arcs)?;
924        let cutpoints = dcf_cutpoints(dcf.uncase(), num_parts);
925        log::info!(
926            "Using DCF-based splitting into {} parts",
927            cutpoints.len() - 1
928        );
929        Ok(cutpoints.into_vec())
930    } else {
931        let dcf_path = basename.with_extension(DEG_CUMUL_EXTENSION);
932        if dcf_path.exists() {
933            log::warn!(
934                "A DCF (degree cumulative function) file exists at {}; consider using --dcf for better load balancing",
935                dcf_path.display()
936            );
937        } else {
938            log::warn!(
939                "No DCF (degree cumulative function) file found; consider building one with `webgraph build dcf {}` for better load balancing",
940                basename.display()
941            );
942        }
943        Ok(uniform_cutpoints(num_nodes, num_parts).collect())
944    }
945}
946
947/// Wraps a graph in a [`ParGraph`] splitting it into `num_parts` parts using
948/// the [cutpoints] computed for the graph with given basename.
949///
950/// [`ParGraph`]: webgraph::graphs::par_graphs::ParGraph
951/// [cutpoints]: cutpoints
952pub fn par_graph<G: SequentialLabeling>(
953    graph: G,
954    basename: &Path,
955    use_dcf: bool,
956    num_parts: usize,
957) -> Result<ParGraph<G>> {
958    let cutpoints = cutpoints(
959        basename,
960        graph.num_nodes(),
961        graph.get_num_arcs(),
962        use_dcf,
963        num_parts,
964    )?;
965    Ok(ParGraph::with_cutpoints(graph, cutpoints))
966}
967
968/// Memory-maps the degree cumulative function (DCF) of the graph with given
969/// basename, checking that it is consistent with the given number of nodes and
970/// arcs.
971pub fn load_dcf(basename: &Path, num_nodes: usize, num_arcs: u64) -> Result<MemCase<DCF>> {
972    let dcf_path = basename.with_extension(DEG_CUMUL_EXTENSION);
973    ensure!(
974        dcf_path.exists(),
975        "DCF file {} does not exist; build it with `webgraph build dcf {}`",
976        dcf_path.display(),
977        basename.display()
978    );
979    let dcf = unsafe { DCF::mmap(&dcf_path, Flags::RANDOM_ACCESS) }
980        .with_context(|| format!("Could not load the DCF from {}", dcf_path.display()))?;
981    let values = dcf.uncase();
982    ensure!(
983        values.len() == num_nodes + 1,
984        "DCF has {} entries, expected {} (num_nodes + 1)",
985        values.len(),
986        num_nodes + 1
987    );
988    ensure!(values.index_value(0) == 0, "DCF does not start with 0");
989    ensure!(
990        values.index_value(num_nodes) == num_arcs,
991        "DCF ends with {}, expected {} (num_arcs)",
992        values.index_value(num_nodes),
993        num_arcs
994    );
995    Ok(dcf)
996}
997
998/// Parses a duration from a string.
999/// For compatibility with Java, if no suffix is given, it is assumed to be in milliseconds.
1000/// You can use suffixes, the available ones are:
1001/// - `s` for seconds
1002/// - `m` for minutes
1003/// - `h` for hours
1004/// - `d` for days
1005///
1006/// Example: `1d2h3m4s567` this is parsed as: 1 day, 2 hours, 3 minutes, 4 seconds, and 567 milliseconds.
1007fn parse_duration(value: &str) -> Result<Duration> {
1008    if value.is_empty() {
1009        bail!("Empty duration string, if you want every 0 milliseconds use `0`.");
1010    }
1011    let mut duration = Duration::from_secs(0);
1012    let mut acc = String::new();
1013    for c in value.chars() {
1014        if c.is_ascii_digit() {
1015            acc.push(c);
1016        } else if c.is_whitespace() {
1017            continue;
1018        } else {
1019            let dur = acc.parse::<u64>()?;
1020            match c {
1021                's' => duration += Duration::from_secs(dur),
1022                'm' => duration += Duration::from_secs(dur * 60),
1023                'h' => duration += Duration::from_secs(dur * 60 * 60),
1024                'd' => duration += Duration::from_secs(dur * 60 * 60 * 24),
1025                _ => return Err(anyhow!("Invalid duration suffix: {}", c)),
1026            }
1027            acc.clear();
1028        }
1029    }
1030    if !acc.is_empty() {
1031        let dur = acc.parse::<u64>()?;
1032        duration += Duration::from_millis(dur);
1033    }
1034    Ok(duration)
1035}
1036
1037/// Initializes the `env_logger` logger with a custom format including
1038/// timestamps with elapsed time since initialization.
1039pub fn init_env_logger() -> Result<()> {
1040    use jiff::SpanRound;
1041    use jiff::fmt::friendly::{Designator, Spacing, SpanPrinter};
1042
1043    let mut builder =
1044        env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"));
1045
1046    let start = std::time::Instant::now();
1047    let printer = SpanPrinter::new()
1048        .spacing(Spacing::None)
1049        .designator(Designator::Compact);
1050    let span_round = SpanRound::new()
1051        .largest(jiff::Unit::Day)
1052        .smallest(jiff::Unit::Millisecond)
1053        .days_are_24_hours();
1054
1055    builder.format(move |buf, record| {
1056        let Ok(ts) = jiff::Timestamp::try_from(SystemTime::now()) else {
1057            return Err(std::io::Error::other("Failed to get timestamp"));
1058        };
1059        let style = buf.default_level_style(record.level());
1060        let elapsed = start.elapsed();
1061        let span = jiff::Span::new()
1062            .seconds(elapsed.as_secs() as i64)
1063            .milliseconds(elapsed.subsec_millis() as i64);
1064        let span = span.round(span_round).expect("Failed to round span");
1065        writeln!(
1066            buf,
1067            "{} {} {style}{}{style:#} [{:?}] {} - {}",
1068            ts.strftime("%F %T%.3f"),
1069            printer.span_to_string(&span),
1070            record.level(),
1071            std::thread::current().id(),
1072            record.target(),
1073            record.args()
1074        )
1075    });
1076    builder.init();
1077    Ok(())
1078}
1079
1080/// Shared CLI arguments for commands that use a log interval.​
1081#[derive(Args, Debug, Clone)]
1082pub struct LogIntervalArg {
1083    #[arg(long, value_parser = parse_duration, default_value = "10s")]
1084    /// How often to log progress (default: 10s). Supported suffixes: "s"
1085    /// (seconds), "m" (minutes), "h" (hours), "d" (days). Without a suffix,
1086    /// the value is interpreted as milliseconds. Example: "1d2h3m4s567" means
1087    /// 1 day + 2 hours + 3 minutes + 4 seconds + 567 milliseconds.​
1088    pub log_interval: Duration,
1089}
1090
1091#[derive(Subcommand, Debug)]
1092pub enum SubCommands {
1093    #[command(subcommand)]
1094    Analyze(analyze::SubCommands),
1095    #[command(subcommand)]
1096    Bench(bench::SubCommands),
1097    #[command(subcommand)]
1098    Build(build::SubCommands),
1099    #[command(subcommand)]
1100    Check(check::SubCommands),
1101    #[command(subcommand)]
1102    From(from::SubCommands),
1103    #[command(subcommand)]
1104    Perm(perm::SubCommands),
1105    #[command(subcommand)]
1106    Run(run::SubCommands),
1107    #[command(subcommand)]
1108    Seq(seq::SubCommands),
1109    #[command(subcommand)]
1110    To(to::SubCommands),
1111    #[command(subcommand)]
1112    Transform(transform::SubCommands),
1113}
1114
1115#[derive(Parser, Debug)]
1116#[command(name = "webgraph", version=build_info::version_string(), max_term_width = 100, after_help = include_str!("common_env.txt"))]
1117/// WebGraph tools to build, convert, modify, and analyze graphs.​
1118pub struct Cli {
1119    #[command(subcommand)]
1120    pub command: SubCommands,
1121}
1122
1123pub mod dist;
1124pub mod rank;
1125pub mod sccs;
1126
1127pub mod analyze;
1128pub mod bench;
1129pub mod build;
1130pub mod check;
1131pub mod from;
1132pub mod perm;
1133pub mod run;
1134pub mod seq;
1135pub mod to;
1136pub mod transform;
1137
1138/// The entry point of the command-line interface.
1139pub fn cli_main<I, T>(args: I) -> Result<()>
1140where
1141    I: IntoIterator<Item = T>,
1142    T: Into<std::ffi::OsString> + Clone,
1143{
1144    timed(|| match Cli::parse_from(args).command {
1145        SubCommands::Analyze(args) => analyze::main(args),
1146        SubCommands::Bench(args) => bench::main(args),
1147        SubCommands::Build(args) => build::main(args, Cli::command()),
1148        SubCommands::Check(args) => check::main(args),
1149        SubCommands::From(args) => from::main(args),
1150        SubCommands::Perm(args) => perm::main(args),
1151        SubCommands::Run(args) => run::main(args),
1152        SubCommands::Seq(args) => seq::main(args),
1153        SubCommands::To(args) => to::main(args),
1154        SubCommands::Transform(args) => transform::main(args),
1155    })
1156}
1157
1158/// Runs a command (including the parsing of its arguments), logging how long
1159/// it took.
1160fn timed(command: impl FnOnce() -> Result<()>) -> Result<()> {
1161    let start = std::time::Instant::now();
1162    command()?;
1163    log::info!(
1164        "The command took {}",
1165        pretty_print_elapsed(start.elapsed().as_secs_f64())
1166    );
1167    Ok(())
1168}
1169
1170/// Pretty-prints seconds in a human-readable format.
1171fn pretty_print_elapsed(elapsed: f64) -> String {
1172    let mut result = String::new();
1173    let mut elapsed_seconds = elapsed as u64;
1174    let weeks = elapsed_seconds / (60 * 60 * 24 * 7);
1175    elapsed_seconds %= 60 * 60 * 24 * 7;
1176    let days = elapsed_seconds / (60 * 60 * 24);
1177    elapsed_seconds %= 60 * 60 * 24;
1178    let hours = elapsed_seconds / (60 * 60);
1179    elapsed_seconds %= 60 * 60;
1180    let minutes = elapsed_seconds / 60;
1181    //elapsed_seconds %= 60;
1182
1183    match weeks {
1184        0 => {}
1185        1 => result.push_str("1 week "),
1186        _ => result.push_str(&format!("{} weeks ", weeks)),
1187    }
1188    match days {
1189        0 => {}
1190        1 => result.push_str("1 day "),
1191        _ => result.push_str(&format!("{} days ", days)),
1192    }
1193    match hours {
1194        0 => {}
1195        1 => result.push_str("1 hour "),
1196        _ => result.push_str(&format!("{} hours ", hours)),
1197    }
1198    match minutes {
1199        0 => {}
1200        1 => result.push_str("1 minute "),
1201        _ => result.push_str(&format!("{} minutes ", minutes)),
1202    }
1203
1204    result.push_str(&format!("{:.3} seconds ({}s)", elapsed % 60.0, elapsed));
1205    result
1206}