1#![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
52macro_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#[macro_export]
101macro_rules! par_comp {
102 ($config:expr, $graph:expr, $endianness:expr) => {
103 $crate::__par_comp_dispatch(&mut $config, $graph, $endianness.as_str())
108 };
109}
110
111pub 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#[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#[derive(Args, Debug)]
207pub struct ArcsArgs {
208 #[arg(long, default_value_t = '#')]
209 pub line_comment_symbol: char,
211
212 #[arg(long, default_value_t = 0)]
213 pub lines_to_skip: usize,
215
216 #[arg(long)]
217 pub max_arcs: Option<usize>,
220
221 #[arg(long, default_value_t = '\t')]
222 pub separator: char,
224
225 #[arg(long, default_value_t = 0)]
226 pub source_column: usize,
228
229 #[arg(long, default_value_t = 1)]
230 pub target_column: usize,
232
233 #[arg(long, default_value_t = false)]
234 pub labels: bool,
237}
238
239pub 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#[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 pub num_threads: usize,
255}
256
257#[derive(Args, Debug)]
259pub struct GranularityArgs {
260 #[arg(long, conflicts_with("node_granularity"))]
261 pub arc_granularity: Option<u64>,
264
265 #[arg(long, conflicts_with("arc_granularity"))]
266 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#[derive(Args, Debug)]
298pub struct MemoryUsageArg {
299 #[clap(short = 'm', long = "memory-usage", value_parser = memory_usage_parser, default_value = "auto")]
300 pub memory_usage: MemoryUsage,
304}
305
306#[derive(Debug, Clone, Copy, Default, ValueEnum)]
308pub enum FloatSliceFormat {
309 Java,
311 Epserde,
313 #[default]
315 Ascii,
316 Json,
318}
319
320impl FloatSliceFormat {
321 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 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#[derive(Debug, Clone, Copy, Default, ValueEnum)]
437pub enum IntSliceFormat {
438 #[cfg(target_pointer_width = "64")]
439 Java,
441 Epserde,
443 BitFieldVec,
447 #[default]
449 Ascii,
450 Json,
452}
453
454pub enum IntSlice {
480 Owned(Box<[usize]>),
482 #[cfg(target_pointer_width = "64")]
483 Java(JavaPermutation),
485 Epserde(MemCase<Box<[usize]>>),
487 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#[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 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 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
645fn 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
653fn 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
664fn 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
674fn 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
696fn 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
704pub 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
769pub 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#[derive(Args, Debug, Clone)]
782pub struct CompressArgs {
783 #[clap(short = 'E', long)]
785 pub endianness: Option<String>,
786
787 #[clap(short = 'w', long, default_value_t = 7)]
789 pub compression_window: usize,
790 #[clap(short = 'i', long, default_value_t = 4)]
792 pub min_interval_length: usize,
793 #[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 pub outdegrees: PrivCode,
801
802 #[arg(value_enum)]
803 #[clap(long, default_value = "unary")]
804 pub references: PrivCode,
806
807 #[arg(value_enum)]
808 #[clap(long, default_value = "gamma")]
809 pub blocks: PrivCode,
811
812 #[arg(value_enum)]
813 #[clap(long, default_value = "zeta3")]
814 pub residuals: PrivCode,
816
817 #[clap(long)]
820 pub bvgraphz: bool,
821
822 #[clap(long, default_value = "10000")]
824 pub chunk_size: usize,
825}
826
827impl CompressArgs {
828 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 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
877pub 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
889pub fn create_parent_dir(file_path: impl AsRef<Path>) -> Result<()> {
891 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
903pub 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
947pub 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
968pub 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
998fn 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
1037pub 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#[derive(Args, Debug, Clone)]
1082pub struct LogIntervalArg {
1083 #[arg(long, value_parser = parse_duration, default_value = "10s")]
1084 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"))]
1117pub 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
1138pub 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
1158fn 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
1170fn 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 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}