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

vigna / webgraph-rs / 19378243882

14 Nov 2025 09:34PM UTC coverage: 62.201% (+0.06%) from 62.146%
19378243882

push

github

vigna
Back to edition 2021

5251 of 8442 relevant lines covered (62.2%)

29314157.11 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::{KMergeIters, SortPairs};
13
use crate::utils::{CodecIter, DefaultBatchCodec, 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 [`simplify`].
29
pub fn simplify_sorted<G: SequentialGraph>(
1✔
30
    graph: G,
31
    memory_usage: MemoryUsage,
32
) -> Result<
33
    NoSelfLoopsGraph<
34
        UnionGraph<
35
            G,
36
            Left<arc_list_graph::ArcListGraph<KMergeIters<CodecIter<DefaultBatchCodec>, ()>>>,
37
        >,
38
    >,
39
>
40
where
41
    for<'a> G::Lender<'a>: SortedLender,
42
    for<'a, 'b> LenderIntoIter<'a, G::Lender<'b>>: SortedIterator,
43
{
44
    let transpose = transpose(&graph, memory_usage).context("Could not transpose the graph")?;
5✔
45
    Ok(NoSelfLoopsGraph(UnionGraph(graph, transpose)))
1✔
46
}
47

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

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

90
    Ok(sorted)
×
91
}
92

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

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

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

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

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