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

vigna / webgraph-rs / 20724877148

05 Jan 2026 06:16PM UTC coverage: 62.048% (-0.02%) from 62.07%
20724877148

push

github

web-flow
Merge pull request #160 from progval/patch-2

Fix typo in docstring

5441 of 8769 relevant lines covered (62.05%)

43310641.57 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::{
12
    LenderIntoIter, RayonChannelIterExt, SequentialGraph, SortedIterator, SortedLender,
13
    SplitLabeling,
14
};
15
use crate::utils::sort_pairs::{KMergeIters, SortPairs};
16
use crate::utils::{CodecIter, DefaultBatchCodec, MemoryUsage};
17
use anyhow::{Context, Result};
18
use dsi_progress_logger::prelude::*;
19
use itertools::Itertools;
20
use lender::*;
21
use tempfile::Builder;
22

23
use super::transpose;
24

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

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

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

92
    Ok(sorted)
×
93
}
94

95
/// Returns a simplified (i.e., undirected and loopless) version of the provided
96
/// graph as a [sequential graph](crate::traits::SequentialGraph).
97
///
98
/// This method uses splitting to sort in parallel different parts of the graph.
99
///
100
/// For the meaning of the additional parameter, see [`SortPairs`].
101
pub fn simplify_split<S>(
4✔
102
    graph: &S,
103
    memory_usage: MemoryUsage,
104
) -> Result<
105
    Left<
106
        arc_list_graph::ArcListGraph<
107
            itertools::Dedup<KMergeIters<CodecIter<DefaultBatchCodec>, ()>>,
108
        >,
109
    >,
110
>
111
where
112
    S: SequentialGraph + SplitLabeling,
113
{
114
    let num_threads = rayon::current_num_threads();
8✔
115
    let (tx, rx) = crossbeam_channel::unbounded();
12✔
116

117
    let mut dirs = vec![];
8✔
118

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

150
    // get a graph on the sorted data
151
    log::debug!("Waiting for threads to finish");
4✔
152
    let edges: KMergeIters<CodecIter<DefaultBatchCodec>> = rx.into_rayon_iter().sum();
20✔
153
    let edges = edges.dedup();
12✔
154
    log::debug!("All threads finished");
4✔
155
    let sorted = arc_list_graph::ArcListGraph::new_labeled(graph.num_nodes(), edges);
20✔
156

157
    drop(dirs);
8✔
158
    Ok(Left(sorted))
4✔
159
}
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