seqwish 0.1.3

A variation graph inducer - build pangenome graphs from pairwise alignments
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// seqwish: a variation graph inducer
//
// Complete Rust implementation of the seqwish algorithm for building
// variation graphs from pairwise alignments.

use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::sync::{Arc, Mutex};
use std::time::Instant;

use bitvec::prelude::*;
use clap::{Arg, Command};
use rayon;

mod alignments;
mod cigar;
mod compact;
mod dna;
mod dset64;
mod dset64_asm;
mod dset64_unsafe;
mod gfa;
mod intervaltree;
mod links;
mod mmap;
mod paf;
mod pos;
mod seqindex;
mod sxs;
mod tempfile;
mod time;
mod transclosure;
mod utils;
mod version;

use crate::alignments::unpack_paf_alignments;
use crate::compact::compact_nodes;
use crate::gfa::emit_gfa;
use crate::intervaltree::{AdaptiveTree, IntervalTree};
use crate::links::{derive_links, RankSelectBitVector};
use crate::seqindex::SeqIndex;
use crate::transclosure::compute_transitive_closures;

fn main() -> io::Result<()> {
    let matches = Command::new("seqwish")
        .version(version::get_version())
        .about("A variation graph inducer")
        .arg(Arg::new("paf-alns")
            .short('p')
            .long("paf-alns")
            .value_name("FILE")
            .help("Induce the graph from these PAF formatted alignments")
            .required(true))
        .arg(Arg::new("seqs")
            .short('s')
            .long("seqs")
            .value_name("FILE")
            .help("The sequences used to generate the alignments (FASTA, FASTQ, .seq)")
            .required(true))
        .arg(Arg::new("gfa")
            .short('g')
            .long("gfa")
            .value_name("FILE")
            .help("Write the graph in GFA to FILE (stdout if not specified)"))
        .arg(Arg::new("temp-dir")
            .short('b')
            .long("temp-dir")
            .value_name("PATH")
            .help("Directory for temporary files [default: current directory]"))
        .arg(Arg::new("threads")
            .short('t')
            .long("threads")
            .value_name("N")
            .help("Use this many threads during parallel steps")
            .default_value("1"))
        .arg(Arg::new("repeat-max")
            .short('r')
            .long("repeat-max")
            .value_name("N")
            .help("Limit transitive closure to include no more than N copies of a given input base")
            .default_value("0"))
        .arg(Arg::new("min-repeat-distance")
            .short('l')
            .long("min-repeat-distance")
            .value_name("N")
            .help("Prevent transitive closure for bases at least this far apart in input sequences")
            .default_value("0"))
        .arg(Arg::new("min-match-len")
            .short('k')
            .long("min-match-len")
            .value_name("N")
            .help("Filter exact matches below this length")
            .default_value("0"))
        .arg(Arg::new("sparse-factor")
            .short('f')
            .long("sparse-factor")
            .value_name("N")
            .help("Sparsify input matches, keeping the fraction that minimize a hash function")
            .default_value("0.0"))
        .arg(Arg::new("transclose-batch")
            .short('B')
            .long("transclose-batch")
            .value_name("N")
            .help("Number of bp to use for transitive closure batch")
            .default_value("1000000"))
        .arg(Arg::new("keep-temp")
            .short('T')
            .long("keep-temp")
            .help("Keep intermediate files generated during graph induction")
            .action(clap::ArgAction::SetTrue))
        .arg(Arg::new("show-progress")
            .short('P')
            .long("show-progress")
            .help("Log algorithm progress")
            .action(clap::ArgAction::SetTrue))
        .arg(Arg::new("in-memory")
            .short('M')
            .long("in-memory")
            .help("Use in-memory interval trees instead of disk-backed (faster for small datasets)")
            .action(clap::ArgAction::SetTrue))
        .get_matches();

    let start_time = Instant::now();

    // Parse arguments
    let paf_file = matches.get_one::<String>("paf-alns").unwrap();
    let seq_file = matches.get_one::<String>("seqs").unwrap();
    let gfa_file = matches.get_one::<String>("gfa");
    let num_threads: usize = matches
        .get_one::<String>("threads")
        .unwrap()
        .parse()
        .unwrap_or(1);

    // Configure Rayon's global thread pool to respect num_threads
    rayon::ThreadPoolBuilder::new()
        .num_threads(num_threads)
        .build_global()
        .unwrap();

    let repeat_max: u64 = matches
        .get_one::<String>("repeat-max")
        .unwrap()
        .parse()
        .unwrap_or(0);
    let min_repeat_dist: u64 = matches
        .get_one::<String>("min-repeat-distance")
        .unwrap()
        .parse()
        .unwrap_or(0);
    let min_match_len: u64 = matches
        .get_one::<String>("min-match-len")
        .unwrap()
        .parse()
        .unwrap_or(0);
    let sparse_factor: f32 = matches
        .get_one::<String>("sparse-factor")
        .unwrap()
        .parse()
        .unwrap_or(0.0);
    let transclose_batch: u64 = matches
        .get_one::<String>("transclose-batch")
        .unwrap()
        .parse()
        .unwrap_or(1000000);
    let keep_temp = matches.get_flag("keep-temp");
    let show_progress = matches.get_flag("show-progress");
    let use_in_memory = matches.get_flag("in-memory");

    // Set up temp directory
    if let Some(temp_dir) = matches.get_one::<String>("temp-dir") {
        tempfile::set_dir(temp_dir);
    }
    tempfile::set_keep_temp(keep_temp);

    // Check input files exist
    if !std::path::Path::new(seq_file).exists() {
        eprintln!(
            "[seqwish] ERROR: input sequence file {} does not exist",
            seq_file
        );
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            "sequence file not found",
        ));
    }
    if !std::path::Path::new(paf_file).exists() {
        eprintln!(
            "[seqwish] ERROR: input alignment file {} does not exist",
            paf_file
        );
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            "alignment file not found",
        ));
    }

    // 1) Build the sequence index
    if show_progress {
        eprintln!(
            "[seqwish::seqindex] {:.3} loading sequences",
            start_time.elapsed().as_secs_f64()
        );
    }
    let mut seqidx = SeqIndex::new();
    seqidx
        .build_index(seq_file)
        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
    let seqidx = Arc::new(seqidx);
    if show_progress {
        eprintln!(
            "[seqwish::seqindex] {:.3} loaded {} sequences",
            start_time.elapsed().as_secs_f64(),
            seqidx.n_seqs()
        );
    }

    // 2) Index alignments
    if show_progress {
        eprintln!(
            "[seqwish::alignments] {:.3} loading alignments",
            start_time.elapsed().as_secs_f64()
        );
    }
    let aln_iitree_idx = tempfile::create("seqwish-", ".sqa")?;
    let mut aln_iitree_obj = if use_in_memory {
        AdaptiveTree::new_memory()?
    } else {
        AdaptiveTree::new_disk(&aln_iitree_idx)?
    };
    aln_iitree_obj.open_writer()?;
    let aln_iitree = Arc::new(Mutex::new(aln_iitree_obj));

    unpack_paf_alignments(
        paf_file,
        Arc::clone(&aln_iitree),
        Arc::clone(&seqidx),
        min_match_len,
        sparse_factor,
        num_threads,
    )?;

    if show_progress {
        eprintln!(
            "[seqwish::alignments] {:.3} indexing",
            start_time.elapsed().as_secs_f64()
        );
    }
    aln_iitree.lock().unwrap().index()?;
    if show_progress {
        eprintln!(
            "[seqwish::alignments] {:.3} index built",
            start_time.elapsed().as_secs_f64()
        );
    }

    // Unwrap the Mutex - aln_iitree is now read-only, no need for mutex
    let aln_iitree_readonly = Arc::new(
        Arc::try_unwrap(aln_iitree)
            .map_err(|_| io::Error::new(io::ErrorKind::Other, "Failed to unwrap Arc"))?
            .into_inner()
            .unwrap(),
    );

    // 3) Find transitive closures and construct graph sequence
    if show_progress {
        eprintln!(
            "[seqwish::transclosure] {:.3} computing transitive closures",
            start_time.elapsed().as_secs_f64()
        );
    }
    let seq_v_file = tempfile::create("seqwish-", ".sqs")?;
    let node_iitree_idx = tempfile::create("seqwish-", ".sqn")?;
    let path_iitree_idx = tempfile::create("seqwish-", ".sqp")?;

    let mut node_iitree_obj = if use_in_memory {
        AdaptiveTree::new_memory()?
    } else {
        AdaptiveTree::new_disk(&node_iitree_idx)?
    };
    node_iitree_obj.open_writer()?;
    let node_iitree = Arc::new(std::sync::RwLock::new(node_iitree_obj));

    let mut path_iitree_obj = if use_in_memory {
        AdaptiveTree::new_memory()?
    } else {
        AdaptiveTree::new_disk(&path_iitree_idx)?
    };
    path_iitree_obj.open_writer()?;
    let path_iitree = Arc::new(std::sync::RwLock::new(path_iitree_obj));

    let graph_length = compute_transitive_closures(
        Arc::clone(&seqidx),
        Arc::clone(&aln_iitree_readonly),
        seq_v_file.to_str().unwrap(),
        Arc::clone(&node_iitree),
        Arc::clone(&path_iitree),
        repeat_max,
        min_repeat_dist,
        transclose_batch,
        show_progress,
        num_threads,
    )?;

    if show_progress {
        eprintln!(
            "[seqwish::transclosure] {:.3} done with transitive closures (graph length: {})",
            start_time.elapsed().as_secs_f64(),
            graph_length
        );
    }

    // 4) Compact nodes by marking boundaries
    if show_progress {
        eprintln!(
            "[seqwish::compact] {:.3} compacting nodes",
            start_time.elapsed().as_secs_f64()
        );
    }
    let mut seq_id_bv = BitVec::<u64, Lsb0>::repeat(false, graph_length + 1);

    compact_nodes(
        Arc::clone(&seqidx),
        graph_length,
        Arc::clone(&node_iitree),
        Arc::clone(&path_iitree),
        &mut seq_id_bv,
        num_threads,
    )?;

    if show_progress {
        eprintln!(
            "[seqwish::compact] {:.3} done compacting",
            start_time.elapsed().as_secs_f64()
        );
    }

    // Build rank/select structure
    let seq_id_cbv =
        RankSelectBitVector::from_bitvec(&seq_id_bv.iter().by_vals().collect::<Vec<bool>>());
    drop(seq_id_bv); // Free memory

    if show_progress {
        eprintln!(
            "[seqwish::compact] {:.3} built node index",
            start_time.elapsed().as_secs_f64()
        );
    }

    // 5) Derive links between nodes
    if show_progress {
        eprintln!(
            "[seqwish::links] {:.3} finding graph links",
            start_time.elapsed().as_secs_f64()
        );
    }

    let link_set = derive_links(
        Arc::clone(&seqidx),
        Arc::clone(&node_iitree),
        Arc::clone(&path_iitree),
        &seq_id_cbv,
        num_threads,
    )?;

    if show_progress {
        eprintln!(
            "[seqwish::links] {:.3} links derived ({} links)",
            start_time.elapsed().as_secs_f64(),
            link_set.len()
        );
    }

    // 6) Emit the graph in GFA format
    if show_progress {
        eprintln!(
            "[seqwish::gfa] {:.3} writing graph",
            start_time.elapsed().as_secs_f64()
        );
    }

    if let Some(gfa_path) = gfa_file {
        // Use large buffer (1MB) for GFA output to minimize write syscalls
        let mut out = BufWriter::with_capacity(1024 * 1024, File::create(gfa_path)?);
        emit_gfa(
            &mut out,
            graph_length,
            seq_v_file.to_str().unwrap(),
            Arc::clone(&node_iitree),
            Arc::clone(&path_iitree),
            &seq_id_cbv,
            Arc::clone(&seqidx),
            link_set.links(),
            num_threads,
        )?;
    } else {
        let stdout = io::stdout();
        // Use large buffer (1MB) for stdout GFA output to minimize write syscalls
        let mut out = BufWriter::with_capacity(1024 * 1024, stdout.lock());
        emit_gfa(
            &mut out,
            graph_length,
            seq_v_file.to_str().unwrap(),
            Arc::clone(&node_iitree),
            Arc::clone(&path_iitree),
            &seq_id_cbv,
            Arc::clone(&seqidx),
            link_set.links(),
            num_threads,
        )?;
    }

    if show_progress {
        eprintln!(
            "[seqwish::gfa] {:.3} done",
            start_time.elapsed().as_secs_f64()
        );
    }

    Ok(())
}