• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vigna / webgraph-rs / 19076069272

04 Nov 2025 04:42PM UTC coverage: 61.785% (-0.2%) from 61.976%
19076069272

push

github

vigna
Fixed doctests

5143 of 8324 relevant lines covered (61.79%)

30278823.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.91
/webgraph/src/transform/simplify.rs
1
/*
2
 * SPDX-FileCopyrightText: 2023 Inria
3
 *
4
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
5
 */
6

7
use crate::graphs::{
8
    arc_list_graph, no_selfloops_graph::NoSelfLoopsGraph, union_graph::UnionGraph,
9
};
10
use crate::labels::Left;
11
use crate::traits::{LenderIntoIter, SequentialGraph, SortedIterator, SortedLender, SplitLabeling};
12
use crate::utils::sort_pairs::{BatchIterator, KMergeIters, SortPairs};
13
use crate::utils::MemoryUsage;
14
use anyhow::{Context, Result};
15
use dsi_progress_logger::prelude::*;
16
use itertools::Itertools;
17
use lender::*;
18
use rayon::ThreadPool;
19
use tempfile::Builder;
20

21
use super::transpose;
22

23
/// Returns a simplified (i.e., undirected and loopless) version of the provided
24
/// sorted (both on nodes and successors) graph as a [sequential
25
/// graph](crate::traits::SequentialGraph).
26
///
27
/// This method exploits the fact that the input graph is already sorted,
28
/// sorting half the number of arcs of
29
/// [`simplify`](crate::transform::simplify::simplify).
30
pub fn simplify_sorted<G: SequentialGraph>(
1✔
31
    graph: G,
32
    memory_usage: MemoryUsage,
33
) -> Result<
34
    NoSelfLoopsGraph<
35
        UnionGraph<G, Left<arc_list_graph::ArcListGraph<KMergeIters<BatchIterator<()>, ()>>>>,
36
    >,
37
>
38
where
39
    for<'a> G::Lender<'a>: SortedLender,
40
    for<'a, 'b> LenderIntoIter<'a, G::Lender<'b>>: SortedIterator,
41
{
42
    let transpose = transpose(&graph, memory_usage).context("Could not transpose the graph")?;
5✔
43
    Ok(NoSelfLoopsGraph(UnionGraph(graph, transpose)))
1✔
44
}
45

46
/// Returns a simplified (i.e., undirected and loopless) version of the provided
47
/// graph as a [sequential graph](crate::traits::SequentialGraph).
48
///
49
/// Note that if the graph is sorted (both on nodes and successors), it is
50
/// recommended to use [`simplify_sorted`](crate::transform::simplify::simplify_sorted).
51
///
52
/// For the meaning of the additional parameter, see
53
/// [`SortPairs`](crate::prelude::sort_pairs::SortPairs).
54
pub fn simplify(
×
55
    graph: &impl SequentialGraph,
56
    memory_usage: MemoryUsage,
57
) -> Result<
58
    Left<
59
        arc_list_graph::ArcListGraph<
60
            impl Iterator<Item = ((usize, usize), ())> + Clone + Send + Sync + 'static,
61
        >,
62
    >,
63
> {
64
    let dir = Builder::new().prefix("simplify_").tempdir()?;
×
65
    let mut sorted = SortPairs::new(memory_usage, dir.path())?;
×
66

67
    let mut pl = ProgressLogger::default();
×
68
    pl.item_name("node")
×
69
        .expected_updates(Some(graph.num_nodes()));
×
70
    pl.start("Creating batches...");
×
71
    // create batches of sorted edges
72
    let mut iter = graph.iter();
×
73
    while let Some((src, succ)) = iter.next() {
×
74
        for dst in succ {
×
75
            if src != dst {
×
76
                sorted.push(src, dst)?;
×
77
                sorted.push(dst, src)?;
×
78
            }
79
        }
80
        pl.light_update();
×
81
    }
82
    // merge the batches
83
    let map: fn(((usize, usize), ())) -> (usize, usize) = |(pair, _)| pair;
×
84
    let filter: fn(&(usize, usize)) -> bool = |(src, dst)| src != dst;
×
85
    let iter = Itertools::dedup(sorted.iter()?.map(map).filter(filter));
×
86
    let sorted = arc_list_graph::ArcListGraph::new(graph.num_nodes(), iter);
×
87
    pl.done();
×
88

89
    Ok(sorted)
×
90
}
91

92
/// Returns a simplified (i.e., undirected and loopless) version of the provided
93
/// graph as a [sequential graph](crate::traits::SequentialGraph).
94
///
95
/// This method uses splitting to sort in parallel different parts of the graph.
96
///
97
/// For the meaning of the additional parameter, see
98
/// [`SortPairs`](crate::prelude::sort_pairs::SortPairs).
99
pub fn simplify_split<S>(
4✔
100
    graph: &S,
101
    memory_usage: MemoryUsage,
102
    threads: &ThreadPool,
103
) -> Result<Left<arc_list_graph::ArcListGraph<itertools::Dedup<KMergeIters<BatchIterator<()>, ()>>>>>
104
where
105
    S: SequentialGraph + SplitLabeling,
106
{
107
    let num_threads = threads.current_num_threads();
12✔
108
    let (tx, rx) = std::sync::mpsc::channel();
12✔
109

110
    let mut dirs = vec![];
8✔
111

112
    threads.in_place_scope(|scope| {
12✔
113
        let mut thread_id = 0;
8✔
114
        #[allow(clippy::explicit_counter_loop)] // enumerate requires some extra bounds here
115
        for iter in graph.split_iter(num_threads) {
28✔
116
            let tx = tx.clone();
48✔
117
            let dir = Builder::new()
48✔
118
                .prefix(&format!("simplify_split_{thread_id}_"))
32✔
119
                .tempdir()
16✔
120
                .expect("Could not create a temporary directory");
32✔
121
            let dir_path = dir.path().to_path_buf();
48✔
122
            dirs.push(dir);
48✔
123
            scope.spawn(move |_| {
48✔
124
                log::debug!("Spawned thread {thread_id}");
16✔
125
                let mut sorted = SortPairs::new(memory_usage, dir_path).unwrap();
80✔
126
                for_!( (src, succ) in iter {
2,604,472✔
127
                    for dst in succ {
27,031,444✔
128
                        if src != dst {
25,379,448✔
129
                            sorted.push(src, dst).unwrap();
75,089,040✔
130
                            sorted.push(dst, src).unwrap();
50,059,360✔
131
                        }
132
                    }
133
                });
134
                let result = sorted.iter().context("Could not read arcs").unwrap();
80✔
135
                tx.send(result).expect("Could not send the sorted pairs");
80✔
136
                log::debug!("Thread {thread_id} finished");
16✔
137
            });
138
            thread_id += 1;
16✔
139
        }
140
    });
141
    drop(tx);
8✔
142

143
    // get a graph on the sorted data
144
    log::debug!("Waiting for threads to finish");
4✔
145
    let edges: KMergeIters<BatchIterator> = rx.iter().sum();
20✔
146
    let edges = edges.dedup();
12✔
147
    log::debug!("All threads finished");
4✔
148
    let sorted = arc_list_graph::ArcListGraph::new_labeled(graph.num_nodes(), edges);
20✔
149

150
    drop(dirs);
8✔
151
    Ok(Left(sorted))
4✔
152
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc