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

vigna / webgraph-rs / 11837625908

12 Nov 2024 07:33PM UTC coverage: 53.594% (-0.04%) from 53.631%
11837625908

push

github

vigna
No more Borrow

5 of 13 new or added lines in 6 files covered. (38.46%)

2 existing lines in 2 files now uncovered.

2371 of 4424 relevant lines covered (53.59%)

23193450.13 hits per line

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

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

8
use crate::cli::*;
9
use crate::graphs::union_graph::UnionGraph;
10
use crate::prelude::*;
11
use anyhow::Result;
12
use clap::{ArgMatches, Args, Command, FromArgMatches};
13
use dsi_bitstream::prelude::*;
14
use mmap_rs::MmapFlags;
15
use std::path::PathBuf;
16
use tempfile::Builder;
17

18
pub const COMMAND_NAME: &str = "simplify";
19

20
#[derive(Args, Debug)]
21
#[command(about = "Makes a BvGraph simple (undirected and loopless) by adding missing arcs and removing loops, optionally applying a permutation.", long_about = None)]
22
pub struct CliArgs {
23
    /// The basename of the graph.
24
    pub src: PathBuf,
25
    /// The basename of the simplified graph.
26
    pub dst: PathBuf,
27

28
    #[arg(long)]
29
    /// The basename of a pre-computed transposed version of the source graph, which
30
    /// will be use to speed up the simplification.
31
    pub transposed: Option<PathBuf>,
32

33
    #[clap(flatten)]
34
    pub num_threads: NumThreadsArg,
35

36
    #[clap(flatten)]
37
    pub batch_size: BatchSizeArg,
38

39
    #[clap(flatten)]
40
    pub ca: CompressArgs,
41

42
    #[arg(long)]
43
    /// The path to an optional permutation in binary big-endian format to apply to the graph.
44
    pub permutation: Option<PathBuf>,
45
}
46

47
pub fn cli(command: Command) -> Command {
18✔
48
    command.subcommand(CliArgs::augment_args(Command::new(COMMAND_NAME)).display_order(0))
18✔
49
}
50

51
pub fn main(submatches: &ArgMatches) -> Result<()> {
2✔
52
    let args = CliArgs::from_arg_matches(submatches)?;
4✔
53

54
    create_parent_dir(&args.dst)?;
×
55

56
    match get_endianness(&args.src)?.as_str() {
4✔
57
        #[cfg(any(
58
            feature = "be_bins",
59
            not(any(feature = "be_bins", feature = "le_bins"))
60
        ))]
61
        BE::NAME => simplify::<BE>(args),
4✔
62
        #[cfg(any(
63
            feature = "le_bins",
64
            not(any(feature = "be_bins", feature = "le_bins"))
65
        ))]
66
        LE::NAME => simplify::<LE>(args),
×
67
        e => panic!("Unknown endianness: {}", e),
×
68
    }
69
}
70

71
fn no_ef_warn(basepath: impl AsRef<std::path::Path>) {
2✔
72
    log::warn!("The .ef file was not found so the simplification will proceed sequentially. This may be slow. To speed it up, you can use `webgraph build ef {}` which would allow us create batches in parallel", basepath.as_ref().display());
4✔
73
}
74

75
pub fn simplify<E: Endianness + Send + Sync + 'static>(args: CliArgs) -> Result<()>
2✔
76
where
77
    for<'a> BufBitReader<E, MemWordReader<u32, &'a [u32]>>: CodeRead<E> + BitSeek,
78
{
79
    // TODO!: speed it up by using random access graph if possible
80
    let thread_pool = crate::cli::get_thread_pool(args.num_threads.num_threads);
2✔
81

82
    let target_endianness = args.ca.endianness.clone().unwrap_or_else(|| E::NAME.into());
6✔
83

84
    let dir = Builder::new().prefix("transform_simplify_").tempdir()?;
4✔
85

86
    match (args.permutation, args.transposed) {
×
87
        // load the transposed graph and use it to directly compress the graph
88
        // without doing any sorting
89
        (None, Some(t_path)) => {
×
90
            log::info!("Transposed graph provided, using it to simplify the graph");
×
91

92
            let has_ef_graph =
×
93
                std::fs::metadata(args.src.with_extension(".ef")).is_ok_and(|x| x.is_file());
×
94
            let has_ef_t_graph =
×
95
                std::fs::metadata(t_path.with_extension(".ef")).is_ok_and(|x| x.is_file());
×
96

97
            match (has_ef_graph, has_ef_t_graph) {
×
98
                (true, true) => {
×
99
                    log::info!("Both .ef files found, using simplify split");
×
100

101
                    let graph =
×
102
                        crate::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
×
103
                            .endianness::<E>()
104
                            .load()?;
105
                    let num_nodes = graph.num_nodes();
×
106
                    let graph_t =
×
107
                        crate::graphs::bvgraph::random_access::BvGraph::with_basename(&t_path)
×
108
                            .endianness::<E>()
109
                            .load()?;
110

111
                    if graph_t.num_nodes() != num_nodes {
×
112
                        anyhow::bail!("The number of nodes in the graph and its transpose do not match! {} != {}", num_nodes, graph_t.num_nodes());
×
113
                    }
114

115
                    let sorted = NoSelfLoopsGraph(UnionGraph(graph, graph_t));
×
116

117
                    BvComp::parallel_endianness(
118
                        &args.dst,
×
119
                        &sorted,
×
120
                        num_nodes,
×
121
                        args.ca.into(),
×
122
                        &thread_pool,
×
123
                        dir,
×
124
                        &target_endianness,
×
125
                    )?;
126

127
                    return Ok(());
×
128
                }
129
                (true, false) => {
×
130
                    no_ef_warn(&args.src);
×
131
                }
132
                (false, true) => {
×
133
                    no_ef_warn(&t_path);
×
134
                }
135
                (false, false) => {
×
136
                    no_ef_warn(&args.src);
×
137
                    no_ef_warn(&t_path);
×
138
                }
139
            }
140

141
            let seq_graph =
×
142
                crate::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.src)
×
143
                    .endianness::<E>()
144
                    .load()?;
145
            let num_nodes = seq_graph.num_nodes();
×
146
            let seq_graph_t =
×
147
                crate::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&t_path)
×
148
                    .endianness::<E>()
149
                    .load()?;
150

151
            if seq_graph_t.num_nodes() != num_nodes {
×
152
                anyhow::bail!(
×
153
                    "The number of nodes in the graph and its transpose do not match! {} != {}",
×
154
                    num_nodes,
×
155
                    seq_graph_t.num_nodes()
×
156
                );
157
            }
158

159
            let sorted = NoSelfLoopsGraph(UnionGraph(seq_graph, seq_graph_t));
×
160

161
            BvComp::parallel_endianness(
162
                &args.dst,
×
163
                &sorted,
×
164
                num_nodes,
×
165
                args.ca.into(),
×
166
                &thread_pool,
×
167
                dir,
×
168
                &target_endianness,
×
169
            )?;
170
        }
171
        // apply the permutation, don't care if the transposed graph is already computed
172
        // as we cannot really exploit it
173
        (Some(perm_path), None | Some(_)) => {
2✔
174
            log::info!("Permutation provided, applying it to the graph");
4✔
175

176
            let perm = JavaPermutation::mmap(perm_path, MmapFlags::RANDOM_ACCESS)?;
4✔
177

178
            // if the .ef file exists, we can use the simplify split
179
            if std::fs::metadata(args.src.with_extension(".ef")).is_ok_and(|x| x.is_file()) {
×
180
                log::info!(".ef file found, using simplify split");
×
181
                let graph =
×
182
                    crate::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
×
183
                        .endianness::<E>()
184
                        .load()?;
185

186
                let perm_graph = PermutedGraph {
187
                    graph: &graph,
×
188
                    perm: &perm,
×
189
                };
190

191
                let sorted = crate::transform::simplify_split(
192
                    &perm_graph,
×
193
                    args.batch_size.batch_size,
×
194
                    &thread_pool,
×
195
                )?;
196

197
                BvComp::parallel_endianness(
198
                    &args.dst,
×
199
                    &sorted,
×
200
                    graph.num_nodes(),
×
201
                    args.ca.into(),
×
NEW
202
                    &thread_pool,
×
203
                    dir,
×
204
                    &target_endianness,
×
205
                )?;
206

207
                return Ok(());
×
208
            }
209

210
            no_ef_warn(&args.src);
2✔
211

212
            let seq_graph =
2✔
213
                crate::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.src)
×
214
                    .endianness::<E>()
215
                    .load()?;
216

217
            let perm_graph = PermutedGraph {
218
                graph: &seq_graph,
×
219
                perm: &perm,
×
220
            };
221

222
            // simplify the graph
223
            let sorted =
×
224
                crate::transform::simplify(&perm_graph, args.batch_size.batch_size).unwrap();
×
225

226
            BvComp::parallel_endianness(
227
                &args.dst,
×
228
                &sorted,
×
229
                sorted.num_nodes(),
×
230
                args.ca.into(),
×
231
                &thread_pool,
×
232
                dir,
×
233
                &target_endianness,
×
234
            )?;
235
        }
236
        // just compute the transpose on the fly
237
        (None, None) => {
×
238
            log::info!(
×
239
                "No permutation or transposed graph provided, computing the transpose on the fly"
×
240
            );
241
            // if the .ef file exists, we can use the simplify split
242
            if std::fs::metadata(args.src.with_extension(".ef")).is_ok_and(|x| x.is_file()) {
×
243
                log::info!(".ef file found, using simplify split");
×
244

245
                let graph =
×
246
                    crate::graphs::bvgraph::random_access::BvGraph::with_basename(&args.src)
×
247
                        .endianness::<E>()
248
                        .load()?;
249

250
                let sorted = crate::transform::simplify_split(
251
                    &graph,
×
252
                    args.batch_size.batch_size,
×
253
                    &thread_pool,
×
254
                )?;
255

256
                BvComp::parallel_endianness(
257
                    &args.dst,
×
258
                    &sorted,
×
259
                    graph.num_nodes(),
×
260
                    args.ca.into(),
×
NEW
261
                    &thread_pool,
×
262
                    dir,
×
263
                    &target_endianness,
×
264
                )?;
265

266
                return Ok(());
×
267
            }
268

269
            no_ef_warn(&args.src);
×
270

271
            let seq_graph =
×
272
                crate::graphs::bvgraph::sequential::BvGraphSeq::with_basename(&args.src)
×
273
                    .endianness::<E>()
274
                    .load()?;
275

276
            // transpose the graph
277
            let sorted =
×
278
                crate::transform::simplify(&seq_graph, args.batch_size.batch_size).unwrap();
×
279

280
            BvComp::parallel_endianness(
281
                &args.dst,
×
282
                &sorted,
×
283
                seq_graph.num_nodes(),
×
284
                args.ca.into(),
×
NEW
285
                &thread_pool,
×
286
                dir,
×
287
                &target_endianness,
×
288
            )?;
289
        }
290
    }
291

292
    Ok(())
2✔
293
}
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